Docs
Launch GraphOS Studio
You're viewing documentation for an upcoming version of this software. Switch to the latest stable version.

Mutations in Apollo Kotlin


Mutations are that modify back-end data. As a convention in , queries are read and are write operations.

Defining a mutation

You define a in your app just like you define a , except you use the mutation keyword. Here's an example for upvoting a post:

UpvotePost.graphql
mutation UpvotePost($postId: Int!) {
upvotePost(postId: $postId) {
id
votes
}
}

And here's an example schema snippet that supports this :

schema.graphql
type Mutation {
upvotePost(postId: Int!): Post
}
type Post {
id: Int!
votes: Int!
content: String!
}

The of the Mutation type (such as upvotePost above) usually describe the actions that can perform. These usually take one or more , which specify the data to create or modify.

Mutation return types

The return type of a Mutation usually includes the backend data that's been modified. This provides the requesting client with immediate information about the result of the .

In the example above, upvotePost returns the Post object that's just been upvoted. Here's an example response:

{
"data": {
"upvotePost": {
"id": "123",
"votes": 5
}
}
}

For more information on return types, see Designing mutations.

Generating mutation classes

Similar to queries, are represented by instances of generated classes, conforming to the Mutation interface. Constructor are used to define . You pass a mutation object to ApolloClient#mutation(mutation) to send the to the server, execute it, and receive typed results:

val upvotePostMutation = UpvotePostMutation(postId = 3)
val response = apolloClient.mutation(upvotePostMutation).execute()

Using fragments in mutation results

In many cases, you'll want to use results to update your UI. Fragments are a great way to share result handling between queries and :

mutation UpvotePost($postId: Int!) {
upvotePost(postId: $postId) {
...PostDetails
}
}

Passing input objects

The includes input objects as a way to pass complex values to . Input objects are often used for , because they provide a compact way to pass in objects to be created:

mutation CreateReviewForEpisode($episode: Episode!, $review: ReviewInput!) {
createReview(episode: $episode, review: $review) {
stars
commentary
}
}
val reviewInput = ReviewInput(stars = 5, commentary = "This is a great movie!")
val response = apolloClient.mutation(CreateReviewForEpisodeMutation(episode = Episode.NEWHOPE, review = reviewInput)).execute()
Previous
Queries
Next
Subscriptions
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company