GraphQL

GraphQL Mutations with Example

January 25, 2018

author:

GraphQL Mutations with Example

# What is GraphQL Mutation?

Fetching and rendering data of course matters, but making changes to the stored data is also an important aspect for APIs. In GraphQL, we can make changes to the current data with Mutations. With respect to REST, Mutations in GraphQL correspond to POST/PUT/PATCH/DELETE methods. With GraphQL mutations, we can perform three tasks: Insert, Update and Delete.

# GraphQL Mutations Example

Maintaining simplicity, the syntax of GraphQL mutations is quite similar to the query.

mutation {
  createAuthor(name: "Khushi", email: "khushi@hashvel.com") {
    email
  }
}

Here, createAuthor is the root field with name and email as arguments. Note that we also specified a payload email which will be returned on successful request completion. We can retrieve (query) any data we want on this server round trip to optimize the server usage. Here’s how a response of the mutation may look like:

{
 "data": {
  "createAuthor": {
    "email": "khushi@hashvel.com"
  }
 }
}

We can also add a unique id to the Author Schema. It can be generated by server.

type Author {  
  id: ID!
  name: String!
  email: String!
  posts: [Post!]!
}

# Define Mutation in GraphQL Schema

As we discussed in previous posts, before running any query or mutation, we must have its schema defined at the back end. To define mutation schema, we have to add a type mutation in the schema with required arguments:

type Mutation {
  createAuthor(name: String!, email:  String!): Author!
}

Note that by now, we have query and mutation schema ready for the back end. And here’s how it looks:

type Query {
 getPosts: [Post!]!
}

type Mutation {
  createAuthor(name: String!, email:  String!): Author!
}

type Author { 
 id: ID!
 name: String!
 email: String!
 posts: [Post!]!
}

type Post {
 title: String!
 body: String!
 author: Author!
}

# Query v/s Mutations

As we already discussed, Query is used for fetching data from a back-end database while Mutation is used to perform insert, update, delete operations. There is one more significant difference between query and mutation. Queries run in parallel whereas mutation fields are executed in series – one request field at a time.

This restricts ending up in a race condition when we, for instance, send two createAuthor mutations in a single request. Since it runs in series, the first mutation is guaranteed to finish before the second one runs.

Conclusion:

In this segment we learned how mutations in GraphQL are used with its schema setup. At last, we also saw how query is different from mutation.

Leave a comment

Your email address will not be published. Required fields are marked *