GraphQL Spring Boot starter with Java
Create a GraphQL API with Spring Boot Framework and JPA
GraphQL is both an API query language and a runtime for executing those queries using your current data. GraphQL allows clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools by providing a clear and intelligible description of the data in your API.
In this article, we will create a simple Airport location app.
Generate the project
Go to https://start.spring.io/ and generate a project, don’t forget to add Spring Web, H2 Database, and Spring Data JPA dependencies.
Add dependencies
To enable the use of GraphQL, add these two dependencies below.
Schema:
The GraphQL schema defines the data points available through an API. The schema describes the data types and their relationships, as well as the available operations, such as queries for retrieving data and mutations for creating, updating, and deleting data.
In the resources folder, create a file with “.graphqls“ extension, the whole name will be “location.graphqls”.
The “!” means the field is required.
Entity and Repository
Now create an entity called Location. The Location should have three attributes: id, name, and address as already mentioned in the schema. And of course generate Getters, Setters, and Constrictors.
Then a repository, for this example, uses just CrudRepository, and extends Location entity.
Queries & Exceptions:
1. Query:
A query allows us to retrieve data. Each query can have a specific object that it returns based exactly on the fields specified on the query, you can add or remove fields to match the exact data you need to fit your specific use case.
Create a resolver package, then add a new Query class that implements GraphQLQueryResolver and adds @Component annotation. We only need to add the queries that we previously entered into location.graphqls.
2. Mutator:
Mutations in GraphQL allow it to update the data stored on the server. Unlike a query, mutations like creating, updating, or deleting will change your data.
Now create a mutator package and then add a new class Mutation that implements GraphQLMutationResolver and add @Component annotation. Also, add the mutations that we previously entered into location.graphqls.
3. Exceptions:
Create an exception package and then add a new class LocationNotFoundException that extends RuntimeException and implements GraphQLError.
Now the GraphQL API is ready to use!
Resources:
Source code here.