GraphQL
Recently, I read some articles about GraphQL and it looks quite interesting. After further reading, I came up this post.
What is GraphQL?
GraphQL is a query language for API, and a server-side runtime for executing queries using a type system you define for your data.
It is an alternative of REST API.
Only one endpoint
Declarative data fetching query
How can we use GraphQL?
For an API, one basic functionality is querying (It provides some other functionalities as well). What it needs to do is to seriliaze objects from one specific programming language to JSON or deserialize from JSON to an object. GraphQL uses a series of types for serializing/deserializing objects. Here are some core concepts in GraphQL.
Schema
A GraphQL Schema defines the types and relationships between Fields in the API.Types
By using the type system, it can be predetermined whether a GraphQL request is valid or not. This allows servers and clients to effectively inform developers when an invalid query has been created, without having to rely on runtime checks.Object type: (<=> like a serializer in DRF?)
- Root object types (These are build-in types):
- Query: (examples: get request)
- Mutation: (examples: post, patch, delete request)
- Subscription: (websocket, django-channels, push data to the client when new data is available)
- Root object types (These are build-in types):
Scalar type:
- Int
- String
- Float
Input type:
Let’s see an object type example:
1
2
3
4
5
6
7type Author {
id: ID!
firstName: String
lastName: String
email: String!
posts: [Post!]
}
GraphQL Schema Definition Language (SDL)
How can we make a query? The the basic structure is as below:
1 | field { |
1 | query { |
What are the benefits of GraphQL?
Avoid overfetching
Specifying only the data we need rather than accepting large RESTful response, clients consume less data.
Don’t need simple version of serializers anymore.Only one endpoint
Retrieving multiple pieces of information across different sources in a single request.
No need to generate URL on the response.Auto-generate API Documentation
Don’t need typescript generator anymore. Reduce the pain of maintaining API Documentation.