GraphQL is a query language for APIs developed by Facebook. It could be used as an alternative to Rest API.
Let’s review the example of a mobile application.
It’s a user page with five titles of posts and three names of followers.
Below you see the result of Rest API requests. To get this data we made three requests to various endpoints to get the required data.
Here is how it works in GraphQL:
A few key differences between GraphQL and Rest API:
- GraphQL uses any protocol to extract information (http, ssh, cli, etc.), while REST relies on HTTP.
- GraphQL uses a single entry point — GraphQL server.
- In the REST API, each route is a separate entry point with its own parameters and data format.
- REST allows working with various data formats (json, xml, etc.), while GraphQL uses the only json.
A little bit about GraphQL
- GraphQL supports 3 types of operations that shouldn’t be used within one request:
- Query — to get data
- Mutation — to change data
- Subscription — to receive a notification if data has changed
- GraphQL supports branching in requests (return if …, do not return if … if the returned result is an instance …, etc.)
Pros and cons of GraphQL
- One entry point: /graphql
- Allows to get data on multiple entities in one request
- The smaller size of returned content Increases performance. It allows you to initiate the system one time and get all the data instead of initializing consecutively multiple connections.
- The built-in mechanism for query comments. Built-in ability to get a list of all methods and parameters (OOTB alternative of Swagger).
- It requires a previously described scheme of request and response parameters.
- Using mostly POST requests. GET requests are possible only through JS or similar approaches due to custom Content-Type: application / json.
GraphQL in Magento 2.3.*
- It is under development. You can access the GraphQL feature only in Magento developer mode.
- Magento modified GraphQL
- added commands (directives) to the documentation scheme, class the prepare data.
- Changed the behavior of the interface.
- Changed schema validation for a request of non-existent EAV data
- Magento implemented the schema description via the etc / schema.graphqls file.
As of Magento 2.3.4, GraphQL provides the following features:
- Support for all product types, payment methods, and shipping methods.
- Achieved <.5 sec average response times with 500 concurrent requests.
- Redesigned a feature of rich layered navigation