“Ask for what you need, get exactly that”
- REST APIs have the problem of either under-fetching data (when we want data related to multiple resources) or over-fetching it (when we only want certain details about a resource)
- With GraphQL we can query for exactly what we want
- Two key parts of GraphQL,
- Query: Fetch the needed data
- Mutation: modify, delete or write server side data
- In GraphQL, data is mostly queried through a single entry point i.e, one API endpoint
Query and Mutation
// Sample query
query {
user {
name
email
}
}
// Sample mutation
mutation {
createUser(input: { name: "Nish", email:"nish@google.com" }) {
id
name
email
}
}
An Example
Consider the below data,
{
"title": "Sys design",
"authors": [{
"name": "Alex Xu"
},
{
"name": "Sahn Lam"
}]
}
The REST way of fetching the data,
GET /books/123
GET /authors/2
The GraphQL way,
// Server side
type Book {
id: ID
title: String
authors: [Author]
}
type Author {
id: ID
name: String
books: [Book]
}
type Query {
book(id: ID): Book
}
// client side
GET /graphql?query={ book(id: "123") { title, authors { name } } }
Advantages
- No more under-fetching or over-fetching
Dis-advantages
- GraphQL needs special libraries, while REST doesn’t
- Difficult to cache when compared to REST