Search code examples
c#graphqlresponsehotchocolate

How can i receive a data from response using GraphQL and .NET


I need to get a text from response field (Banana Cake Pop) but don't get how to do it with GraphQL nuget. I've found code similar to

            var graphQLClient = new GraphQLHttpClient("url", new NewtonsoftJsonSerializer());

        graphQLClient.HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer token");
        graphQLClient.HttpClient.DefaultRequestHeaders.Add("Accept", "application/json");

        var heroRequest = new GraphQLRequest
        {
            Query = @"
            {query(
            $propIdArray: [Uuid!], $objectIdArray: [Uuid!], $ts: String){
                propertyViews(
                propIdArray: $propIdArray, objectIdArray: $objectIdArray, ts: $ts
                ) {
                id,
                value,
                valueTypeId
                }
            }}"
        };

        var graphQLResponse = await graphQLClient.SendQueryAsync<object>(heroRequest);

But it doesn't give me anything. The Banana Cake Pop page requset and variables and response looks like this banana cake pop screen


Solution

  • The solution turned out to be insanely simple. Just had to add a Variables property in heroRequest. Now request method looks like this

    var myRequest = new GraphQLRequest
            {
                Query = File.ReadAllText(path),
                Variables = new
                {
                    ts = string.Empty,
                    filterObject = new { parentId = $"{parentId}" },
                    sort = new { orders = new[] { new { direction = "ASC", property = "name" } } }
                }
            };
    
            var graphQLResponse = _graphQLClient.SendQueryAsync<object>(myRequest);