Guest Frank Boucher Posted July 11, 2024 Posted July 11, 2024 Most (if not all) projects are consuming APIs to get data, and there many ways to do it. One of the most popular ways is to use REST APIs. However, REST APIs have some limitations, such as over-fetching (forcing the client to load all properties even when only a few are needed for the UI). GraphQL is a great alternative to REST APIs because it allows you to request only the data you need, which can help reduce the amount of data transferred over the network and improve performance. It also allows you to request information coming from multiple resources in a single request, thus avoiding multiple “round trips” that can negatively impact performance and the user experience. In this post, I will show you how to query a GraphQL API in .NET using Strawberry Shake GraphQL client. With Strawberry Shake version 13 there are now 3 packages: StrawberryShake.Server: For consoles or backend-to-backend. StrawberryShake.Blazor: For Blazor projects, use this package in your project, and we pre-configured it to generate Razor components automatically and use a client-side store for reactive web applications. StrawberryShake.Maui: For Maui projects. This post will familiarize you with GraphQL in a .NET application, and will provide you with context to better understand the Blazor and Maui implementations if you are using those technologies. Note: You can find the code for this post in the startrek-demo GitHub repo. [HEADING=1]Let’s create the console application[/HEADING] In a terminal, execute the following command to create a new project, move into the new folder created, and add Strawberry Shake nuget package to the project. dotnet new console -n GraphqlDemo --use-program-main cd .\startrekdemo\ dotnet add package StrawberryShake.Server Strawberry Shake comes with tools to help improve your experience building a GraphQL client. You install tools in .NET projects by providing a manifest. Let’s create a dotnet-tools manifest and add the GraphQL tool locally. We will see what is created in a few steps. dotnet new tool-manifest dotnet tool install StrawberryShake.Tools --local In GraphQL, APIs are defined by a schema. This is similar to how OpenAPI is used to document REST endpoints. Like OpenAPI, you can use the schema to generate the code for .NET clients that are ready “out of the box” to consume their owned data. This is how Strawberry Shake will generate a client for us based on the schema. To download the GraphQL schema and generate the client code specifying the client name “StartrekClient”, run the following command: [iCODE]dotnet graphql init http://localhost:5000/graphql -n StartrekClient[/iCODE] It’s finally time to open the project and look at what we have… Note the generated files: [iCODE].config\dotnet-tools.json[/iCODE] [iCODE].graphqlrc.json[/iCODE] with our client’s name StartrekClient [iCODE]schema.extensions.graphql[/iCODE] [iCODE]schema.graphql[/iCODE] [HEADING=1]Adding a new query[/HEADING] In the current database I have 3 tables: Series, Character, and a relation table Series_Character. The schema is as follows: With a REST API, the typical design is to provide an endpoint with a list of series and another with a list of characters in the series. A client would need to make multiple requests in order to get the characters for multiple series. GraphQL enables you to retrieve all of this data in a single call! Banana Cake Pop is a nice GraphQL IDE for Developers, a bit like Swagger for REST APIs. You can learn more about it and Data API Builder in this session that I did with Jerry Nixon during Developer .NET Day . To add a new query, create a new file [iCODE]getCharacterbySeries.graphql[/iCODE] in the root of the project. Here is a query that will return a list of series with the characters for each series. query getCharacterbySeries{ series { items { Name character { items { Name } } } } } The syntax looks similar to JSON, but is in fact specific to GraphQL. Looking at the tables diagram, notice that the query doesn’t contain the property [iCODE]StartDate[/iCODE] from the [iCODE]Character[/iCODE] table. With bigger tables, this can be a huge performance gain, as the client avoid over-fetching data that isn’t used. After compiling the project [iCODE]dotnet build[/iCODE], you can see the generated the GraphQL client in [iCODE]obj\Debug\net8.0\berry\GraphqlDemo.Client.cs[/iCODE]. This is one of the changes that Strawberry Shake made in version 13. The generated code is now in a folder called [iCODE]berry[/iCODE] and not in the [iCODE]Generated[/iCODE] folder as before. [HEADING=1]Using the generated GraphQL client[/HEADING] Open the file [iCODE]Program.cs[/iCODE] file. Add the using for dependency injection at the top of the file. [iCODE]using Microsoft.Extensions.DependencyInjection;[/iCODE] Let’s modify [iCODE]Main[/iCODE] with the following code to create an instance of the StartrekClient (aka the GraphQL client). static async Task Main(string[] args) { var servicesCollection = new ServiceCollection(); servicesCollection.AddStartrekClient().ConfigureHttpClient(client => { client.BaseAddress = new Uri("http://localhost:5000/graphql"); }); var services = servicesCollection.BuildServiceProvider(); var client = services.GetRequiredService<IStartrekClient>(); // Execute the query GetCharacterbySeries var result = await client.GetCharacterbySeries.ExecuteAsync(); // Loop through the series and characters to display the results foreach (var tvShow in result.Data.Series.Items) { Console.WriteLine($"Series: {tvShow.Name}"); foreach (var character in tvShow.Character.Items) { Console.WriteLine($" . {character.Name}"); } } } The few last lines of [iCODE]Main[/iCODE] are looping through query results and display the information. Executing the code [iCODE]dotnet run[/iCODE], will write a list of series with the characters for each series. [HEADING=1]What’s Next?[/HEADING] In this post, I showed you how to query a GraphQL API in .NET using Strawberry Shake from a console application. I hope you found this post helpful and that you are now ready to start using GraphQL in your .NET projects. In the next post, let’s explore how we can execute GraphQL queries in a Blazor project and display the result using the new QuickGrid. The post Why and How to Execute GraphQL Queries in .NET appeared first on .NET Blog. Continue reading... Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.