https://medium.com/@weblab_tech/ graphQL-everything-you-need-to-know-58756ff253D8

Original author :Weblab Technology

Translator: Yang Tao

The purpose of this article is to point out the main features associated with GraphQL and discuss the advantages and disadvantages of the specific API specification.

GraphQL is often described as a “front-end oriented” API technology because it allows front-end developers to request data in a much simpler way than before. Facebook introduced this query language with the goal of customizing client-side applications in intuitive and scalable ways to describe data preconditions and interactions. The best part is that the query language is not dependent on any particular database management system and is supported by current data formats and encoding methods.

A fundamental problem with traditional REST is that clients cannot personalize the collection of data. In addition, running and controlling multiple endpoints is another challenge, because clients often need to fetch data from multiple endpoints.

When you set up a GraphQL server, you only need a simple URL to fetch and modify the data. Thus, a user can request a dataset from the server by passing a query string and declaring what they need.

Before we continue, here’s where you can find our personal practice. graphlql-example

GraphQL VS REST

Speaking of similarities, REST and GraphQL are both used to build apis. In addition, they can all be managed over HTTP. As for the differences, REST is primarily a software-centric, structured concept with no specification and no explicit toolset. It focuses more on API stability than performance. GraphQL, on the other hand, is a query language designed to manage endpoints over HTTP to improve performance and applicability. I would go so far as to say that the query language and the architectural style of developing the web might seem strange to compare side by side :). Some other notable differences include:

Data acquisition

Without a doubt, data acquisition is one of the most compelling features of GraphQL. To generate and retrieve data through standard REST apis, we may need to make requests to multiple endpoints. In contrast, GraphQL provides a single endpoint that can fetch server data

query {
  books {
    id
    title
    author
    isbn
    price
  } 
}
Copy the code

Beyond data acquisition

Since every interface in REST contains a fixed data format, it allows you to get more redundant data than GraphQL does. Similarly, REST sends additional requests to retrieve relevant data. For the previous example, GraphQL is quite different. Because it is a query language and supports declarative fetching of data, users can fetch only the data they need from the server.

Only the title and price of books are queried
query {
 books {
   title
   price
 } 
}
Copy the code

Error management

In the REST style, error management is very simple. What we need to do is check the HTTP headers and see where the response is. With status codes, we can quickly find the error and the appropriate way to resolve it. On the other hand, in GraphQL, we always receive a status code of 200 OK.

Request: query { books { error_field } } Response: Request Method:POST Status Code: 200 OK {" errors ":[{" message" : "Cannot query field\" error_field\ "ontypeThe Book \ \ ""." Graphql ", "category" : ", "locations" : [{" line ": 3," column ", 3}]}}]Copy the code

The cache

Because REST enforces the USE of the HTTP protocol with caching, you can use it to avoid retrieving unwanted resources. GraphQL, on the other hand, has no caching mechanism, leaving the caching responsibility to the user.

The advantages of GraphQL

version

Data control brings API boundaries, and any change is considered a disruptive change that requires updating the VERSION of the API. This is probably why most apis opt for version control. If the new API requires the latest version, we need to make frequent adjustments between the new API and the original API. In contrast, GraphQL returns only the data we need, getting the latest data types and fields without changing the original request.

Abandonment is easy

When using GraphQL, you can easily deprecate a field. GraphQL users will definitely declare the fields they need.

'author_name = > ['type'=> Type::string(),' deprecationReason '=>' Deprecated. Use author field ',],Copy the code

REST apis work in different ways. Although basic endpoints are available in the REST API, not all endpoints can return sparse fields. By contrast, GraphQL makes it very easy to monitor the use of specific fields. API consumers can deploy retrieved fields on specific clients.

Performance optimization

REST requests default as a whole, and GraphQL generally tries to send as few requests as possible. Even though REST returns the bare minimum for each request, GraphQL can transfer many more pieces of data in the same case.

The disadvantage of GraphQL

GraphQL caching is not easy

Unlike REST, which defaults to HTTP for clients and proxies to work perfectly, GraphQL is called in a completely different way. Of course, things are not as simple as REST, because you need to adjust your data sets, use Redis collections and always need to pray that the client can cache.

As the official documentation explains, “In an endpoint-based API, clients can use HTTP caching to easily avoid retrieving resources twice and to recognize when two resources are the same. Clients can build caches from urls in the API as globally unique identifiers. In GraphQL, no URL-like object can be used as a globally unique identifier. The best practice is to provide such an identifier for clients to use.”

Authentication problem

Authentication was also an important concern when using GraphQL. Think of GraphQL as a domain-specific language, which is just a thin layer between the server and the client. Authentication is a separate layer, and the language itself does not authenticate or authorize applications. But you can use Entry tokens to associate clients with responses. This is very similar to the approach we follow in REST.

Detect and resolve N +1 problems

What is the n+1 problem?

The n+1 problem is the most obvious optimization problem you might encounter when doing a GraphQL back end.

If you don’t optimize your GraphQL query, you might make multiple queries in a single Query. Without a proper caching and batch processing system, the server responds to a request every time a field is determined. DataLoader is far and away the best solution to dramatically improve the performance of the back end, especially in the GraphQL server. Use a simple example to describe the n+1 problem

query {
 users {
    name
    education {
      degree
      year
    }
    age
    address {
      country
      city
      street
    }
  }
}
Copy the code

It is easy to evaluate, identify, and solve N +1 problems using REST apis. It’s different for GraphQL. Fortunately, Facebook is trying to solve this problem with DataLoader

What is the DataLoader

How does it work?

DataLoader mainly uses batch processing and caching. It is used to batch load responses to multiple questions/requests from clients. In addition, it can cache responses and enable them to respond to successive similar resource requests.

Queries, Mutations, and Subscriptions in GraphQL

Ok, so we’ve highlighted some important aspects of GraphQL. But in order to develop a fully functional app, we also need to know some other parts to enhance functionality and performance.

Queries

As its name suggests, Queries are for the client to fetch data from the server. Unlike REST, which returns details from multiple endpoints, GraphQL provides only one endpoint and lets the client decide what data it needs from a predefined framework. Such as:

{
 Users {
   name
 }
}
Copy the code

The ‘Users’ field mentioned in the above query is called the root field, and the other data is called the payload. This query will return a list of user names:

{" Users ": [{" name" : "Damira"}, {" name ":" Michael "} {" name ":" Salman "} {" name ":" Sara "} {" name ":" Maria "}]}Copy the code

It is worth noting that this query only returns the user name (because in our query we only declared that we needed the user name). For a second foreign request, we need to add specific details to it. For example, suppose we only want to get information for the last three users in the list. We can implement it by writing arguments like this.

{
  Users (last: 3) {
    name
    username
}}
Copy the code

So far, we have seen how to get data from the server through a query. Now let’s take a look at creating, omitting, and updating data in GraphQL.

Mutations

Mutations are used to create, update or delete data. It has almost the same structure as queries, except that you need to add the ‘mutation’ field at the beginning. For example,

Mutation {createUser (name: "John", username: "jo123"){name username}}Copy the code

Subscriptions

Subscriptions are used to set up and maintain real-time connections to servers. It allows you to get real-time information about relevant events. In most cases, clients need to subscribe to specific events to get the corresponding data. Please pass graphql.org/learn/queri… Get details

The best of both worlds

Part of the solution can be found in Stack in Aollo.

If you have a running project, it’s hard to quickly migrate from RESTful apis to GraphQL. But the good news is that you can enjoy the benefits of both. For example, you can use GraphQL queries to reconstruct the way data is retrieved in the front end, and then start integrating mutations. It allows you to slowly reduce the actions in your controllers and, in addition, you can keep both methods in the project for a long time. For example, if you want to simplify authorization, you can always help with REST architecture.

conclusion

SOAP

Some useful information

https://github.com/weblab-technology/graphql-example

Implementing GraphQL as a Query Language for Deductive Databases in SWI-Prolog Using DCGs, Quasi Quotations, and Dicts

REST and Web Services — In Theory and In Practice — Springer

by Oleksandr Knyga, Software Engineer Maksim Kolesnikov, DevOps Sergei Guliaev, Back-End Developer Viacheslav Eremin, Front-End Developer Sharmeen Hayat, author & Data Specialist Dima Dmytriienko, editor & Brand Specialist

.

Some of the GraphQL problems mentioned in the original article were solved in Apollo GraphQL project to a certain extent, compared to adding caching.