Writing Basic Mutations
What you'll learn: How to modify server data in GraphQL by writing mutations with input arguments and defined return types.
While queries read data, mutations write data. Think of mutations as the GraphQL equivalent of HTTP POST, PUT, PATCH, and DELETE operations—they create, update, or delete resources on your server.
Mutation Syntax Structure
A mutation follows a similar structure to queries but uses the mutation keyword and typically returns the modified data or confirmation:
mutation {
createUser(name: "Alice", email: "alice@example.com") {
id
name
email
}
}
Input Arguments
Mutations accept arguments that specify what data to modify. These arguments can be inline (as shown above) or passed as variables:
mutation CreateUser($name: String!, $email: String!) {
createUser(name: $name, email: $email) {
id
name
createdAt
}
}
Return Types Matter
Unlike REST where you might get back just a status code, GraphQL mutations return typed data. You explicitly select which fields you want back—often the newly created or updated object:
mutation UpdateUser($id: ID!, $name: String) {
updateUser(id: $id, name: $name) {
id
name
updatedAt
}
}
Delete mutations might return a success boolean or the deleted object's ID:
mutation DeleteUser($id: ID!) {
deleteUser(id: $id) {
success
deletedId
}
}
The Pattern
Every mutation follows this pattern: specify the operation name, provide required input arguments, and select the fields you want returned. The server validates your inputs against the schema's type system before executing.
Key Takeaway: GraphQL mutations modify server data using structured operations with typed inputs and explicit return field selections, giving you precise control over both what changes and what confirmation data you receive back.