GraphQL Core: Queries, Mutations & Subscriptions #6
Deep dive into the GraphQL Queries, Mutations & Subscriptions & how to work with them
In this post, you'll learn in detail about Core concepts of GraphQL. In this post, we will look into below concepts
GraphQL Query
GraphQL Mutation
GraphQL Subscription
Most types in your schema will just be normal object types, but there are special within a schema such as Query:
That means that the GraphQL service needs to have a Query type with Person and Planet fields:
type Query {
person(id: Int!): Person
planet(id: Int!): Planet
}
Every GraphQL service has a query type and may or may not have a mutation type. These types are the same as a regular object type, but they are special because they define the entry point of every GraphQL query.
{
person (id:1) {
name
image
id
height
}
planet (id: 1) {
name
id
gravity
population
}
}
It's important to remember that other than the special status of being the "entry point" into the schema, the Query and Mutation types are the same as any other GraphQL object type, and their fields work exactly the same way.
Most types in your schema will just be normal object types, but there are special within a schema such as Mutation:
schema {
mutation: Mutation
}
That means that the GraphQL service needs to have a Mutation type with createPerson field:
type Mutation {
createPerson(name: String!, age: Int!): Person
}
Mutations follow the same syntactical structure as queries, but they always need to start with the mutation keyword. Here’s an example for how we might create a new Person.
mutation {
createPerson(name: "Bob", age: 36) {
name
id
age
}
}
Most types in your schema will just be normal object types, but there are special within a schema such as Subscription :
schema {
subscription: Subscription
}
That means that the GraphQL service needs to have a Mutation type with newPerson field:
type Subscription {
newPerson (): Person
}
Subscriptions are written using the same syntax as queries and mutations. Here’s an example where we subscribe on events happening on the Person type:
subscription {
newPerson {
name
age
}
}
After a client sent this subscription to a server, a connection is opened between them. Then, whenever a new mutation is performed that creates a new Person, the server sends the information about this person over to the client:
{
"data": {
"newPerson": {
"name": "Bob",
"age": 36,
"id": "7db71f51-2a6d-47d9-b261-879c41f293f0"
}
}
}
You can play around with below codesendbox to see how it works
once new person is created, it will be displayed on the newPerson subscription tab:
Generally, a schema is simply a collection of GraphQL types. However, when writing the schema for an API, there are some special root types:
type Query { ... }
type Mutation { ... }
type Subscription { ... }
In the next tutorial, we will look into Argument, Aliases & Fragments