GraphQL 101
A gentle introduction to a different API paradigm
What is GraphQL?
Is a data query language created by Facebook for internal use and later released in 2015, It basically provides a new paradigm to exchange information with a server, it is an alternative to SOAP and REST APIs.
Main advantages of GraphQL
More simple data retrieval:
It allows you to customize your request and ask for as many or fewer fields you need in a simple call
Main advantages of GraphQL
Better performance:
It uses fewer round-trips to get the data you need
Main advantages of GraphQL
Strongly typed:
It uses an enforceable data schema which includes validations
Main advantages of GraphQL
It is a standard:
Defines a specific way to expose data and operations
Main advantages of GraphQL
Native discoverable:
Is self-documented and self-described which ease the introduction to users and developers
Who is using GraphQL?
Who is using GraphQL?
Who is using GraphQL?
How does it work?
The best way to explain it is describing its principal concepts:
Schema
The GraphQL schema defines the server’s API and is written in its own typed language:
type Message {
id: ID!
text: String!
author: String!
comment: String
}
Queries
Defined inside the Schema, Queries in GraphQL are analogous to REST’s GET, is the way to ask the server for the data we need. Contrary to REST, however, we get full power to ask for exactly what we need, and in the format we need it.
type Query {
allMessages(): [Message]
}
Mutators
Defined inside the Schema, Mutators could be compared to REST’s POST, PUT and DELETE, is the way to modify data in the server, they allow to create, modify and delete information:
input MessageInput {
text: String
}
type Mutation {
updateMessage(id: ID!, input: MessageInput): Message
}
Resolvers
Resolver are external functions mapped to the Schema in charge of processing the queries and mutators, they should process the data, make the writing operations and return the queried information:
const root = {
allMessages: function (args) {
return db.getAllMessages()
},
updateMessage: function ({id, input}) {
const currentMessage = db.getMessage(id)
if (!currentMessage) {
throw new Error('No message exists with id: ' + id);
}
currentMessage.update({text: input})
return currentMessage
}
}
References
Keep learning:
- Official site: http://graphql.org/
- JS implementation: http://graphql.org/graphql-js/
- Fullstack tutorial: https://www.howtographql.com/
GraphQL 101
By Adrián Estrada
GraphQL 101
A gentle introduction to a different API paradigm
- 1,486