A gentle introduction to a different API paradigm
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.
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
Better performance:
It uses fewer round-trips to get the data you need
Strongly typed:
It uses an enforceable data schema which includes validations
It is a standard:
Defines a specific way to expose data and operations
Native discoverable:
Is self-documented and self-described which ease the introduction to users and developers
The best way to explain it is describing its principal concepts:
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
}
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]
}
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
}
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
}
}
Keep learning: