How to Design Mutation Response in GraphQL
In GraphQL, design a mutation response by returning an object that includes the updated data and any relevant status or error information inside a
type. This helps clients understand the result of the mutation clearly and handle success or failure accordingly.Syntax
A mutation response in GraphQL is defined as a type that specifies the fields returned after a mutation runs. It usually includes the updated object and optional fields like success or message to indicate the operation result.
The mutation itself returns this response type.
graphql
type MutationResponse { success: Boolean! message: String updatedItem: Item } type Mutation { updateItem(id: ID!, input: ItemInput!): MutationResponse! }
Example
This example shows a mutation that updates an item and returns a response with success status, a message, and the updated item data.
graphql
type Item { id: ID! name: String! description: String } type MutationResponse { success: Boolean! message: String updatedItem: Item } type Mutation { updateItem(id: ID!, name: String, description: String): MutationResponse! } # Example resolver response (pseudo-code): // return { // success: true, // message: "Item updated successfully", // updatedItem: { id: "1", name: "New Name", description: "Updated description" } // }
Output
{
"data": {
"updateItem": {
"success": true,
"message": "Item updated successfully",
"updatedItem": {
"id": "1",
"name": "New Name",
"description": "Updated description"
}
}
}
}
Common Pitfalls
One common mistake is returning only a Boolean or the updated object without any status or error message, which makes it hard for clients to handle failures gracefully.
Another pitfall is not making the response fields non-nullable when appropriate, causing unexpected null values.
graphql
type Mutation { updateItem(id: ID!, name: String): Item } # This returns only the updated item or null, no status info. # Better approach: type MutationResponse { success: Boolean! message: String updatedItem: Item } type Mutation { updateItem(id: ID!, name: String): MutationResponse! }
Quick Reference
- Always return a response object, not just a scalar or the updated data.
- Include a
successBoolean to indicate operation result. - Add a
messagefield for human-readable info or errors. - Return the updated or created object for client use.
- Make required fields non-nullable to avoid surprises.
Key Takeaways
Design mutation responses as objects containing status, message, and updated data.
Include a non-nullable success Boolean to clearly indicate operation outcome.
Provide a message field to communicate errors or confirmations.
Return the updated or created object to help clients update their UI.
Avoid returning only scalars or nullable fields without context.