What is GraphQL?
GraphQL is a query language and runtime for APIs (Application Programming Interfaces). It allows clients to request exactly the data they need, and nothing more. This is in contrast to REST (Representational State Transfer), which often requires clients to make multiple requests to fetch related data, or to receive more data than they actually need.
GraphQL also provides a strongly-typed schema that defines the types and fields of the data available in the API. This schema can be used to validate queries at compile-time, and to generate documentation and type-safe client code.
Why Use GraphQL in ASP.NET Core?
ASP.NET Core is a popular web framework for building web applications and APIs. It includes support for building RESTful APIs using controllers and action methods.
However, RESTful APIs can sometimes be inefficient, especially when dealing with complex or hierarchical data. GraphQL can help address these issues by allowing clients to request exactly the data they need, in a single request.
Additionally, GraphQL can make it easier to evolve the API over time, without breaking existing clients. This is because clients can specify exactly what data they need, and the API can change the data schema without affecting clients that don’t need the changed data.
Installing the Required Packages
To use GraphQL in ASP.NET Core, we’ll need to install the following packages:
GraphQL
– the main GraphQL package for .NETGraphQL.Server
– a package that provides middleware for handling GraphQL requests in ASP.NET CoreGraphQL.Server.Ui.GraphiQL
– a package that provides a graphical interface for exploring and testing GraphQL APIs
You can install these packages using the dotnet add package
command in your project directory, like this:
dotnet add package GraphQL
dotnet add package GraphQL.Server
dotnet add package GraphQL.Server.Ui.GraphiQL
Creating the GraphQL Schema
The first step in using GraphQL in ASP.NET Core is to define the GraphQL schema. This schema defines the types and fields of the data available in the API.
You can define the schema using the SchemaBuilder
class provided by the GraphQL
package. Here’s an example of a simple schema that defines a Person
type with id
, name
, and age
fields:
using GraphQL.Types;
public class PersonType : ObjectGraphType<Person>
{
public PersonType()
{
Field(x => x.Id, type: typeof(IdGraphType)).Description("The ID of the person.");
Field(x => x.Name).Description("The name of the person.");
Field(x => x.Age, nullable: true).Description("The age of the person.");
}
}
public class Query : ObjectGraphType
{
public Query()
{
Field<PersonType>(
name: "person",
description: "Get a person by ID.",
arguments: new QueryArguments(
new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "id", Description = "The ID of the person." }
),
resolve: context =>
{
var id = context.GetArgument<int>("id");
return GetPersonById(id);
}
);
}
private Person GetPersonById(int id)
{
// TODO: Implement method to get person by ID.
}
}
This schema defines a PersonType
class that inherits from ObjectGraphType<Person>
, and a Query
class that inherits from ObjectGraphType
.
The PersonType
class defines the fields of the Person
type using the Field
method.
This field takes a required argument called id
of type ID
. The resolve
function is called to fetch the data for this field. In this example, it calls the GetPersonById
method to retrieve the person with the given ID.
Creating the GraphQL Middleware
The next step is to create the GraphQL middleware that will handle incoming GraphQL requests. This middleware can be added to the ASP.NET Core pipeline using the UseGraphQL
extension method provided by the GraphQL.Server
package.
Here’s an example of how to add the GraphQL middleware to your ASP.NET Core application:
using GraphQL;
using GraphQL.Http;
using GraphQL.Server;
using GraphQL.Types;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Add GraphQL services.
services.AddSingleton<IDocumentExecuter, DocumentExecuter>();
services.AddSingleton<IDocumentWriter, DocumentWriter>();
services.AddSingleton<ISchema, MySchema>();
services.AddSingleton<MyQuery>();
services.AddSingleton<PersonType>();
services.AddSingleton<IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));
services.AddGraphQL();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseGraphQL<MySchema>();
app.UseGraphQLPlayground();
}
}
This code registers the required services and types with the ASP.NET Core dependency injection container, and adds the GraphQL middleware to the pipeline using the UseGraphQL
method. It also adds the GraphQL Playground middleware using the UseGraphQLPlayground
method, which provides a graphical interface for exploring and testing GraphQL APIs.
Testing the GraphQL API
With the GraphQL middleware added to the pipeline, we can now test the API using GraphiQL or a similar tool.
To access GraphiQL, navigate to the URL /graphql/ui
in your web browser. This should bring up the GraphiQL interface, which allows you to explore the schema and test queries.
Here’s an example of a query you can run in GraphiQL to fetch a person by ID:
graphqlCopy code<code>query {
person(id: 1) {
id
name
age
}
}
</code>
This query requests the person
field with the id
argument set to 1
, and requests the id
, name
, and age
fields of the returned Person
object.
Conclusion
In this article, we’ve learned how to use GraphQL in ASP.NET Core by creating a schema, adding the GraphQL middleware to the pipeline, and testing the API using GraphiQL.
While this is just a simple example, it should provide a good starting point for exploring the power and flexibility of GraphQL in your own ASP.NET Core applications.
Laisser un commentaire