Getting started with GraphQL

Javeeth Basha
TestVagrant
Published in
7 min readJun 18, 2020

--

GraphQL — A Query Language for APIs

  • GraphQL was developed in facebook’s incubator in the year 2012 and was open-sourced in 2015 and moved under a foundation called GraphQL foundation.
  • GraphQL is an API design architecture and open-source data query and manipulation language, which provides a more efficient, powerful, and flexible alternative to RESTful.
  • It operates over HTTP protocol, same as RESTful APIs.
  • It considers data as a graph implying it’s connected, it doesn’t deal with dedicated resources. What it means is that you can create your request to match your exact requirements using the GraphQL query language.
  • GraphQL follows Query — What You want pattern, which empowers the client to build and specify their queries and get what data it needs from an API. This form of payload reduces the wait time and increases performance.

How does it work?

GraphQL has 2 parts:

  • A GraphQL server which handles the incoming request that is sent to it and responds with precise data.
  • A Client, which will build a request according to its requirement and POST that request payload to the GraphQL server.
Calling GraphQL API using Postman.

GraphQL Terminologies

  • Schema: GraphQL schema is the core of Graph server implementation. It acts as a contract between a client and server, it describes the functionality that the server provides and how clients can access it’s data so that they can connect to it.
schema {
query: Query
mutation: Mutation
}
  • Types: Types are the building blocks of the GraphQL, it is a custom object to specify the fields that are exposed as part of the API. Types have fields and every field returns a data of type which is specified to it.
type Book {
id : ID!
name : String
genre : String
author : Author
}
type Author {
id : ID!
name : String
age : Int
books: [Book]
}

In the above example, we see two types Book and Author, which contains fields for querying id, name, genre, and age that returns ID, String, and Int data types. The Exclamation mark denotes that the field is non-nullable(mandatory) and square brace denotes it’s a list.

  • Query: A query is a request that is made by the client. Query fields can support arguments and can be an array. It is a fetch operation that retrieves the data with respect to the query sent.
type Query {
book(id: ID) : Book
author(id: ID) : Author
}

In the above example, the schema allows the client to query a book with a valid Id and an author with a valid Id.

  • Mutation: GraphQL allows us to modify resources on the server using mutations. It is used to perform CRUD operations on resources available on server.

In GraphQL, Mutation is always a POST(over HTTP) call which will perform some operation and return a response. The Operation of the mutation is defined by the schema.

type Mutation {
addBook(id:ID!, name:String, genre:String, author:Author) : Book
addAuthor(id:ID!, name:String, age:Int, books:[Book]) : Author
}

In the above example, two mutations will add a Book and an Author. The Book and Author are created with respect to the payload passed to it.

  • Resolvers: Resolver is a piece of code that acts as a query handler. It helps the GraphQL server to resolve the query sent to it by the client. Resolvers tell the GraphQL server, from where to fetch the data for the query received and generate the response for the query.
GraphQL Resolver Function.

In the above example, Resolver handles the query to fetch the book.

  • Subscriptions: Subscription is a feature that allows the server to send data to the subscribed clients whenever a specific event occurs.
type Subscription {  
newBook: Book
}

In the above example, Whenever a new book is added, the author of the book gets notified by the event. Method newBookwill be resolved by the resolver, which will push the event data(New Book Details) to the subscribed clients.

Advantages of GraphQL over RESTful

  1. Solves the problems associated with over/under Data Fetching:

Over Fetching:

In RESTful, each API has specific response payload and for each call, all the entities of the payload will be sent back even if some are not really required by the client. In this scenario, the client will receive more information than actually what he needs. This is called as Over Fetching.

For example, Client wants to know only the name of the book.

The RESTful API call to GET — /Book/1

In RESTful API — Let’s assume a Get Book API which will return book information. In the above call whenever the client hits GET - /book/id API it returns book info as a JSON response, The response contains more information (genre, authorId) rather than what the client requires.

In GraphQL — As we saw earlier, in GraphQL client can send a query with specifying the entities that it requires from the GraphQL server.

GraphQL API call to GET — Book

The above query retrieves only the name of a book, which corresponds to the Id-1. In this way GraphQL lets clients build queries according to their requirements and get what data it needs from the API.

GraphQL can do more magic than this, let’s see how we can play around with queries.

GraphQL query to get a book — Id 1 and its author details
Query to get a list of books and its author and sub-query to get a list of books written by the author.
  • Under Fetching:

Under fetching means that one single endpoint doesn’t provide enough of the information that is required so that the client has to make multiple calls to fetch the necessary information that it needs.

Problem Statement: Fetch Author name for the given Book name.

RESTful API and GraphQL API call to get Author name.

As evident from the screenshot, using GraphQL would return as much data that the client requires rather than fetching it from multiple endpoints as RESTful does.

2. Single Endpoint:

In RESTful API, every resource has a dedicated endpoint and it’s very common that we end up having multiple endpoints. Each Endpoint corresponds to a resource.

Whereas, in GraphQL, it considers data as a graph implying it’s connected and it doesn’t deal with dedicated resources rather a single endpoint to serve all requests. The Endpoint serves all operations such as Query, Mutation, and Subscription.

3. Versioning:

In RESTful API, we have seen APIs having different versions like v1, v2, and so on, whenever an additional feature is added to the API.

Whereas in GraphQL, there’s no need to maintain versions. When the older features are not used anymore, We can make changes to our schema and mark as deprecated. The older feature will continue to work even if it’s deprecated. By this GraphQL eliminates the process of maintaining versions.

4. Documentation:

GraphQL provides an option to automatically create documentation for queries and mutations that we have defined in the Schema.

GraphiQL reference can be used to enable the documentation for the code.

The documentation for a GraphQL API lives parallel to the code so that it is always in sync with the changes. Whenever a change is done, like adding a field or type or updating a query then documentation also gets updated, reducing the overhead of maintaining separate documentation.

Conclusion

GraphQL which started as a concept to overcome Facebook’s News Feed API for the mobile platform has become one of the efficient API architectural styles of today.

GraphQL gives control over the data to the client and by using a query, the client can exactly describe what the response should look like. Also, the GraphQL query lets the client fetch information of all the connected entities in a single query. With no over-fetching and by avoiding multiple API calls, GraphQL increases the performance of the API.

Thanks for Reading !!!

Keep following TestVagrant for more such interesting and valuable learnings — next blog in the GraphQL series coming soon !!

--

--