GraphQL – APIs to Next Level

Have you ever tried GraphQL for your APIs? Still sticked with traditional REST/SOAP? Give GraphQL a try !

GraphQL aka Graph Query Language is originally developed by facebook sometimes ago for their product lines and became available to public few years ago. If you are intend to design and develop lightweight but powerful API which is dynamic and respond with not more or not less data, this is ideal selection for you.

Most of the time we are writing APIs in day-today to request a resource and respond with bunch of data. But think, different components in your system require different combination of data, for example, you need a user APIs which requests profile details from server for one component of your application and another component need your birth-date only, how you are going to design such a scenario? If you are develop your APIs using REST you have to design two APIs right? for get user profile(/user/profile) and get get user birth day(/user/birthday) or sometimes you think why I can’t use profile api(/user/profile) for both? But reusing such a time consuming and bulk APIs again and again slow down your system, specially you are more into mobile friendly design. Using two APIs solves the problem but lot of code to write and increase your app complexity and app maintainability.

Here is the rescuer, GraphQL

Sample express-graphql implementation with unit test available here for your reference.

https://github.com/dumindarw/graphql-mongo-test.git

GraphQL is a kind of a query language, it provides you what you want without going here and there for requesting resources 🙂

There are two main two categories for GraphQL

  • Query
  • Mutation

Query is used when you want to ‘GET’ data, means, whole data or partial of data
Mutation is used when you want to ‘POST’ or ‘PUT’, means you need to insert record or update records, simple as that !

How to write queries

Get all users

query a{
users{
id,
nic,
username,
currentaddr{
district
}
}
}

Get user by id

query b{
user(username: "dum2"){
nic
firstname
currentaddr {
district
}
location{
coordinates
}
}
}

The awesomeness here is you can add remove fields as you wish.

How to write mutations

Save User

mutation c{
adduser(user: {username:"dumindaw",firstname:"xxxx",
lastname:"xxxx",password:"abc123",nic:"870750986V",
deviceid:"1234567", email:"deemind@gmail.com",tp:"0779906999",
location:{type:"Point", coordinates: [7.88,81.44]},
currentaddr:{district:"Kurunegala",dsdivision:"YMP"},verified:false,blackListed:false}){
insertedId
}
}