Graphql
Graphql is an api design offering a flexible and efficient usage of the endpoints and service developed in your applications. While endpoints in REST api are fixed, graphql is not. It is a query language that allows clients to request exactly the data they need at any time. This query language is based on a defined typed schema (contract) generated by the server and used by the clients to make proper requests.
Graphql only exposes a single endpoint POST /graphql. With this endpoint,
clients can create their own query to get the information from multiple servers.
Some benefits from using graphql are:
- Every time a request is sent, clients send which data to obtain. Multiple queries can be combined to get one response.
- Clients can optimize response payload, avoiding over-fetching and under-fetching.
- No need to configure multiple services neither versions.
- Real-time notification.
Graphql response is always a json object with the same structure as the query.
Successful responses are under the data field, while errors are under the
errors field. If more than one query is sent, the response will contain both
successful and failed responses (query name will be key in the data json
object), allowing partial success.
Concepts
- Query: request to get data. Allows full control on what resources to retrieved.
- Mutation: request to perform modification on resources.
- Subscriptions: enables clients to listen for changes and receive automatic updates when resources are modified.
Disadvantages
- Complexity: not plug-and-play like REST, requires more configuration and schema.
- Caching: is a challenge, as each request is configured by client.
- Optimization: huge nested payload request can overload the system. As we don’t know which data to retrieve beforehand, endpoints needs to be optimized, avoiding any impact in your database.