[Spring Boot] GraphQL with Spring Boot using graphql-spring-boot-starter

In this article, we will look at a sample Spring Boot application using Spring GraphQL Boot Starter. This example will cover how to implement controller for GraphQL schema and how to write test code.

According to the Spring GraphQL reference, the following dependency needs to be added to pom.xml.

pom.xml

First of all, my GraphQL schema is defined:

src/main/resources/graphql/schema.graphqls

There are a few rules we have to follow when mapping a GraphQL schema to a controller.

  1. Query types are mapped with @QueryMapping
  2. Mutation types are mapped with @MutationMapping
  3. Method names of the controller class need to match the type names (in this example employees, departments, departmentById, updatedDepartmentName)
  4. Arguments are mapped with @Argument

Putting these rules together, the controller implementation looks like:

Controller implementation

The GraphQL endpoint can be tested with your favorite Rest Client tool (such as Insomnia, Postman, etc). By default, the GraphQL endpoint is at POST /graphql.

GraphQL endpoint can be tested with WebGraphQlTester. The approach was to define some queries to test against and use them in test cases. Of course queries can be typed up in string if preferred.

This test code consists of one query type and one mutation type. The full test code looks like below:

Test code

Lastly, here are test queries:

employees.graphql
updateDepartmentName.graphql

Welcome to Jay’s blog. This blog is for myself to keep notes. Feel free to take a look and share.