GraphQL Kotlin Tutorial with Spring Webflux

Julian muñoz
The Startup
Published in
5 min readDec 13, 2020

--

A green constelation artistic frame, with some blue tones.

In this tutorial, we are going to build a simple API with the GraphQL kotlin libraries from Expedia Group.

GraphQL kotlin provides collection of libraries to ease the development of GraphQL applications with kotlin.

GraphQL Kotlin documentation:

https://expediagroup.github.io/graphql-kotlin/docs/getting-started.html

In this example we use the Spring boot autoconfiguration library graphql-kotlin-spring-server. This library built on top of Spring Webflux, provides us with automatic schema generation, graphql-playground and out of the box support for kotlin coroutines.

Configuration

Create a Kotlin project with gradle in spring initializr:

This project uses the following dependencies:

This project runs with h2 database. As reference, I also added MySQL dependencies if you to use a regular database instead or replace with your preferred database dependency, and it’s r2dbc driver.

We tell graphql-kotlin to expose schema objects in the base package com.prueba.graphkt and configure the GraphQL web server. We specify the base package in the application.yml. You can take the included application.properties file located at src/main/resources and replace it with the application.yml file.

H2 database needs no configuration, but if you are using MySQL, set up r2dbc adding the following configuration and adjusting the configuration for your database.

The project uses the schema.sql, and the data.sql files in the classpath to bootstrap database data.

To load these files in the database, we have to create a db initializer class and specify of our sql files.

Queries

Let’s get to the actual code now. We start with a basic query that fetches a mock weapon database.

First we implement the query interface to create the entry point for our graphql server. Graphql-kotlin would pick the methods in our class and generate the schema for us. In this first example we have a find all function witch returns all the weapons, and a find by id function witch receives the weapon id as parameter.

Our first repository is simple, a set of mock data.

This is the data class.

Now we start the application and graphql-kotlin automatically creates the schema and the playground for us. Let’s head up to localhost:8080/playground and try some queries.

Mock weapon query test.

We see at the left, the query to retrieve our mock weapons. We are asking our graphql server to fetch the id and the name of the weapon. There’s a play button in the mid section, click it to make the query. At the right section we see the actual result of the query and two tabs.

The first tab is the documentation of the API and the second is the schema generated by graphql-kotlin. If we click the docs tab, we see a nice autogenerated API documentation.

Autogenerated documentation with our API types and query definitions.

The second tab contains our schema.

Our autogenerated API schema with the MockWeapon type and the mockWeapon query.

As we see, graphql-kotlin has generated the graphql schema for us with just defining a query class, and a data class.

Now let’s play around a little. I’m going to return a different type, List in our mockWeapons query to see what happens. This will generate an error.

Despite our source code compiles, we get the below error.

An error after we try to autogenerate the GraphQL schema with th wrong type for a query.

If we have a query returning a different type in our mock query, graphql-kotlin would throw a reflection error, as this library uses kotlin reflection to generate the schema matching the query name with the return type name.

Finally, we revert our source code to fix the error.

Now we saw the basics of graphql-kotlin, we are going to a more realistic example using the actual Spring Webflux this library runs on.

Webflux and coroutines

In this section we are working with a more realistic setup, fetching data from the database using the Webflux ReactiveCrudRepository.

Our data class is the same as the mock version.

Notice the @Id annotation needed for Spring Data in order to map our data classes to database records. Now let’s see the query class.

We use the Webflux ReactiveCrudRepository findAll and findById stock methods to fetch our weapons, then we use the Reactor’s kotlin coroutines api to transform the resulting Flux to a suspend function. Kotlin coroutines have built-in support for graphql-kotlin-schema-generator, if your are using other asynchronous models like RxJava and Reactor, you have to specify your own data fetcher. Form more info about other asynchronous models, follow this link https://expediagroup.github.io/graphql-kotlin/docs/schema-generator/execution/async-models.

Now we have finish our graphql API, let’s try some queries on graphql playground.

The result of the graphql weapon query after we finish our API.

We are querying now data from our database and have the full schema. Let’s try some more queries.

A composed query. We are fetching in one trip, the name of the weapon with id 5 and the entire weapon list.

There you go, a fully working graphql server easily implemented with Spring boot and graphql-kotlin.

We have a lot of flexibility for defining our queries with this setup, for example, we can arrange our application in three layer architecture. For a tree layer architecture setup, we can move the query class logic to a service.

Our query class be the following.

The application is still working as expected.

That’s it for this tutorial.

Conclusions

We created a graphql server with graphql-kotlin. The implementation was easy as we only have to provide the data with the help of kotlin coroutines. We can have Spring boot application as complex as we need and allow our clients to decide on how they fetch the API. As long as the query name matches the resulting entity name. The next steps is learning how to make paginated queries with the help of Spring data, avoid DDOS attacks because of recursive queries and to secure our API with Spring security.

For more information on GraphQL Kotlin check the library documentation and examples: https://expediagroup.github.io/graphql-kotlin.

Link of finished tutorial repo:

Originally published at http://github.com.

--

--

Julian muñoz
The Startup

I'm a software developer with interest in frontend development, mobile functional and reactive programming.