DEV Community

loading...

Using GraphQL .NET Client in .NET 5

mahdi profile image Mahdi Taghizadeh ・2 min read

GraphQL for .NET is one of the open-source libraries available both to create and consume a GraphQL API and there are dozens of blog posts and tutorials available to learn more about it.

In this quick post, I want to show you how to use GraphQL.Client and define the client in your Startup.cs and inject it into a controller in ASP.NET Web API.

Once you've created your Web API (or any other type of .NET project); you need to add its NuGet package:

dotnet add package GraphQL.Client --version 3.2.0
Enter fullscreen mode Exit fullscreen mode

If you want to use Newtonsoft.JSON, feel free to add that too

dotnet add package Newtonsoft.Json --version 12.0.3
Enter fullscreen mode Exit fullscreen mode

The next step is adding a GraphQLClient to your Startup services to be able to inject them into your controller later:

public void ConfigureServices(IServiceCollection services) {
            services.AddMicrosoftIdentityWebApiAuthentication(Configuration);

            var graphQlClient = new GraphQLHttpClient(Configuration.GetSection("MyGraphQLApi").GetSection("ApiUrl").Value, new NewtonsoftJsonSerializer());
            graphQlClient.HttpClient.DefaultRequestHeaders.Add("Authorization", Configuration.GetSection("MyGraphQLApi").GetSection("ApiToken").Value);
            services.AddScoped<IGraphQLClient>(x => graphQlClient);

            services.AddControllers();
}
Enter fullscreen mode Exit fullscreen mode

It's simply getting API URL and Token from "MyGraphQLApi" section in your appsettings.json file (so you don't need to repeatedly do this in your methods) and adds it to your services.

Then you can easily inject it into your controller:

private IGraphQLClient _mondayClient;
public MondayController(IGraphQLClient mondayClient) {
     _mondayClient = mondayClient;
}
Enter fullscreen mode Exit fullscreen mode

Now you can use this injected instance of GraphQLClient in your methods:

var request = new GraphQLRequest {
                Query = @"query Project($boardId: [Int], $groupId: [String], $columnsIds: [String])
                {
                    boards (ids: $boardId) {
                        name,
                        groups (ids: $groupId) {
                            id
                            title
                            items {
                                name
                                column_values (ids: $columnsIds) {
                                    id
                                    title
                                    value
                                }
                            }
                        }
                    }
                }",
                Variables = new { boardId = new List<int> { 379551383 }, groupId = new List<string> { "new_group80740" }, columnsIds = new List<string>() { "text73", "text7" } }
            };

var response = await _mondayClient.SendQueryAsync<Data>(request);
Enter fullscreen mode Exit fullscreen mode

In the example above I'm getting some data from Monday.com API and I've passed parameters using Variables.

If you have a complicated data model returned in JSON, you can use tools like JSONUtils or JSON2CSharp to generate your model classes from the JSON and use it to deserialize the response to objects.

Enjoy!

Discussion (0)

pic
Editor guide