[Yugong Series] July 2023 .NET CORE tool case - GraphQL.Server (basic use)


foreword

1. The concept of GraphQL

GraphQL is a query language and runtime environment for APIs. It was used internally by Facebook in 2012, and it was announced as open source in 2015. GraphQL aims to solve some limitations of RESTful API, such as multiple requests are required to obtain complete data, it is difficult to expand, and it is impossible to precisely control data return.

The core concept of GraphQL is: the client defines the structure and relationship required by the data, and the server returns the data that matches this structure. Therefore, GraphQL is very suitable for applications where the front and back ends are separated, and the client can precisely control the data returned, improving the reliability and flexibility of the API.

2. GraphQL application scenarios and usage process

The specific application scenarios of GraphQL are as follows:

  1. Application of front-end and back-end separation

  2. Mobile App Backend API

  3. Multi-language (multi-platform) supported API

  4. Large API architecture

The detailed usage process of GraphQL is as follows:

  1. Define Schema: Schema defines all available queries, relationships, and data types, which can be understood as GraphQL API documents.

  2. Define Resolver: Resolver is the code used to actually obtain data, and obtain actual data according to the query fields in the Schema.

  3. Write a query: Write a query according to your needs. The query can contain multiple fields and parameters, and can be nested.

  4. Send query: use the GraphQL client to send a query request and return the data matching the query.

  5. Handling errors: Error handling is an important aspect of GraphQL. Errors are managed by using error handlers and exception catching.

GraphQL is a powerful and flexible API development tool. Through its unique query language and runtime environment, it can greatly improve the usability and flexibility of API, and is an important choice for API development.

3. Comparison between RESTful API and GraphQL

Both RESTful API and GraphQL are tools for building web APIs, but they have some different characteristics.

  1. Data acquisition method

RESTful API is an HTTP-based protocol that uses HTTP verbs (GET, POST, PUT, DELETE, etc.) to get or modify data. Each resource has a unique URI, and each verb corresponds to a specific action. RESTful API responses are based on the URI and verbs in the request and cannot cross these boundaries.

GraphQL uses a single endpoint to fetch and modify data, using a query language to specify the desired data. GraphQL allows clients to request precise data, rather than just returning entire resources.

  1. query efficiency

One disadvantage of RESTful API is that when multiple resources need to be obtained, multiple HTTP requests need to be made. This "resource waterfall" approach results in latency and bandwidth consumption for multiple requests, limiting application performance.

GraphQL allows multiple resources to be obtained in one request, and can specify the required fields and relationships, avoiding unnecessary data transmission and making it more efficient.

  1. Caching and Versioning

RESTful APIs typically use HTTP standard caching mechanisms (for example, using Last-Modified and ETag headers) to reduce bandwidth and server load. RESTful API also supports version control, which can better manage API changes.

GraphQL has no built-in caching mechanism, but other caching mechanisms (for example, HTTP caching) can be used to cache GraphQL queries. Versioning is usually managed by the client, and GraphQL returns errors telling the client how to fix the query.

  1. development efficiency

RESTful API and GraphQL have their own advantages. RESTful API is easier to understand and learn, while GraphQL is more flexible.

GraphQL is more powerful and flexible in data acquisition, and can better adapt to complex data requirements. However, due to the complex syntax of GraphQL, developers need more learning and writing time. Also, GraphQL requires a runtime and requires stricter code inspections, making it harder to use.

  1. API discoverability

The structure of the resource URI of the RESTful API can convey the basic structure of the API. Every resource must be described in the API documentation.

GraphQL does not have a URI to communicate the structure of the API, and API discoverability needs to be achieved in a different way. For example, developers need to provide a document describing all available query and mutation operations.

Both RESTful API and GraphQL have their pros and cons. Which API to choose depends on the needs of the project. If you need a simple and reliable API, RESTful API is a good choice; if you need a fast, flexible and accurate data acquisition method, GraphQL is a better choice.

4. GraphQL syntax

GraphQL is a query language for writing and manipulating APIs. Following is the basic syntax of GraphQL:

  1. Inquire

Use the keyword "query" to declare the query type, followed by the fields and parameters of the query. For example:

query {
    
    
  person(id: "1") {
    
    
    name
    age
  }
}
  1. variable

Variables are declared using the $ symbol and can be reused in queries.

For example:

query getPerson($id: ID!) {
    
    
  person(id: $id) {
    
    
    name
    age
  }
}

At execution time, the value of the variable needs to be provided. For example:

{
    
    
  "id": "1"
}
  1. fragment

Fragments can be used in queries to reuse query parts. Fragments begin with "..." followed by the fragment name.

For example:

query {
    
    
  person(id: "1") {
    
    
    name
    age
    address {
    
    
      ...addressFields
    }
  }
}

fragment addressFields on Address {
    
    
  street
  city
  state
}
  1. operation name

Operation names can be used to identify queries for easy debugging and tracing. The operation name is defined between curly braces after the keywords "query" or "mutation".

For example:

query getPerson($id: ID!) {
    
    
  person(id: $id) {
    
    
    name
    age
  }
}
  1. change

Use the keyword "mutation" to declare a mutation operation. Changes can be used to modify and create data.

For example:

mutation {
    
    
  createPerson(name: "Sam", age: 25) {
    
    
    id
    name
    age
  }
}

The above is the basic syntax of GraphQL. For more advanced features and syntax details, please refer to the official GraphQL documentation.

1. Use of GraphQL.Server

GraphQL.Server related URL: https://github.com/graphql-dotnet/server

insert image description here

1. Installation package

Installation package

GraphQL.Server.All

insert image description here

2. Basic use

1. Configure GraphQL nodes

using GraphQL;
using GraphQL.Samples.Schemas.Chat;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddGraphQL(b => b
    .AddAutoSchema<Query>()  // schema
    .AddSystemTextJson());   // serializer


var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseDeveloperExceptionPage();
app.UseWebSockets();
app.UseGraphQL("/graphql");            // url to host GraphQL endpoint
app.UseGraphQLPlayground(
    "/",                               // url to host Playground at
    new GraphQL.Server.Ui.Playground.PlaygroundOptions
    {
    
    
        GraphQLEndPoint = "/graphql",         // url of GraphQL endpoint
        SubscriptionsEndPoint = "/graphql",   // url of GraphQL endpoint
    });
await app.RunAsync();
public class Query
{
    
    
    public static string Hero() => "Luke Skywalker";
}

insert image description here

2. Run

ask

http://localhost:5001/graphql?query={
    
    hero}

corresponding

{
    
    "data":{
    
    "hero":"Luke Skywalker"}}

insert image description here

Guess you like

Origin blog.csdn.net/aa2528877987/article/details/131899502