Prerequisite
If you don’t know about GraphQL, this link is a good place to start. This article would assume that reader has basic knowledge of REST as well as Java.
Mutation
Drawing comparison from REST, any verb (e.g. GET, POST, PUT etc) are able to do server changes. But as convention, we use POST to make new resource and PUT for updating resource. In an almost similar fashion, any query in GraphQL can be used for server side changes, however, we set up a convention that any server side write should be done via mutations.
Extending the example in last post, we will try to write a mutation that creates a driver(i.e. stores the firstName as well as last name) of a given car Id.
Schema Change
type Mutation {
createDriver(id: ID!, firstName: String!, lastName: String!):
Driver!
}
The mutation field returns an object type which in the example shown above is Driver. As in cases of query, we can ask for nested object. This is meant to ask for updated state after the mutation.
Data Provider
We have established in our last post that every field in GraphQL has a data provider associated with it. The one for this simple mutation is not different. We have added a new type for the added mutation as shown below.
.type(TypeRuntimeWiring.newTypeWiring("Mutation")
.dataFetcher("createDriver", graphQLDataFetchers.setDriverDataFetcher()))
The updated class should look like one below:
Data Fetcher
The data fetcher for the mutation field is shown in gist below. Here, we have used a in-memory data storage but this can connect to any database or call some other API as well.
Mutation Query
mutation {
createDriver(id: "car1", firstName: "Prathamesh", lastName: "Waghmode") {
id
firstName
}
}

Github repository
Reference:
GraphQL Java
GraphQL Official
Apollo Blog
If you liked this article and would like one such blog to land in your inbox every week, consider subscribing to our newsletter: https://skillcaptain.substack.com