Mutations — GraphQL

A mutation changes data on the server (create, update, delete), like POST, PUT and DELETE in REST, and must be written with the word mutation. Its fields live…

So far we have only read data. The Bookshop also needs to add new books and change the stock when a delivery arrives. For that, GraphQL has the mutation: the operation for creating, updating or deleting data on the server. It plays the part of POST, PUT, PATCH and DELETE in REST, while a query is like GET.

It's like the cashier at a bookshop. You hand over a change form ("add this book", "change that book's stock"), the cashier processes them one at a time in order, then hands you a receipt. You pick what's on the receipt yourself, just like a query.

Mutations in the schema

A mutation is a field on type Mutation. In the Bookshop schema:

type Mutation {
  createBook(input: CreateBookInput!): Book!
  updateStock(id: ID!, stock: Int!): Book
}

input CreateBookInput {
  title: String!
  authorId: ID!
  price: Int!
  stock: Int!
}

Creating a book: createBook

Ahmad Tohari has no book in the shop yet. Add The Dancer:

mutation {
  createBook(input: {
    title: "The Dancer"
    authorId: 4
    price: 95000
    stock: 3
  }) {
    id
    title
    author {
      name
    }
  }
}
{
  "data": {
    "createBook": {
      "id": "4",
      "title": "The Dancer",
      "author": { "name": "Ahmad Tohari" }
    }
  }
}

Changing the stock: updateStock

This Earth of Mankind is sold out (stock 0). A delivery of 7 copies arrives:

mutation {
  updateStock(id: 2, stock: 7) {
    title
    stock
    status
  }
}
{ "data": { "updateStock": { "title": "This Earth of Mankind", "stock": 7, "status": "IN_STOCK" } } }

status changes too, from SOLD_OUT to IN_STOCK, because its resolver works the status out from the stock. That's why a mutation returns the changed object: the client knows the new state right away, without a second query.

Two mutations in one request

One mutation operation may hold several fields. Use aliases so their keys differ:

mutation {
  first: updateStock(id: 3, stock: 4) {
    stock
  }
  second: updateStock(id: 3, stock: 2) {
    stock
  }
}

Both change the stock of Beauty Is a Wound (id 3). Before you look at the answer, guess: is the final stock 4 or 2?

{ "data": { "first": { "stock": 4 }, "second": { "stock": 2 } } }

The GraphQL specification requires the top-level fields of a mutation to run in order (serially): first finishes completely, selection set included, before second starts. So the final stock is 2. The top-level fields of a query may run at the same time, because reading data doesn't get in each other's way.

When a mutation fails

There are two kinds of failure. Validation rejects the operation before anything runs, so no data changes and the response holds only errors. A resolver can refuse while running, and its field's result becomes null.

What is sent Rejected by Response
updateStock(id: 2, stock: -1) resolver "Stock cannot be negative", data: { "updateStock": null }
createBook with authorId: 9 resolver "Author not found", data: null
createBook without stock in the input validation Expected value of type "CreateBookInput" to include required field "stock", found: { title: "The Dancer", authorId: 4, price: 95000 }.
updateStock(id: 2, stock: "7") validation Int cannot represent non-integer value: "7"
updateStock(id: 2, stock: 7) without a selection set validation Field "updateStock" of type "Book" must have a selection of subfields. Did you mean "updateStock { ... }"?
createBook inside query { ... } validation Cannot query field "createBook" on type "Query".

Look at the difference between the first two rows. updateStock returns a nullable Book, so only that field is null. createBook returns Book!, so its null moves up until the whole data is null. The messages "Stock cannot be negative" and "Author not found" are written by the Bookshop resolvers. The validation messages come from the GraphQL engine (here graphql-js 17.0.2). Apollo Server 5 uses graphql-js 16: there the third row's message reads Field "CreateBookInput.stock" of required type "Int!" was not provided., and the other messages in this table are the same.

The naming many APIs use

⚠️ Mutation rejected, or a different result?

📌 Payloads with messages for the user

Many big APIs don't throw an error for an ordinary user mistake such as a negative stock. The mutation returns a payload instead: a special type holding the result and a list of problems, for example type UpdateStockPayload { book: Book, userErrors: [UserError!]! }. The client reads userErrors to show messages on the form, and the response's errors is kept for truly unexpected failures. Shopify, for one, uses this userErrors pattern in its GraphQL API. The "Error Handling in GraphQL" lesson comes back to this pattern.

TL;DR: A mutation changes data on the server (create, update, delete), like POST, PUT and DELETE in REST, and must be written with the word mutation. Its fields live on type Mutation, take arguments (often one input of an input type), and return the changed object. You pick the result's fields yourself: createBook(...) { id title } returns only the new book's id and title. Several top-level fields in one mutation run in order, so stock 4 then 2 ends at 2. Validation rejects before anything changes; a resolver that refuses makes its field null (and data: null when the result is Book!). Name them verb + noun (createBook, updateStock), and never send a mutation with GET.

⚡ A mutation changes data

Write:

mutation {
  createBook(input: {
    title: "The Dancer"
    authorId: 4
    price: 95000
    stock: 3
  }) {
    id
    title
  }
}

Meaning: A mutation is for changing data on the server: creating, updating or deleting. The word mutation in front is required. Without it, the operation counts as a query.

⚡ You pick what comes back

Write:

mutation {
  updateStock(id: 2, stock: 7) {
    title
    stock
    status
  }
}

Meaning: After the argument's parentheses comes a selection set, exactly like a query. A mutation returns the changed object, so the client knows right away that stock is now 7 and status is IN_STOCK, without a second query.

⚡ Two mutations, run in order

Guess first: in one mutation, first sets book 3's stock to 4, then second sets it to 2. What is the final stock?

It ends at 2. The top-level fields of a mutation must run in order: first finishes before second starts.

Meaning: A query's top-level fields may run at the same time; a mutation's always run top to bottom.

What you will learn