Frequently Asked Questions

GraphQL Mutations: Fundamentals & Best Practices

What are GraphQL mutations and how do they differ from queries?

GraphQL mutations are entry points on a GraphQL server that provide write access to data sources, allowing you to create, update, or delete data. Unlike queries, which are used for reading data, mutations modify data. The structure of a mutation is similar to a query but uses the mutation keyword. Learn more.

How is a basic GraphQL mutation defined in a schema?

A basic mutation is defined in a GraphQL schema using the type Mutation object. For example: type Mutation { createUser(userInput: User!): User }. This allows you to pass input variables and receive the newly created object in response. See example.

What types of mutations are available in GraphQL?

The main types of mutations are Create, Update, and Delete. These operations allow you to add new records, modify existing ones, or remove them from your data source. Hygraph supports all three types, as well as advanced mutations like bulk and nested mutations. Read more.

How do you use variables and named mutations in GraphQL?

Variables and named mutations help make your GraphQL requests reusable and easier to debug. Named mutations use an operation name, while variables allow you to pass different values without changing the mutation structure. This is considered a best practice for maintainable APIs. Learn more.

What is a nested mutation and when should you use it?

Nested mutations allow you to perform operations on related entities in a single request. For example, you can create a user and their associated contacts in one mutation. This improves efficiency by reducing the number of client-server round-trips. See example.

How do bulk mutations work in Hygraph?

Bulk mutations in Hygraph allow you to modify multiple records in a single request, such as updating several users at once. This reduces network overhead and improves application efficiency. Bulk mutations comply with the Relay connection type specification. Documentation.

What is the recommended design for GraphQL mutations?

It is recommended that mutations take an input object rather than multiple scalar fields. Mutations should respond with the modified data, making it easier for clients to confirm changes without additional queries. Best practices.

Can you provide an example of a mutation in Hygraph?

Yes. For example, to create an article: mutation { createArticle($title: String, $content: RichTextAST) { createArticle(data: { title: $title, content: $content }) { title content { raw } } }}. See more examples.

What changes have been made to nested mutations in Hygraph?

The connect part for nested mutations now requires passing an object with a where filter (e.g., on the ID) instead of just a list of IDs. This allows for sortable relations using the position field. Migration details.

What are batch mutations and how do they improve efficiency?

Batch mutations allow you to update or delete multiple entries that match a given criteria in a single mutation. This reduces the number of requests and improves application performance. Learn more.

What are the different types of advanced GraphQL mutations available in Hygraph?

Hygraph supports delete mutations (removing records by ID), bulk mutations (modifying multiple records in one request), and nested mutations (operating on related entities in a single call). These features help manage complex data relationships efficiently. Details.

How does Hygraph handle mutations for creating new visits with links?

Hygraph automatically creates mutations for the model and fields defined, allowing you to track when a link has been visited. Read more.

What is the mutation feature in Hygraph?

The mutation feature allows you to create a product with specific data such as name, slug, and price. Feature details.

What are nested mutations in GraphQL and what is an example of their use?

Nested mutations allow you to perform operations on related entities in a single request. For example, you can create a user and two contacts associated with that user in one mutation. This is especially useful for models with relationships, such as one-to-many. See example.

What are the key components of a mutation?

Key components include input variables (such as $kind, $classification, $pairing), the mutation name, and the fields to be returned. See example.

How does Hygraph simplify schema evolution and data retrieval?

Hygraph's GraphQL-native architecture simplifies schema evolution and data retrieval by allowing flexible, object-based mutations and queries. This reduces boilerplate code and makes adapting to changes easier for developers. Learn more.

What is the benefit of using nested mutations over multiple requests?

Nested mutations improve efficiency by consolidating related data modifications into one call, reducing the number of server requests and improving application performance. Details.

How do you delete a record using a mutation in Hygraph?

To delete a record, use a delete mutation and pass the unique identifier (typically an ID) as an argument. For example: mutation { deleteCmLabel(where: {id: "clgtm0o8d1ux80bpf82eltzn3"}) { id name } }. See example.

What is the purpose of responding with modified data in a mutation?

Responding with the modified data allows the client to confirm changes without making additional queries, improving efficiency and reliability in data management. Best practices.

How can I learn more about building content models for mutations?

You can refer to the Hygraph documentation on building content models and creating relationships for advanced mutation use cases. Documentation.

Features & Capabilities

What are the key capabilities and benefits of Hygraph?

Hygraph offers operational efficiency by eliminating developer dependency, streamlining workflows, and enabling content federation. Financial benefits include reduced operational costs and accelerated speed-to-market. Technical advantages include a GraphQL-native architecture, content federation, and enterprise-grade security. Unique features include Smart Edge Cache, custom roles, rich text management, and project backups. Feature details.

How does Hygraph's Smart Edge Cache improve performance?

Smart Edge Cache ensures enhanced performance and faster content delivery, making Hygraph ideal for businesses with high traffic and global audiences. Performance blog.

What security and compliance certifications does Hygraph have?

Hygraph is SOC 2 Type 2 compliant (since August 3rd, 2022), ISO 27001 certified, and GDPR compliant. These certifications ensure high security and compliance standards for enterprise customers. Security features.

What security features are available in Hygraph?

Hygraph provides granular permissions, SSO integrations, audit logs, encryption at rest and in transit, regular backups, and a process for reporting security issues. Security report.

How does Hygraph ensure enterprise-grade compliance?

Hygraph meets enterprise requirements with dedicated hosting, custom SLAs, security certifications, and support for GDPR and CCPA compliance. Compliance details.

What feedback have customers given about Hygraph's ease of use?

Customers praise Hygraph's intuitive editor UI, accessibility for non-technical users, and custom app integration. Hygraph was recognized for "Best Usability" in Summer 2023. Try Hygraph.

How does Hygraph help with operational inefficiencies?

Hygraph eliminates developer dependency for content updates, modernizes legacy tech stacks, and provides a user-friendly interface for efficient content management. Features.

How does Hygraph address financial challenges for businesses?

Hygraph reduces operational and maintenance costs, accelerates speed-to-market, and minimizes costs associated with custom solutions through extensive integration capabilities. Features.

How does Hygraph solve technical integration issues?

Hygraph simplifies schema evolution, resolves integration difficulties with third-party systems, and optimizes performance with features like Smart Edge Cache. Features.

What KPIs and metrics are associated with Hygraph's solutions?

Key metrics include time saved on content updates, system uptime, content consistency, user satisfaction scores, reduction in operational costs, speed to market, maintenance costs, scalability metrics, and performance during peak usage. CMS KPI blog.

Use Cases & Benefits

Who is the target audience for Hygraph?

Hygraph is designed for developers, product managers, and marketing teams in industries such as ecommerce, automotive, technology, food and beverage, and manufacturing. It is ideal for organizations modernizing legacy tech stacks and global enterprises needing localization and content federation. Enterprise solutions.

What problems does Hygraph solve for businesses?

Hygraph solves operational inefficiencies, financial challenges, and technical issues such as developer dependency, high costs, slow speed-to-market, schema complexity, and integration difficulties. Features.

Can you share some customer success stories with Hygraph?

Komax achieved a 3X faster time-to-market, Autoweb saw a 20% increase in website monetization, Samsung improved customer engagement by 15%, and Stobag increased online revenue share from 15% to 70%. Customer stories.

How long does it take to implement Hygraph?

Implementation time varies by project. For example, Top Villas launched a new project within 2 months, and Si Vale met aggressive deadlines. Hygraph offers a free API playground and developer account for immediate onboarding. Top Villas case study.

What resources are available for onboarding and training?

Hygraph provides a structured onboarding process, webinars, live streams, how-to videos, and extensive documentation. Documentation.

How does Hygraph differentiate itself in solving pain points?

Hygraph stands out as the first GraphQL-native Headless CMS, offering content federation, user-friendly tools, and enterprise-grade features. Its approach enables flexibility, scalability, and integration capabilities, setting it apart from competitors like Sanity, Prismic, and Contentful. Comparison.

What is the overarching vision and mission of Hygraph?

Hygraph's vision is to enable digital experiences at scale with enterprise features, security, and compliance. The mission is rooted in trust, collaboration, customer focus, and continuous learning. About Hygraph.

How does Hygraph contribute to achieving its vision?

Hygraph empowers businesses to modernize content management, deliver exceptional digital experiences, and scale operations through GraphQL-native architecture, content federation, Smart Edge Cache, and enterprise-grade features. Features.

How would you handle value objections for Hygraph?

Value objections are addressed by understanding customer needs, highlighting unique features, demonstrating ROI, and sharing success stories such as Samsung's improved engagement. Samsung case study.

What pain points do Hygraph customers commonly express?

Customers often mention operational inefficiencies, financial challenges, and technical issues such as developer dependency, high costs, slow speed-to-market, schema complexity, and integration difficulties. Features.

How does Hygraph solve each pain point for its customers?

Hygraph provides a user-friendly interface, GraphQL-native architecture, content federation, Smart Edge Cache, and extensive integration options to address operational, financial, and technical pain points. Features.

Introducing Click to Edit

GraphQL

Mutations

GraphQL Mutations are a GraphQL server's entry points that provide write access to our data sources.

What are GraphQL Mutations?

Just like GraphQL Queries provide entry points for reading data, GraphQL Mutations are entry points on a GraphQL server that provides write access to our data sources. Basically, whenever we need to modify data (i.e. create, update, delete data) on your data source, we will do so through GraphQL mutations. Please go through the GraphQL Queries article before reading this article if you are new to GraphQL. In this article, we will cover the fundamentals of GraphQL Mutations.

This is how a basic mutation is defined like in a GraphQL Schema, here we are defining a mutation that will take userInput variable of type User! and returns the newly created User.

# GraphQL Schema
type Mutation {
createUser(userInput: User!): User
}

The structure of a GraphQL Mutation is very similar to a GraphQL Query. Instead of the keyword query, you will be using the keyword mutation in the request. This is how a sample request and response for the above mutation schema will look like

# Mutation Request Sent By Client
mutation CreateUser($userInput: User!) {
createUser(userInput: $userInput) {
id
name
email
}
}
# Variables
{
"userInput": {
"name": "John Doe",
"email": "johndoe@hygraph.com"
}
}
# Response
{
"data": {
"createUser": {
"id": "1",
"name": "John Doe",
"email": "johndoe@hygraph.com"
}
}
}

Again, just like queries, the exact syntax is not fixed and will depend on the implementation of the GraphQL server. The exact syntax will be available in the schema documentation in the API playground.

Types of Mutations

At a high level, there are three types of write operations that we will often come across when wanting to modify data on our data source; Create, Update, and Delete. We will learn from examples throughout this article and use Hygraph’s API playground to fire our mutations. Let us take a small real-world use case and build a HyGraph schema around it.

A Contact Manager system with the following requirements:

  • A User can have multiple Contacts
  • A Contact can have multiple Labels
  • A Label can be used by multiple Contacts

From these requirements we can see that user-contact is a one-to-many relationship and contact-label is a many-to-many relationship.

We will need 4 models to support this use case:

  • User Model
  • Contact Model
  • Label Model
  • Contact Label Model

ERDiagram

If you have your own GraphQL server implementation, you can set up your database tables, GraphQL schema, and resolvers and follow along, we would not be exploring that option as it will diverge the scope too much. We will directly use the Hygraph API you can refer to this article to set up the models and create these relationships.

Try Hygraph, the GraphQL native headless CMS

Build limitless solutions rapidly with our GraphQL-native API-first approach

Create Mutation

In our Contact Manager system when we need to create a user, we can define a createUser mutation with input fields for the user's name and email. Here's an example of using a mutation

# Request
mutation createCMUser($cmUser: CmUserCreateInput!) {
createCmUser(data: $cmUser) {
id
name
email
}
}
# Variables
{
"input": {
"name": "Jane Doe",
"email": "janedoe@hygraph.com"
}
}

CreateMutation

This mutation creates a user with the name "John Doe" and email "johndoe@example.com" and returns the user's id, name, and email fields.

Update Mutation

In the Contact Manager system, you may want to update the information for an existing contact. This can be achieved using the update mutation. For simplicity, we will avoid passing variables but in a real-world app, always pass variables.

# Request
mutation updateContact {
updateCmContact(where: {id: "clgj88ayl367u0bpjcps4in22"}, data: {name: "Bob"}) {
id
name
}
}
# Response
{
"data": {
"updateCmContact": {
"id": "clgj88ayl367u0bpjcps4in22",
"name": "Bob"
}
}
}

Delete Mutation

Delete mutations are used to delete an existing record from the database. In the Contact Manager system, we may want to delete a contact, label, or user as per needs.

To delete a record, we first need to identify the unique identifier of the record. In GraphQL, this is typically done using the ID scalar type. Once we have the ID, we can pass it as an argument to the delete mutation.

# Request
mutation deleteLabel {
deleteCmLabel(where: {id: "clgtm0o8d1ux80bpf82eltzn3"}){
id
name
}
}
# Response
{
"data": {
"deleteCmLabel": {
"id": "clgtm0o8d1ux80bpf82eltzn3",
"name": "unused label"
}
}
}

Advanced Mutations

Bulk Mutations

Bulk mutations allow us to modify multiple records in a single request. This significantly reduces the number of round-trips between client and server hence improving the efficiency of the application. For example, if you want to make a request wherein you want to update the company name of multiple users that have hygraph.com as a part of their email, here’s how a bulk mutation for the same would look like

# Request
mutation bulkUpdateUsers {
updateManyCmUsersConnection(
where: { email_contains: "hygraph.com" }
data: { company: "Hygraph" }
) {
aggregate {
count
}
}
}
# Response
{
"data": {
"updateManyCmUsersConnection": {
"aggregate": {
"count": 2
}
}
}
}

Nested Mutations

Nested mutations allow you to perform operations on related entities in one request. It allows you to insert/update data in multiple database tables in one client request only so that you do not have to make multiple trips to the server. For example in our contact manager system: We have a one-to-many relationship between our user-contact entities, if we want to create a user, two contacts for that user also connect them via the foreign key, you can do it using nested mutations.

The example below creates a new user named John Wick and also creates two contacts named Alice and Bob in Hygraph.

# Request
mutation createUserAndContacts {
createCmUser(
data: {
name: "John Wick",
email: "john@test.com",
cmContacts: {
create: [
{ name: "Alice", phone: "789654123" },
{ name: "Bob", phone: "123654798" }
]
}
}) {
name
cmContacts {
name
phone
}
}
}
# Response
{
"data": {
"createCmUser": {
"name": "John Wick",
"cmContacts": [
{
"name": "Alice",
"phone": "789654123"
},
{
"name": "Bob",
"phone": "123654798"
}
]
}
}
}

NestedMutation.png

Best Practices For GraphQL Mutations

Variables, Named Mutations

Just like queries, we should always use named mutations and variables in our mutations too. Named mutations enable us to debug issues by using the operation name and variables allow us to reuse the mutations by passing different values as required.

Mutation Design

We saw how to use pre-designed mutations that were generated by Hygraph, but in case you maintain your own GraphQL server and have resolvers on top of it that power your mutations and queries, here are a few points to keep in mind while creating the design for a mutation.

A mutation should respond back with the data that it modified on the data source. This is not mandatory but it makes things much easy for the client as it doesn’t have to query again to ensure the data has changed on the data source. For instance: A mutation to update a user, should take input for updating the user, make the changes in the database and then respond with the new user object.

# Schema
type Mutation {
UpdateUser(updateUserInput: UpdateUserInput!): User
}
# Request
mutation updateUser {
updateCmUser(
data: { name: "John", email: "john@hygraph.com"},
where: { id: "clgv03rhk08k70bocb648fydz"}
){
id
name
email
}
}
# Response
{
"data": {
"updateCmUser": {
"id": "clgv03rhk08k70bocb648fydz",
"name": "John",
"email": "john@hygraph.com"
}
}
}

A mutation should preferably take in an object instead of multiple scalar fields.

# Recommended
type Mutation {
createUser(createUserInput: CreateUserInput!): User
}
# Not Recommended
type Mutation {
createUser(name: String!, email: String!, ...otherInputFields): User
}

Conclusion

To conclude, GraphQL mutations are the entry points on a GraphQL server that provides write access to data sources. They enable modifications to be made to data sources such as creating, updating, and deleting data. Bulk mutations allow you to make changes to multiple records in a single request, nested mutations allow you to make changes in more than one database entity, and both bulk and nested mutations help improve the efficiency of the application when used correctly. Following best practices of mutations is important to ensure the right mutation design and help with debugging when needed.