Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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..)

like image 451
Enrico Avatar asked Nov 16 '25 09:11

Enrico


1 Answers

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 clause 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;
    }
}
like image 55
Moslem Hady Avatar answered Nov 19 '25 10:11

Moslem Hady



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!