0
0
GraphQLquery~5 mins

Mutation syntax in GraphQL

Choose your learning style9 modes available
Introduction

Mutations let you change data in a database, like adding or updating information.

When you want to add a new user to a system.
When updating a product's price in an online store.
When deleting a comment from a blog post.
When changing a user's password.
When submitting a form that saves data.
Syntax
GraphQL
mutation MutationName {
  mutationFieldName(input: InputType) {
    returnedField1
    returnedField2
  }
}

Start with the keyword mutation followed by an optional name.

Inside braces, call the mutation field with input data, then specify what data you want back.

Examples
Adds a new user named Alice and asks for the new user's id and name in response.
GraphQL
mutation {
  addUser(name: "Alice", age: 30) {
    id
    name
  }
}
Updates the price of a product with id 123 and returns the updated id and price.
GraphQL
mutation UpdatePrice {
  updateProductPrice(id: "123", price: 19.99) {
    id
    price
  }
}
Deletes a comment by id and returns if it was successful and a message.
GraphQL
mutation {
  deleteComment(id: "456") {
    success
    message
  }
}
Sample Program

This mutation adds a new book with a title and author, then returns the book's id, title, and author.

GraphQL
mutation {
  createBook(title: "Learn GraphQL", author: "Sam") {
    id
    title
    author
  }
}
OutputSuccess
Important Notes

Mutations always change data, unlike queries which only read data.

You can request specific fields in the response to get only what you need.

Give your mutation a name to help with debugging and tracking.

Summary

Mutations let you add, update, or delete data in GraphQL.

Use the mutation keyword followed by the mutation call and requested return fields.

Always specify what data you want back after the mutation runs.