Understanding GraphQL Mutations
Queries are intended for reading data, while mutations represent operations that modify server-side state.
A schema commonly defines a root Mutation type:
type Mutation {
createUser(input: CreateUserInput!): User!
updateUser(id: ID!, input: UpdateUserInput!): User!
deleteUser(id: ID!): DeleteUserPayload!
}
A client can call a mutation using:
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) {
id
name
email
}
}
Mutations are not automatically database writes. The schema defines the operation, while the resolver determines what actually happens.
A mutation might write to MongoDB, PostgreSQL, Redis, another API, or several systems.
Mutation naming
Prefer names that describe the business action rather than vague names such as save or process.
Examples:
createOrdercancelOrderpublishArticleresetPasswordaddProductToCart
Good mutation names make an API easier to understand and monitor.
Create User Mutation
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) {
id
name
email
}
}💡 The mutation accepts a strongly typed input object and returns the newly created user. The client controls which fields of the returned user it needs.
Key Takeaways
- Mutations represent state-changing operations.
- A mutation does not inherently require a database.
- Mutation names should describe meaningful business actions.
- Mutation responses should expose useful result data.
Knowledge Check
Which statement about GraphQL mutations is correct?