GraphQL for APIs
Get introduced to GraphQL API and its components.
We'll cover the following
GraphQL is a query language for APIs and runtime used to execute the queries on existing data. It allows us to precisely describe the shape of the data that should be queried and defines a schema for it.
A GraphQL API uses the GraphQL query language to enable clients to interact with the server and receive responses tailored to their needs. GraphQL APIs provide a more flexible alternative to traditional RESTful APIs
GraphQL API vs. REST API
Let’s compare GraphQL API with REST API. Consider a news website as a web application with multiple sections on the front page, as shown in the illustration below, each for headlines, weather updates, and featured articles. Each section might have a different data source. A RESTful API will create a separate endpoint for each data source and call multiple endpoints simultaneously, adding to the network latency. To resolve this issue, GraphQL API combines the calls to multiple data sources in one API endpoint call as illustrated in the diagram below:
Another advantage GraphQL APIs offer is the ability to specify the data we need. For example, consider a similar news website application designed for the mobile application. Due to the smaller screen size, the developer may display only a summary of information. In a RESTful API, the only feasible solution would be to filter the JSON payload we receive in response to the API call. But GraphQL provides a more elegant solution by only fetching the required data.
Components of GraphQL API
GraphQL API comprises a schema that defines the data structure to be fetched from the data source. The resolvers handle the business logic to fetch data from the data source. Let's dive deep into each of these components.
Schemas
As described above, Schema is the blueprint that describes the shape of the data to be fetched from the data source. GraphQL API is based on a single schema against which all operations in a GraphQL API request must be validated.
Schemas are written in Schema Definition Language (SDL) and are usually defined in a .graphql
or a .json
file. It comprises types and fields that define the data shape and fields within each type, respectively. The code widget below shows a sample schema that allows us to fetch news blogs from the table:
type NewsBlog {id: ID!blogTitle: StringimgUrl: StringcontentUrl: StringblogAuthor: String}type Mutation {addNewsBlog(id: ID!,blogTitle: String!,imgUrl: String,contentUrl: String!,blogAuthor: String): NewsBlog!editNewsBlog(id: ID!,blogTitle: String!,imgUrl: String,contentUrl: String!,blogAuthor: String): NewsBlog!removeNewsBlog(id: ID!): NewsBlog}type Query {getNewsBlog(id: ID!): NewsBlogallNewsBlogs: [NewsBlog]}schema {query: Querymutation: Mutation}
The schema given above consists of three types: NewsBlog
, Mutation
, and Query
. Let's understand these.
NewsBlog
: The object that defines the blueprint of the instance of a news blog and contains the fields required from the database. They define the properties of the NewsBlog, such as its title is aString
. These fields gain us control over the amount of data fetched from the source.
type NewsBlog {id: ID!blogTitle: StringimgUrl: StringcontentUrl: StringblogAuthor: String}
Mutation
: The mutations modify the data, such as updating or deleting. TheMutation
given below adds, updates, and removes the news blogs from the database. It is similar toPUT
andPOST
operations.
type Mutation {addNewsBlog(id: ID!,blogTitle: String!,imgUrl: String,contentUrl: String!,blogAuthor: String): NewsBlog!editNewsBlog(id: ID!,blogTitle: String!,imgUrl: String,contentUrl: String!,blogAuthor: String): NewsBlog!removeNewsBlog(id: ID!): NewsBlog}
Query
: The object of typeQuery
retrieves data from the source. It is similar to the GET request. TheQuery
given below gets a CloudLab using its ID.
type Query {getNewsBlog(id: ID!): NewsBlogallNewsBlogs: [NewsBlog]}
Data sources
The Data source, as the name suggests, is the data on which GraphQL API works. We can attach multiple data sources to a single API endpoint and thus process multiple requests in one request.
Resolvers
Resolvers connect GraphQL API and the data source we attached to it. It is a code that converts the API request to the instruction required by the data source, and the data is returned to the response required by the API endpoint. Also, it requires a runtime to execute.
A simple resolver may define the handlers for the request and response. The code snippets given below show the resolvers for the Cloud Lab example.
import { util } from '@aws-appsync/utils';export function request(ctx) {const {source, args} = ctxreturn {operation: 'Invoke',payload: { field: ctx.info.fieldName },};}export function response(ctx) {const { error, result } = ctx;if (error) {util.appendError(error.message, error.type, result);}return result;}
This is an example of Unit Resolver, which defines a single request and response handler. In addition, GraphQL offers Pipeline Resolvers to create a sequence, or pipeline, of functions that process the response of a GraphQL resolver and transform it before sending it back to the client.
Resolvers can be defined in both Javascript and Apache Velocity Template Language, or VTL, for short. The code snippet given below shows the VTL equivalent for the resolver given above.
{"version": "2017-02-28","operation": "Invoke","payload": {"field": $util.toJson($context.info.fieldName)}}
Get hands-on with 1300+ tech skills courses.