Skip to the workspace
Pebellslearn by building
Mutations  ›  Lesson

What are Mutations

What are Mutations? 12 minA mutation is the operation type for changing data, declared on the Mutation root type with input types for its arguments and answered with a normal selection so the client can read back the changed data in the same request.

graphql / What are Mutations

Explore each scene at your own pace.

01 · The rule

The rule

What are Mutations

A reader finishes The Salt Road and leaves a five-star review. That is not a read: it changes data on the server. In GraphQL, writes get their own operation type, the mutation, so everyone reading the code knows that this request has side effects.

The rule

Queries read, mutations write; both answer with a selection.

The schema lists writes on a separate root type, Mutation. Their arguments are usually grouped into an input type, declared with input instead of type:

input AddReviewInput {
  bookId: ID!
  rating: Int!
  text: String
}

type Mutation {
  addReview(input: AddReviewInput!): Review!
  updatePrice(bookId: ID!, price: Float!): Book!
}

A client calls one with the mutation keyword, and, just like a query, selects fields from what comes back:

mutation AddReview($input: AddReviewInput!) {
  addReview(input: $input) {
    id
    rating
    book {
      title
      reviews(first: 3) { rating }
    }
  }
}
{ "input": { "bookId": "b1", "rating": 5, "text": "Could not put it down." } }

Things to notice:

  • The mutation keyword is required. The { ... } shorthand always means a query, so { addReview(...) } would look for addReview on Query and fail.
  • The response is a normal selection. Asking for the new review's id and the book's latest ratings lets the page refresh in the same trip, and client caches update the stored book automatically.
  • Input types are for data going in; object types are for data coming out. You cannot pass a Review as an argument, and you cannot select fields from an AddReviewInput.

Nothing in the language physically stops a query resolver from writing data, but doing so breaks everyone's expectations: clients retry and cache queries freely. Keep side effects in mutations.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.