Base Format for GraphQL trong Drupal 9
6th May 2022REST vs GraphQL
The same route handler function is called in REST whereas in GraphQL query can be called to form nested response with multiple resources. GraphQL execution library is used to construct response structures.
PURPOSE
- Decoupled Drupal applications with a javascript front-end (React, Angular, Ember, etc)
- Providing more flexibility and efficiency as compared to REST endpoint by exposing API endpoints using GraphQL (Query language).
For Query Structure
type Car { id: ID name: String launched: Date price: String brand: Brand } type Brand { id: ID country: String cars: [car] }
Base Format for GraphQL
type Query { car(id: CID!): Car brand(id: BID!): Brand } type Mutation { getTestDrive(input: AddRequestInput): TestDrive } type Car { ... } type Brand { ... } type TestDrive { ... } input AddRequestInput { ... }
Request Format
GET /graphql?query={ car(id: "1") { name, brand { country } } }
Integration in Drupal 8
- Module: graphql
- Library : graphql-php
Advantage of GraphQL
- Reduce the number of API calls to the server by the ability to created nested API calls.
- It uses strong type system to define the capabilities of an API. These types are written in the schema using GraphQL Schema definition (SDL) which is serves as a contract between the Client and Server.
- Once the schema is defined front-end and back-end teams know the structure of the data and can, therefore, work independently.
- No more Over- and Under fetching of attributes that may be one of the concerns in REST
- GraphQL uses the concept of resolver functions to collect the data that’s requested by a client. With the help of resolvers, we can identify issues/errors in the schema definition
- Changes in the Frontend design can be addressed without any extra work on the server. Since Client-side application (React, Angular, etc) can specify their exact data requirements, no backend engineer needs to make adjustments in API.
Add new comment