0
0
GraphqlHow-ToBeginner · 3 min read

How to Create Data Using Mutation in GraphQL

In GraphQL, you create data by using a mutation operation, which modifies server-side data. A mutation defines the action and the data you want to create, and the server returns the newly created data as a response.
📐

Syntax

A GraphQL mutation has this basic structure:

  • mutation: keyword to start a mutation operation.
  • mutationName: a descriptive name for the mutation.
  • input: the data you want to create, passed as arguments.
  • selection set: fields you want returned after creation.
graphql
mutation CreateItem($input: ItemInput!) {
  createItem(input: $input) {
    id
    name
    description
  }
}
💻

Example

This example shows how to create a new book with a title and author using a mutation. The server responds with the book's ID and title.

graphql
mutation CreateBook {
  addBook(title: "The GraphQL Guide", author: "John Doe") {
    id
    title
  }
}
Output
{ "data": { "addBook": { "id": "1", "title": "The GraphQL Guide" } } }
⚠️

Common Pitfalls

Common mistakes when creating data with mutations include:

  • Not defining required input arguments correctly.
  • Forgetting to request fields in the selection set, resulting in empty responses.
  • Using query instead of mutation keyword for data changes.

Always check your schema for required inputs and return fields.

graphql
/* Wrong: Missing required input argument */
mutation {
  addBook {
    id
  }
}

/* Right: Provide all required inputs */
mutation {
  addBook(title: "New Book", author: "Jane") {
    id
    title
  }
}
📊

Quick Reference

PartDescription
mutationKeyword to start a mutation operation
mutationNameName of the mutation for clarity
input argumentsData you want to create or change
selection setFields you want returned after mutation

Key Takeaways

Use the mutation keyword to create or modify data in GraphQL.
Always provide required input arguments as defined in the schema.
Request the fields you want returned after the mutation in the selection set.
Check your schema for exact mutation names and input types.
Avoid using queries for data changes; use mutations instead.