tezvyn:

GraphQL Mutations: Writing Data to Your Graph

AI-drafted, machine-checkedSource: apollographql.comadvanced

Think of a GraphQL mutation as a remote function call for writing data. Unlike REST, you declare what data you want back from the server in the same operation. Use it for creating, updating, or deleting data, like submitting a form or liking a post.

WHY IT EXISTS: Traditional REST APIs use different HTTP verbs and endpoints for writes (e.g., POST /users, PUT /users/1). This creates endpoint sprawl and ambiguity about what data is returned. GraphQL needed a single, explicit convention for all state-changing operations, centralizing them through one operation type.

THE MENTAL MODEL: A mutation is a remote function you call to change server-side data. You pass arguments to it, just like a local function. The key difference from a typical API call is that you also specify the 'return value' in the request itself—telling the server exactly which fields of the modified data you want back. This avoids a second fetch and gives you immediate feedback to update your UI.

HOW IT WORKS: You define a mutation on your GraphQL schema with a name, input arguments, and a return type (e.g., createPost(title: String!): Post). In your client, you call this mutation by name, provide variables for the arguments, and specify which fields you want from the returned Post object (like id and createdAt). The server executes the corresponding resolver, performs the database write, and then returns a JSON object containing only the fields you requested.

WHEN TO USE IT: Use mutations for any operation that causes a write or side effect on your backend. This includes all CUD (Create, Update, Delete) operations: user signup, profile edits, posting a comment, or deleting a photo. It is the standard and only way to perform writes in a conventional GraphQL API.

WHEN NOT TO USE IT: Never use mutations for read-only data fetching. That is the sole purpose of GraphQL Queries. Using a mutation for a read-only operation violates the specification's core convention that mutations cause side effects. While technically possible to implement, it's a major anti-pattern that makes the API's intent confusing and unpredictable.

ONE CANONICAL EXAMPLE: To add a new to-do item, your client would send a mutation like mutation AddTodo(text: String!) { addTodo(text: text) { id text completed } }. Here, addTodo is the mutation field. After the server creates the to-do, it returns a JSON object with its new id, text, and completed status, which you can use to immediately update your client-side state without another network request.

Read the original → apollographql.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.