How to Write Mutation in GraphQL: Syntax and Examples
In GraphQL, a
mutation is used to modify data on the server. You write a mutation by defining the mutation keyword followed by the mutation name and input arguments, then specify the fields you want returned after the change.Syntax
A GraphQL mutation starts with the mutation keyword, followed by a mutation name and input parameters inside parentheses. Inside curly braces, you specify the mutation operation and the fields you want returned after the mutation runs.
- mutation: keyword to start a mutation operation.
- mutationName: the name of the mutation you want to call.
- input: arguments or data you send to the mutation.
- fields: the data you want back after the mutation.
graphql
mutation mutationName($input: InputType!) {
mutationName(input: $input) {
field1
field2
}
}Example
This example shows a mutation to add a new user with a name and email, returning the new user's ID and name.
graphql
mutation AddUser($input: AddUserInput!) {
addUser(input: $input) {
id
name
}
}Output
{
"data": {
"addUser": {
"id": "123",
"name": "Alice"
}
}
}
Common Pitfalls
Common mistakes when writing mutations include:
- Forgetting to use the
mutationkeyword before the operation. - Not passing required input arguments or using wrong types.
- Requesting fields that the mutation does not return.
- Confusing query syntax with mutation syntax.
graphql
Wrong:
{
addUser(name: "Alice") {
id
}
}
Right:
mutation AddUser($input: AddUserInput!) {
addUser(input: $input) {
id
}
}Quick Reference
| Part | Description |
|---|---|
| mutation | Keyword to start a mutation operation |
| mutationName | Name of the mutation function to call |
| input | Arguments or data sent to the mutation |
| fields | Data fields requested in the response |
Key Takeaways
Always start a mutation with the
mutation keyword.Pass required input arguments with correct types to the mutation.
Specify the fields you want returned after the mutation runs.
Avoid confusing query syntax with mutation syntax.
Test mutations to ensure they modify data as expected.