Reputation: 3461
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..)
Upvotes: 2
Views: 9767
Reputation: 1020
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;
}
}
Upvotes: 5
Reputation: 3461
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 } } }\" }";
Upvotes: 4