0

I'm a Unity developer tool and i want to post a GraphQL request with using System.Net.Http; (i don't want to use the GraphQL dll because there are compatibility problems).

But i have this error (got on the Debug.Log) :

POST body missing, invalid Content-Type, or JSON object has no keys.

My code :

static async Task<string> getEntityID(string path)
{
    var values = new Dictionary<string, string>
      {
          { "query", "query {topLevelEntityTypes {id}}" },
          { "variables", "{}" }
      };

    var content = new FormUrlEncodedContent(values);
    var response = await client.PostAsync("http://localhost:4000/graphql", content);
    var responseString = await response.Content.ReadAsStringAsync();

    Debug.Log(responseString);
    return responseString;
}

Thank you !

Isaac
  • 7
  • 2
  • It sounds like the API is expecting JSON, but you're passing form-encoded content instead. – ProgrammingLlama Nov 04 '22 at 10:23
  • Why do you have Q in your JSON? Your JSON should either start with `"`, `[`, `{`, `t`, `f`, `-`, maybe `+` (not 100% sure), or a digit. To me it sounds like you didn't actually send JSON. I'm guessing you probably sent the same content as you're currently sending but lied to the API and said "this is application/json" even though it isn't. Does that sound about right? – ProgrammingLlama Nov 04 '22 at 10:47
  • https://stackoverflow.com/questions/6117101/posting-jsonobject-with-httpclient-from-web-api – ProgrammingLlama Nov 04 '22 at 10:50
  • Ok we just used the wrong method to convert the JSON, thank you that work !! – Isaac Nov 04 '22 at 10:52

1 Answers1

0

Solution by ProgrammingLlama :

static async Task<string> getEntityID(string path)
{
    var myObject = new QueryJson();
    myObject.query = "query {topLevelEntityTypes {id}}";
    myObject.variables = "{}";

    var response = await client.PostAsync("http://localhost:4000/graphql", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(myObject), Encoding.UTF8, "application/json"));
    var responseString = await response.Content.ReadAsStringAsync();

    Debug.Log(responseString);
    return responseString;
}

Class json

internal class QueryJson
    {
        public string query { get; set; }
        public string variables { get; set; }
    }
Isaac
  • 7
  • 2