Create, Update, Delete, and Publish Content with GraphQL Mutations

Whether you're building a static website, eCommerce store, Content Hub, or Mobile App, Hygraph powered GraphQL Mutations will bring your project to life.

Jamie Barton
Jamie Barton
GraphQL Mutations with GraphCMS

Since the very beginning, Hygraph has boasted a GraphQL Mutations API alongside the traditional Query Content API, and it's free!

One of the biggest benefits of working on the Jamstack is that you get to pick the best of breed APIs. Whether you're building a static website, eCommerce store, Content Hub, or Mobile App, Hygraph powered GraphQL Mutations will bring your project to life.

For each model you create in your project, Hygraph automatically generates a mutation to create, update, delete, publish, and unpublish your content entries (records). These mutations are also backed up by a flexible, and secure permissions API.

Imagine we have a list of products, and we want to allow users to "upvote" products. The UI could look something like this:

Upvote products on click

You can also try this for yourself here.

To make this possible, you might reach for a serverless function, and you can easily build serverless functions with Next.js API routes. Here's a taste of what that looks like to create and publish votes for our products:

// https://github.com/hygraph/hygraph-examples/blob/master/using-mutations/src/pages/api/upvote.js
import { GraphQLClient } from 'graphql-request';
export default async ({ body }, res) => {
const hygraph = new GraphQLClient(
process.env.HYGRAPH_ENDPOINT,
{
headers: {
authorization: `Bearer ${process.env.HYGRAPH_MUTATION_TOKEN}`,
},
}
);
const { createVote } = await hygraph.request(
`mutation upvoteProduct($id: ID!) {
createVote(data: { product: { connect: { id: $id } } }) {
id
}
}`,
{ id: body.id }
);
res.status(201).json({ id: createVote.id });
};

On each request we send a GraphQL mutation to our Hygraph endpoint with the id as a variable from the body of the request payload.

We are using connect to tell Hygraph which product we want to reference when creating a new Vote. The createVote mutation is automatically generated for us when we create a model named Vote.

In the function above we are just creating an upvote, but what about if we want to publish this too? By default, Hygraph only returns PUBLISHED content, so when we call createVote, we'll be creating a DRAFT record.

Client to Hygraph request flow

If we want to show the new vote count, we can also call the publishVote mutation after we create it!

await hygraph.request(
`mutation publishUpvote($id: ID!) {
publishVote(where: { id: $id }, to: PUBLISHED) {
id
}
}`,
{ id: createVote.id }
);

You can read more about all that is possible with the Hygraph Mutation API over at the docs.

Have fun!