GraphQL with Spring Boot java

Sumitra Dhakre
7 min readFeb 21, 2022

--

Graphql developed by Facebook in 2012 is an exciting and quite new concept compared to REST and SOAP which have been around since 2000. I personally like how simple and easy it’s to use.

This quick tutorial will give you an idea of how to use GraphQl with spring boot in java. So let's get started!!

What is GraphQL?

GraphQl is a query and manipulation language for developing APIs. Unlike traditional REST APIs GraphQl allows the client to specify which data is required and only return that data. To do the same thing with REST you’ll need multiple endpoints. This helps to develop lightweight manageable APIs. For information make sure to check out the official documentation.

GraphQL Schema

A GraphQL schema describes what the API can be queried for. I like to think of it as a blueprint of the API. The schema tells us what types and queries the API has. Most objects are normal objects that define the data. But there are two special types in the schema mentioned below, used for querying the data they are also the entry point of every GraphQL query.

Query Type: It’s like the GET method. Used to read the data.

Mutation Type: It’s used for the Create/ Update/Delete operations on the data.

What are we building?

For this tutorial, we’re going to make a Book API. The API will query the Database and reply to the GraphQL requests.

Requirements

Setup you’ll need for this project:

  • Basic understanding of spring boot and spring JPA
  • Java 11
  • Docker installed on your machine
  • Intellij or IDE of your choice
  • Postman for testing the API

Project setup

Open your Spring boot project. You can also quickly create it with a spring initializer. We’ll need the graphql spring boot kickstart starter and graphql java tools dependencies:

<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>12.0.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>12.0.0</version>
</dependency>

By default, the graphql is deployed at /graphql endpoint but this can be easily changed by defining the endpoint name in the application.properties for spring. For this tutorial, I am using the default one.

endpoint mapping

Building Schema

After this, let’s build the schema. The schema for this API is very simple.

schema for Book API

Here we have a Book object type that contains the Author object type. Then we have some query and mutation operations on these object types. For having coloration and syntax checks you can install the graphql IntelliJ plugin.

schema file

All .graphqls files are picked up by graphql spring boot starter and mapped to the java beans. The schema files have the .graphqls extension and can be present anywhere on the classpath. Here I have declared the whole schema in one file, but you can split it up into multiple files. The only requirement is that, there should be only one root query and up to one root mutation type. Now let's create the POJO classes.

model classes

Here they are also the entity classes for the database. It’s just for demo purposes only. Generally, it’s a good practice to separate your data layer from the service layer.

NOTE: Makes sure the POJO/DTO classes have the exact same name and attributes as the Schema. GraphQL error messages are not always very clear. Trust me it will save you from wasting hours on debugging.

repository class

Then we need to create our repository class to get data from the DB. With spring data JPA is very quick to do this.

Query Resolvers

Query resolvers classes are spring @component classes and must implement GraphQLQueryResolver to use the methods provided by graphql-kickstart.

Book query resolver

Here we just @Autowire or create a constructor for these repositories to fetch the data from DB. I just used the spring JPA repository method findAll() to make things easier and fast.

Mutation Resolver

Just like the query resolvers, mutation resolvers are component classes and must implement GraphQLMutationResolver.

Book Mutation Implementation

As mentioned in the schema, here we have the create and delete book object.

Lazy GraphQLResolver<T>

Now Author part here is a little different we can configure our repository class to find an author for each book or we can ask GraphQL to do it for us through lazy data fetching. The latter is much easier. To do this I created GraphQLResolver<Book> class to resolve Author for each book by using bookId.

author resolver

why Lazy? Because GraphQL won’t do this part if the user doesn’t ask for the author in response. We’ll see it in action soon when we’ll test the queries. This also makes it efficient if your API has strict/ limited network and data constraints.

From the Book.id we can easily find the author with the repository method findAuthorByBookId(). This not only makes the dev quick and easy but also reduces the repository method or complex queries we would have written.

Run the project

To run the application you will need a docker desktop installed on your machine. I like using docker it just makes things easier to test and deploy.

Just do a maven clean install to create our jar

mvn clean build

or you can use the maven tab on IntelliJ

Intellij maven toolbar

After that go ahead and open up the terminal tab in IntelliJ to run the docker containers.

docker-compose up

Here we can see both of our containers have started. The book-mysql container contains our database. Below is what the DB looks like in HeidiSQL.

BOOK API DB

The book-api container is for the API as you can see in the spring boot startup logs below.

book-api container startup

With the docker plugin, you can see the logs for each container more clearly and can start or stop containers directly from this GUI.

Testing the API

Since our important parts of the code are complete let's do the testing and see GraphQL in action. Here, I am using postman you can use any HTTP client of your choice. I like postman because it has an option for graphql which is super easy to use and start testing the API. Note that all GraphQL requests are POST methods.

allBook query in postman

As expected we get all the records from the book with the author. The best part about graphql is that you get what you asked for. So let's change this request to just get books and no author details.1

allBook query without author data

Here you can see we only got book data and since I have used GraphQL Resolver this time the author's data wasn’t even queried thus, making it more efficient.

Now let's look into some mutation by deleting a book with the id 1.

deleteBook mutation in postman

And now if we do findAll() to see all books we won’t see this deleted book.

allBook data after the deletion

I hope this brief tutorial will help you to understand some GraphQL basics. There are other many cool things you can do with GraphQL by using input types, enums, scalar types, nested queries, error handling, exceptions, etc but they all deserve their own tutorial. For now, don’t hesitate to check out my project on GitHub to start playing with GraphQL. If you like this article be sure to check out my other articles related to spring boot.

Happy coding😊!!

--

--