GraphQL is a specification for how to talk to an API. It is designed for HTTP clients to be able to make API calls to fetch exactly the data they need from the APIs.
It stands for Graph Query Language. It is an API standard similar to REST. The fact that it is defined by an open standard, there is no official implementation of it. A GraphQL implementation can be written with any programming language, integrate with any type of database, and support any client (such as mobile or web applications), as long as it follows the rules outlined in the specs.
Almost all gql request are either queries or mutations. They are strongly defined in type defination of graphQL server.
These are a way to ask for response
Request1 Response1
query { | {
user (id: 1) { | "user": {
id | "id": 1
} | }
} | }
----------------------------------------
Request2: | Response2:
query { | {
user (id: 1) { | "user": {
id | "id": 1
name | "name": "Elmo"
} | }
} | }
They are the way to change data on the backend, similar to what is achieved by REST post/put/update etc verbs. Like queries it also returns an object based on the operation performed.
mutation AddNewPet ($name: String!, $petType: PetType) {
addPet(name: $name, petType: $petType) {
id
name
petType
}
}
Variables
{
"name": "Rover",
"petType": "DOG"
}
Response
{
"data": {
"addPet": {
"id": 1
"name": "Rover",
"petType": "DOG"
}
}
}
Before writing logic for any of the queries/ mutations we first have to map all the type of objects, return types, queries etc, in a graphql schema object.
Lets say for a API with User
and Posts
may look like:
type Post {
id: ID!
body: String!
createdAt: String!
username: String!
objectURL: String!
}
type User {
createdAt: String!
username: String!
email: String!
token: String!
password: String!
}
type Query {
getPosts: [Post]
getPost(postId: String!): Post!
}
type Mutation {
registerUser(
username: String!
email: String!
password: String!
confirmPassword: String!
): User!
login(username: String!, password: String!): User!
createPost(body: String!, objectURL: String!): Post!
deletePost(postId: ID!): String!
}
Notice how the types for each entity and relations are clearly defined. All the queries and mutations have type Query
and Mutation
respectively. This blueprint also contains the shape of arguments and the return type, as discussed.
While clearly it looks graphql is more flexible, lets look at each point of difference.
Status 200
with all errors listed in errors
property of response.Coming soon...