What is Mutation in GraphQL: Definition and Usage
Mutation in GraphQL is a type of operation used to create, update, or delete data on the server. Unlike queries which only fetch data, mutations change data and can return the updated result.How It Works
Think of GraphQL mutations like sending a request to change something in a database, similar to filling out a form to update your profile on a website. When you perform a mutation, you tell the server exactly what change you want, such as adding a new item or editing existing information.
Unlike queries that only ask for data, mutations can modify data and then return the new or updated data as a response. This is like ordering a product online and immediately getting a confirmation with the order details.
Each mutation is defined in the GraphQL schema with specific input parameters and a return type, so the client knows what data to send and what to expect back.
Example
This example shows a mutation to add a new book with a title and author, and then returns the book's id and title.
mutation AddBook {
addBook(title: "The Great Gatsby", author: "F. Scott Fitzgerald") {
id
title
}
}When to Use
Use mutations whenever you need to change data on the server, such as creating new records, updating existing ones, or deleting data. For example, in a social media app, posting a new comment or liking a post would use mutations.
Mutations are essential for any interactive application where users can modify content or settings, ensuring the server updates data and sends back the latest state.
Key Points
- Mutations modify data on the server.
- They accept input parameters to specify changes.
- Mutations return the updated data after the change.
- They are different from queries, which only fetch data.
- Use mutations for create, update, and delete operations.