API Fundamentals Course
API Fundamentals
/
Beginner

GraphQL Mutations

Definition

The GraphQL equivalent of REST `POST`, `PUT`, `PATCH`, and `DELETE` requests. Mutations are used to modify server-side data and return a response.

Explain Like I'm New

Queries are for reading. Mutations are for changing. If you want to create a new user, you send a Mutation. The best part is, immediately after creating the user, the Mutation allows you to ask for exactly what data you want returned about the newly created user.

Real World Example

Submitting a 'Sign Up' form. The frontend executes a `createUser` mutation, passing the email and password as arguments, and requests that the server return the new user's ID and Auth Token.

Common Use Cases

  • •Creating records
  • •Updating records
  • •Deleting records

Terminal Output

bash / terminal
/* GraphQL Mutation Example */ mutation CreateNewUser($email: String!, $password: String!) { # The Action: Call the 'createUser' function on the server createUser(email: $email, password: $password) { # The Return Request: # If successful, give me back these specific fields id email createdAt } }

Interview Questions

basic

  • While Queries are used to read data, what are Mutations used for?

intermediate

  • Why does a GraphQL Mutation usually include a block of requested fields at the very end of it?

Flash Cards

Question

Mutations used for?

Click to reveal answer
Answer

Writing, updating, or deleting data.

Question

Why include fields?

Click to reveal answer
Answer

GraphQL allows you to mutate data and query the updated result in the exact same request. By including fields at the end, you tell the server: 'Create the user, and then immediately return the new user's ID and Email to me so I can update the UI.'