Skip to content

GraphQL Mutations

Mutations in GraphQL are used to modify data on the server — such as creating, updating, or deleting records. While queries fetch data, mutations change state and can also return data after the change.


Basic Mutation Structure

A mutation operation resembles a query but uses the mutation keyword.

Example: Create a Post

mutation CreatePost {
  createPost(title: "Hello World", content: "This is my first post") {
    id
    title
    content
  }
}
  • createPost is a mutation field defined in the schema.
  • You can select which fields you want back from the newly created post.

Using Variables with Mutations

Variables make mutations dynamic and reusable.

Mutation:

mutation CreatePost($input: CreatePostInput!) {
  createPost(input: $input) {
    id
    title
    content
  }
}

Variables:

{
  "input": {
    "title": "Hello World",
    "content": "This is my first post"
  }
}

Input Types

Mutations often use input types to encapsulate arguments.

input CreatePostInput {
  title: String!
  content: String!
}

type Mutation {
  createPost(input: CreatePostInput!): Post
}

Multiple Mutations in One Request

You can send multiple mutations in a single operation:

mutation {
  createPost(input: { title: "Post 1", content: "Content 1" }) {
    id
  }
  updatePost(id: "123", input: { title: "Updated Title" }) {
    id
    title
  }
}

The order of execution is guaranteed to be sequential.


Response Structure

Like queries, mutation responses mirror the selection set requested.

{
  "data": {
    "createPost": {
      "id": "1",
      "title": "Hello World",
      "content": "This is my first post"
    }
  }
}

Best Practices

  • ✅ Use descriptive names for mutation fields (e.g., createUser, deleteComment).
  • ✅ Use input types for cleaner and more maintainable APIs.
  • ✅ Return the affected object or relevant data after mutation.
  • ✅ Validate inputs and handle errors gracefully.
  • ✅ Keep mutations idempotent when possible.

Tools & Libraries


Summary

  • Mutations are the way to change data in GraphQL APIs.
  • They support arguments and return data.
  • Using variables and input types keeps your API flexible and clean.