Implement A GraphQL Mutation With No Data Return
GraphQL stands as a robust query language tailored for APIs, offering a versatile and effective means to engage with our data. Typically, when addressing mutations, the focus revolves around updating or adding data on the server. Nevertheless, there are occasions where a mutation is required without returning any data. In GraphQL, the standard protocol involves enforcing non-nullability for fields within the schema. This means that a field is obligated to return a value and cannot be null unless specifically denoted as nullable. Let us delve into understanding how to implement a GraphQL mutation without returning data in Java.
1. Introduction
GraphQL is an API syntax that defines how to fetch data from one or more databases. It was developed by Facebook to optimize the RESTful api calls.
- It is a data query and manipulation language for API’s. It is faster, simple, and easier to implement
- It follows the client-driven architecture and gives a declarative way to fetch and update the data
- It has a graphical structure where objects are represented by nodes and edges represent the relationship between the nodes
- Provides high consistency across all platforms
- It doesn’t have any automatic caching system
1.1 Application components in GraphQL
In graphql, there are two types of application components.
1.1.1 Service-side components
The server-side component allows parsing the queries coming from the graphql client applications and consists of 3 components i.e. query, resolver, and schema. Apollo is the most popular graphql server.
Component | Description |
Query | A query is a client request made by the graphql client for the graphql server. It is used to fetch values and can support arguments and points to arrays. field and arguments are two important parts of a query |
Resolver | Helps to provide directions for converting graphql operation into data. Users define the resolver functions to resolve the query to the data. They help to separate the db and api schema thus making it easy to modify the content obtained from the db |
Schema | It is the center of any graphql server implementation. The core block in a schema is known as a type |
Mutation | It allows to modify the server data and returns an object based on the operation performed |
1.1.2 Client-side components
The client-side components represent the client which is a code or a javascript library that makes the post request to the graphql server. It is of two types i.e.
- GraphiQL – Browser-based interface used for editing and testing graphql queries and mutations
- Apollo client – State management library for javascript that enables local and remote data management with graphql. Supports pagination, prefetching data, and connecting the data to the view layer
2. Implementing GraphQL Mutation Without Returning Data in Spring Boot
In a Spring Boot application, GraphQL is a powerful tool for building APIs. When creating mutations, sometimes there’s a need to perform actions without returning any data.
First, let’s set up a basic Spring Boot application with GraphQL support. You can use tools like Spring Initializr or create a new project in your IDE with Spring Boot and GraphQL dependencies.
2.1 Defining the Mutation
In GraphQL, a mutation is a type of operation used to make changes to the data on the server side. While queries are used for fetching data, mutations are used for modifying data. Mutations are analogous to the POST
, PUT
, PATCH
, or DELETE
methods in RESTful APIs.
A mutation typically consists of three parts:
- Mutation keyword: It indicates that the operation is a mutation.
- Mutation name: It specifies the name of the mutation operation.
- Input parameters: They represent the data that needs to be provided to perform the mutation.
Now, mutation without returning data refers to a scenario where a mutation is performed on the server side, but the client does not need any specific data back from the server as a result of the mutation. This could be the case for mutations that trigger actions or side effects on the server, such as updating a database, sending an email, or logging an event, where the client is only interested in knowing if the mutation was successful or not.
To create a mutation without returning data, define a mutation in your GraphQL schema with the necessary input parameters:
type Mutation { performAction(input: InputData!): Boolean }
Here, InputData
is the input type containing the necessary fields for the action.
2.2 Implementing the Mutation Resolver
A mutation resolver in GraphQL is a function or method responsible for handling the execution of a mutation operation defined in the GraphQL schema. Resolvers are essentially functions that resolve the value of a field in a GraphQL query or mutation.
For mutations specifically, mutation resolvers are responsible for executing the logic associated with the mutation operation. This logic could involve actions such as creating, updating, or deleting data on the server side, interacting with external services or databases, performing validation, and handling any errors that may occur during the mutation process.
In a GraphQL server implementation, mutation resolvers are typically organized into resolver classes or components. Create a resolver for the mutation in your Spring Boot application:
import org.springframework.stereotype.Component; import com.coxautodev.graphql.tools.GraphQLMutationResolver; @Component public class MutationResolver implements GraphQLMutationResolver { public boolean performAction(InputData input) { //Act here return true; // Or false based on success/failure } }
2.3 Using Nullable Type
To make a field nullable in GraphQL, use the Nullable
annotation:
import graphql.annotations.annotationTypes.GraphQLField; import graphql.annotations.annotationTypes.GraphQLNonNull; public class InputData { @GraphQLField @GraphQLNonNull private String data; // Other fields and methods }
In the above example, data
field is marked as non-null by default. To make it nullable, remove the @GraphQLNonNull
annotation.
2.4 Creating Custom Scalar
A custom scalar in GraphQL is a scalar type that is not one of the built-in scalar types. Custom scalars allow you to define and use your scalar types in GraphQL schemas to represent specialized data types that are not covered by the built-in scalars.
Custom scalars are particularly useful when you need to represent non-standard or complex data types in your GraphQL schema. For example, you might want to define custom scalar types for representing dates, times, geographic coordinates, or other specialized data formats.
To create a custom scalar in GraphQL, define a class implementing the Coercing
interface:
import graphql.schema.Coercing; import graphql.schema.GraphQLScalarType; public class CustomScalar { public GraphQLScalarType createCustomScalar() { return GraphQLScalarType.newScalar() .name("CustomScalar") .description("Custom scalar for specific type") .coercing(new Coercing() { @Override public Object serialize(Object dataFetcherResult) { return dataFetcherResult.toString(); } @Override public Object parseValue(Object input) { return input.toString(); } @Override public Object parseLiteral(Object input) { return input.toString(); } }) .build(); } }
Use this scalar in your schema definition by specifying its name.
3. Conclusion
Implementing a GraphQL Mutation without returning data in a Spring Boot application is straightforward. By defining the mutation, implementing the resolver, and optionally using nullable types and custom scalars, you can build powerful APIs to handle various actions.