Can I send GraphQL queries with an httpclient in .NET core?

7.1k views Asked by At

Is it possible to send graphQL queries with the standard httpclient in .NET core? When I try to send my query with a client.post I get "Expected { or [ as first syntax token."

How can I send GraphQL queries with a httpclient. Without having to use a library (like GraphQLHttpClient etc..)

2

There are 2 answers

1
Enrico On BEST ANSWER

Got it: Just add "query" as a json object. Like this:

{"query" : "query { __schema { queryType { name } mutationType { name } types { name } directives { name } } }"}

In .NET you can use this in an HTTP post (don't forget to string escape the double quotes

private static string myquery = "{ \"query\" : \"query { __schema { queryType { name } mutationType { name } types { name } directives { name } } }\" }";
0
Moslem Hadi On

Here's an example of how to call a GraphQL endpoint with HttpClient in .net Core:

public async Task<string> GetProductsData(string userId, string authToken)
{
    var httpClient = new HttpClient
    {
        BaseAddress = new Uri(_apiUrl)
    };

    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);

    var queryObject = new
    {
        query = @"query Products {
            products {
            id
            description
            title
            }
        }",
        variables = new { where = new { userId = userId } }//you can add your where cluase here.
    };

    var request = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        Content = new StringContent(JsonConvert.SerializeObject(queryObject), Encoding.UTF8, "application/json")
    };

    using (var response = await httpClient.SendAsync(request))
    {
        response.EnsureSuccessStatusCode();
        var responseString = await response.Content.ReadAsStringAsync();
        return responseString;
    }
}