13. Mutation response
5m

Overview

So far, we've only been working with one type of : queries. These are read-only operations to retrieve data. To modify data, we need to use another type of GraphQL operation: , which are write operations.

In this lesson, we will learn about common conventions for designing and mutation responses

Mutations

On to the next feature in our MusicMatcher project: adding tracks to an existing playlist.

Let's take a look at the corresponding REST API method that enables this feature: POST /playlists/{playlist_id}/tracks.

https://spotify-demo-api-fe224840a08c.herokuapp.com/v1/docs

Mock REST API with POST endpoint

From the documentation, we need the following parameters:

  • playlist_id - The ID of the playlist, as a string (required)
  • position - An integer, zero-indexed, where we want to insert the track(s)
  • uris - A comma-separated string of uri values corresponding to the tracks we want to add

The method then returns an object with a snapshot_id property that represents the state of the playlist at that point in time.

All right, now how do we enable this functionality in ?

Designing mutations

Let's start with our schema.

For names, we recommend starting with a verb that describes the specific action of our update (such as add, delete, or create), followed by whatever data the mutation acts on.

For the return type of a , we could return the the mutation is acting on. However, we recommend following a consistent Response type for responses.

Mutation responses

We'll need to account for any partial errors that might occur and return helpful information to the client. We recommend adding three common to all responses:

  • code: an int that refers to the status of the response, similar to an HTTP status code.
  • success: a bool flag that indicates whether all the updates the was responsible for succeeded.
  • message: a string to display information about the result of the on the client side. This is particularly useful if the mutation was only partially successful and a generic error message can't tell the whole story.

Then, we'll also have a for the we're mutating (Playlist, in our case). In certain , this could be multiple objects!

As for naming conventions, return types usually end with the word Payload or Response.

The AddItemsToPlaylistPayload type

Following the best practices we covered, we'll name our AddItemsToPlaylist. Let's first create the return type for this : AddItemsToPlaylistPayload.

Under Types, we'll create a new class file called AddItemsToPlaylistPayload.

Types/AddItemsToPlaylistPayload.cs
namespace Odyssey.MusicMatcher;
public class AddItemsToPlaylistPayload
{
}

Then, we'll add the properties for code, success and message.

Types/AddItemsToPlaylistPayload.cs
[GraphQLDescription("Similar to HTTP status code, represents the status of the mutation.")]
public int Code { get; set; }
[GraphQLDescription("Indicates whether the mutation was successful.")]
public bool Success { get; set; }
[GraphQLDescription("Human-readable message for the UI.")]
public string Message { get; set; }

The object we're mutating in this case is a Playlist type, which is nullable because it's possible that something can go wrong in the !

Types/AddItemsToPlaylistPayload.cs
[GraphQLDescription("The playlist that contains the newly added items.")]
public Playlist? Playlist { get; set; }

Lastly, we'll add the constructor. Remember to make the playlist parameter nullable! It's possible that the could fail and we don't receive a playlist object.

Types/AddItemsToPlaylistPayload.cs
public AddItemsToPlaylistPayload(int code, bool success, string message, Playlist? playlist)
{
Code = code;
Success = success;
Message = message;
if (playlist != null) {
Playlist = playlist;
}
}

A new entry point: Mutation

Under Types, we'll create a new class file called Mutation.

Types/Mutation.cs
namespace Odyssey.MusicMatcher;
public class Mutation
{
}

Next, we'll write the function for our AddItemsToPlaylist . It will return the AddItemsToPlaylistPayload type. We'll add a description for it too.

Types/Mutation.cs
[GraphQLDescription("Add one or more items to a user's playlist.")]
public AddItemsToPlaylistPayload AddItemsToPlaylist()
{
}

Then, we'll hard-code the results of the for now. Small steps! We'll create a new AddItemsToPlaylistPayload instance, passing in 200 for code, true for the success status, a successful message and a hard-coded Playlist object.

Types/Mutation.cs
return new AddItemsToPlaylistPayload(
200,
true,
"Successfully added items to playlist.",
new Playlist("6Fl8d6KF0O4V5kFdbzalfW", "Sweet Beats & Eats")
);

Our needs to know about this new entry point to the schema. Much like the Query type, we'll need to call AddMutationType on the and pass in the Mutation type.

Program.cs
builder.Services
.AddGraphQLServer()
.AddQueryType<Query>()
.AddMutationType<Mutation>()
.RegisterService<SpotifyService>();

Save all these changes and restart the server.

Explorer time!

Time to take our for a spin! Back in Sandbox Explorer, we'll create a new workspace tab.

In the Documentation panel, let's navigate back to the root of our schema. Beside Query, we can see the Mutation type.

https://studio.apollographql.com/sandbox/explorer

Explorer - mutation added

Let's add the addItemsToPlaylist and all the subfields inside it. For the playlist sub, select the name for now.

GraphQL operation
mutation AddItemsToPlaylist {
addItemsToPlaylist {
code
message
success
playlist {
name
}
}
}

Run the .

https://studio.apollographql.com/sandbox/explorer

Explorer - mutation response

Response data
{
"data": {
"addItemsToPlaylist": {
"code": "200",
"message": "Added items to playlist successfully",
"success": true,
"playlist": {
"name": "Sweet Beats & Eats"
}
}
}
}

Much like responses, our response followed the same shape as our mutation!

Practice

Which of these are good names for mutations based on the recommended conventions above?
In the mutation response type (AddItemsToPlaylistPayload), why is the modified object's return type (Playlist) nullable?

Key takeaways

  • are write used to modify data.
  • Naming usually starts with a verb that describes the action, such as "add," "delete," or "create."
  • It's a common convention to create a consistent response type for responses.

Up next

We'll learn best practices for inputs and return real data.

Previous

Share your questions and comments about this lesson

This course is currently in

beta
. Your feedback helps us improve! If you're stuck or confused, let us know and we'll help you out. All comments are public and must follow the Apollo Code of Conduct. Note that comments that have been resolved or addressed may be removed.

You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.