How to Create Data Using Mutation in GraphQL
In GraphQL, you create data by using a
mutation operation, which modifies server-side data. A mutation defines the action and the data you want to create, and the server returns the newly created data as a response.Syntax
A GraphQL mutation has this basic structure:
- mutation: keyword to start a mutation operation.
- mutationName: a descriptive name for the mutation.
- input: the data you want to create, passed as arguments.
- selection set: fields you want returned after creation.
graphql
mutation CreateItem($input: ItemInput!) {
createItem(input: $input) {
id
name
description
}
}Example
This example shows how to create a new book with a title and author using a mutation. The server responds with the book's ID and title.
graphql
mutation CreateBook {
addBook(title: "The GraphQL Guide", author: "John Doe") {
id
title
}
}Output
{
"data": {
"addBook": {
"id": "1",
"title": "The GraphQL Guide"
}
}
}
Common Pitfalls
Common mistakes when creating data with mutations include:
- Not defining required input arguments correctly.
- Forgetting to request fields in the selection set, resulting in empty responses.
- Using
queryinstead ofmutationkeyword for data changes.
Always check your schema for required inputs and return fields.
graphql
/* Wrong: Missing required input argument */ mutation { addBook { id } } /* Right: Provide all required inputs */ mutation { addBook(title: "New Book", author: "Jane") { id title } }
Quick Reference
| Part | Description |
|---|---|
| mutation | Keyword to start a mutation operation |
| mutationName | Name of the mutation for clarity |
| input arguments | Data you want to create or change |
| selection set | Fields you want returned after mutation |
Key Takeaways
Use the
mutation keyword to create or modify data in GraphQL.Always provide required input arguments as defined in the schema.
Request the fields you want returned after the mutation in the selection set.
Check your schema for exact mutation names and input types.
Avoid using queries for data changes; use mutations instead.