Getting started with GraphQL and Spring Boot

Saloo Gupta
3 min readJun 8, 2020

--

GraphQL is a query language for your API . It has many advantages when it comes to retrieve the data and also query required fields.

When using it with spring-boot, development was so easy and quick.Let’s start how to integrate GraphQL with spring boot and test it.

Step 1: Create a spring-boot application using Spring Initializr https://start.spring.io/

Step 2: Import the project in your IDE and define your GraphQL dependencies.

Step 3: Create a schema file for types and queries and keep under resources folder with extension .graphqls

Types — It represent a kind of object you want to fetch from your service. Each type should have a POJO defined in Spring. Every field defined in schema must be present in POJO. You can have other attributes in your class and GraphQL will not throw any exception but will ignore it.

Query — It can be understood as entry points. Every query should be resolved in a class with same signature which we will discuss later.

Step 4: For all queries defined in schema file , a class is created which implements GraphQLQueryResolver. Actually any class implementing this will be searched for methods that are defined in schema file.

Step 5 : If you have defined any Object inside type as above Address in Employee , you need to write resolvers to fetch the data. GraphQL will fetch only if you have defined resolvers for it so that unnecessary data fetching is skipped. In this case we create a class that implements GraphQLResolver(a field resolver). This is different from above as GraphQLQueryResolver which resolves entry points.

Step 6: Finally start the spring-boot:run and open the url for testing http://localhost:8080/graphiql

GraphiQL is a tool for schema introspection and query debugging.

I have used H2 Database to feed some data and also lombok to create my data objects like Employee and Address. Complete source code can be found here GraphQLDemo.

Hope it helps!!!!.

--

--

Saloo Gupta
Saloo Gupta

Written by Saloo Gupta

Senior Full Stack Developer. | *** Angular & GraphQL *** | Make your life worth living. Share knowledge and Learn Together.