Working with Variables in Mutations
GraphQL supports the use of variables in mutations, which makes them more flexible and reusable. Here’s how we can use variables with the addBook mutation.
1. Define the Mutation with Variables:
In GraphiQL, the mutation is defined and each variable is separately defined in the query section of the dropdown.
mutation AddNewBook($title: String!, $author: String!) {
addBook(title: $title, author: $author) {
id
title
author
}
}
2. Provide Variable Values:
Under the query editor process, there is a space to input variables in json format.
{
"title": "Brave New World",
"author": "Aldous Huxley"
}
This way, we can reuse the mutation with different variables without changing the mutation query itself.
Mutations in GraphQL
GraphQL is a query language for REST APIs created by Facebook which is designed to provide more efficiency, flexibility, and superiority in data handling.
While GraphQL queries are used to retrieve information, mutations are used to perform data operations on the server, similar to HTTP Commands like POST, PUT, PATCH, and DELETE in REST APIs. In this article, We will learn about the Mutations in GraphQL in detail.