Course contentsShow
← Software Engineering
Lesson 808 of 1,93325. RPC and GraphQL API DesignFree lesson

Mutations: Writing Data in GraphQL

Defining and executing mutations to create, update, or delete data, and understanding mutation conventions.

Mutations: Writing Data in GraphQL

What you'll learn: How to modify server-side data in GraphQL using mutations to create, update, and delete resources.

The Write Side of GraphQL

You've learned that queries read data from a GraphQL server. Mutations are how you write data—creating new records, updating existing ones, or deleting them. While queries and mutations are technically similar under the hood, separating them by name makes your intent crystal clear: "I'm changing something, not just looking."

Think of it like the difference between browsing a library catalog (query) versus checking out a book, returning it, or updating your account information (mutation).

Defining Mutations in Your Schema

In your GraphQL schema, you define mutations in a special Mutation type, just like you defined queries in the Query type:

type Mutation {
  createUser(name: String!, email: String!): User
  updateUser(id: ID!, name: String): User
  deleteUser(id: ID!): Boolean
}

Each mutation acts like a function: it takes input arguments and returns a result type.

Executing Mutations from the Client

When a client executes a mutation, it uses the mutation keyword instead of query:

mutation {
  createUser(name: "Alice", email: "alice@example.com") {
    id
    name
    email
  }
}

Mutation Conventions

By convention:

  • Name mutations with verbs: createUser, updatePost, deleteComment
  • Return the modified object: Helps clients update their local state without a follow-up query
  • Mutations execute sequentially: Unlike queries (which can run in parallel), multiple mutations in one request run one after another, ensuring predictable side effects

Key Takeaway:
Mutations are GraphQL's mechanism for writing data, defined in the Mutation type with verb-based names, executed sequentially, and conventionally return the modified resource to avoid extra round-trips.