0
0
GraphQLquery~5 mins

Create mutation pattern in GraphQL

Choose your learning style9 modes available
Introduction

A create mutation lets you add new data to your database. It helps you save new information easily.

When a user signs up and you want to save their details.
When adding a new product to an online store.
When submitting a new comment on a blog post.
When recording a new order in a sales system.
Syntax
GraphQL
mutation CreateItem($input: ItemInput!) {
  createItem(input: $input) {
    id
    name
    description
  }
}

The mutation keyword starts the operation to change data.

$input is a variable holding the new data you want to add.

Examples
This mutation adds a new user with username and email.
GraphQL
mutation CreateUser($input: UserInput!) {
  createUser(input: $input) {
    id
    username
    email
  }
}
This mutation adds a new product with title and price.
GraphQL
mutation AddProduct($input: ProductInput!) {
  addProduct(input: $input) {
    id
    title
    price
  }
}
Sample Program

This mutation adds a new book with its title and author.

GraphQL
mutation CreateBook($input: BookInput!) {
  createBook(input: $input) {
    id
    title
    author
  }
}

# Variables:
# {
#   "input": {
#     "title": "The Great Gatsby",
#     "author": "F. Scott Fitzgerald"
#   }
# }
OutputSuccess
Important Notes

Always define the input type to specify what data is needed.

Use variables to keep your mutation flexible and reusable.

The server returns the new item's fields you ask for after creation.

Summary

Create mutations add new data to your database.

Use mutation keyword with input variables.

Request the fields you want back after creating the item.