Back to Examples

GraphQL service - Mutations

The Ballerina graphql module allows defining GraphQL Mutation operations. A remote method inside a graphql:Service represents a field in the root Mutation object type. Therefore, if a remote method is present inside the graphql:Service, the auto-generated schema will have the Mutation type. Each remote method in the service will be added as a field of the Mutation type. The field name will be the remote method name and the field type will be the return type of the remote method. Use the Mutation operation when performing any side-effects on the underlying data system.

Note: GraphQL mutations are actions that are expected to mutate the state of the server. Ballerina uses remote methods to handle such cases. Therefore, these remote methods are usually named using verbs.

import ballerina/graphql;

// Defines a `record` type to use as an object in the GraphQL service.
type Profile readonly & record {|
    int id;
    string name;
    int age;
|};

// Defines an in-memory table to store the profiles.
table<Profile> key(id) profiles = table [
        {id: 1, name: "Walter White", age: 50},
        {id: 2, name: "Jesse Pinkman", age: 25}
    ];

service /graphql on new graphql:Listener(9090) {

    // A resource method represents a field in the root `Query` operation.
    resource function get profile(int id) returns Profile {
        return profiles.get(id);
    }

    // A `remote` method represents a field in the root `Mutation` operation. This `remote` method
    // is used to update the name for the given profile ID and returns the updated `Profile` value.
    // If the ID is not found, this will return an error.
    remote function updateName(int id, string name) returns Profile|error {
        if profiles.hasKey(id) {
            Profile profile = profiles.remove(id);
            Profile updatedProfile = {
                id: profile.id,
                name: name,
                age: profile.age
            };
            profiles.put(updatedProfile);
            return updatedProfile;
        }
        return error(string `Profile with ID "${id}" not found`);
    }
}

Run the service by executing the following command.

$ bal run graphql_mutations.bal

Then, send the following document to update the name.

mutation {
    updateName(id: 1, name: "Mr. Lambert") {
        id
        name
    }
}

To send the document, execute the following cURL command.

$ curl -X POST -H "Content-type: application/json" -d '{ "query": "mutation { updateName(id: 1, name: \"Mr. Lambert\") { id name } }" }' 'http://localhost:9090/graphql'{"data":{"updateName":{"id":1, "name":"Mr. Lambert"}}}

Tip: You can invoke the above service via the GraphQL client.

Related links

PreviousInput types
NextSubscriptions