[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
First of all, my GraphQL schema is defined:
There are a few rules we have to follow when mapping a GraphQL schema to a controller.
Querytypes are mapped with
Mutationtypes are mapped with
- Method names of the controller class need to match the type names (in this example
employees, departments, departmentById, updatedDepartmentName)
- Arguments are mapped with
Putting these rules together, the controller implementation looks like:
The GraphQL endpoint can be tested with your favorite Rest Client tool (such as Insomnia, Postman, etc). By default, the GraphQL endpoint is at
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:
Lastly, here are test queries: