This blog post was written under the Pusher Guest Writer program.

GraphQL is a modern alternative to REST for writing web-based APIs, allowing for the server to expose a schema describing the entire graph of data, and for the client query against that schema. This allows for much richer data to be obtained with less overhead, due to needing less requests and no need for returning undesired fields.

Kotlin is a modern language that executes on the JVM, and while it has gotten a lot of press recently for use in Android development it has a huge amount of potential for server-based development as well. It has recently been blessed for use in Spring 5. However, it works incredibly well in Spring 4 already. Kotlin can be useful to make our applications significantly easier to develop and understand, and to remove a number of potential sources of bugs.

This article will show how to build a GraphQL Service from scratch, including setting up Spring Boot and working with a data access layer. The database will be entirely abstracted for purposes of this article, but plugging in to a real data store can be easily achieved.

The end result of this will be a simple family tree API, allowing us to get details of people and follow links from one person to another.

Prerequisites
This article assumes that you already have some knowledge of the Kotlin programming language and the GraphQL API system. You can learn more about these at their appropriate websites if you do not already know them.

In order to follow the article, you will need to have a recent JDK installed, and a recent version of Maven. Everything else will be handled as we work through the article.

GraphQL Support in Spring Boot

GraphQL can be supported in Spring Boot by use of the graphql-spring-boot-starter working in conjunction with the graphql-java-tools module. In addition, there is a graphiql-spring-boot-starter that can be included to give access to the GraphiQL tool built directly into our application. This is a fantastic way of testing our API when it is running.

The graphql-java-tools module allows us to write our GraphQL schema in schema files, and then connect it to Java classes—written in Kotlin here—to actually represent the data objects and to provide values to them. The graphql-spring-boot-starter does all of the work to automatically configure everything and ensure that it works as desired.

GraphQL Java Tools expects that we will have special resolver classes registered in the Spring context that do the majority of the work. These come in a number of forms:

  • GraphQLQueryResolver – classes implementing this interface are responsible for the root query fields
  • GraphQLMutationResolver – classes implementing this interface are responsible for the root mutation fields
  • GraphQLResolver – classes implementing this interface are responsible for resolving complex fields on a specific type

All types in the GraphQL Schema correspond to a class in the Java runtime. There needs be no connection between the Java class name and the GraphQL type, but the same class must always be used for the same type. Classes are determined automatically at startup by introspecting the various resolvers to see what is returned.

Any time a Java class used to represent a GraphQL type has a method with a name matching a field on the type, this can be used to return the value for that field. The rules for this are:

  • <fieldName>
  • is <fieldName> – only for boolean fields
  • get <fieldName>

If the GraphQL field takes any parameters then these will be provided, and the method must expect them.

If the field is more complex, a resolver can be written instead. This always has a class name matching the Java bean, with the suffix Resolver, and the method rules are exactly the same as above, except that the method will always take the Java bean as a first parameter.

For example, if we have a GraphQL type as follows:

    type Person {
        id: ID!
        name: String!
        relatedTo: [Relatonship]!
    }

we could have a Java type:

    data class Person(val id: String, val name: String)

and a Resolver class:

    class PersonResolver : GraphQLResolver<Person> {
        fun getRelatedTo(person: Person) : List<Relationship>
    }

Setting up the build

The easiest way to get started on a new Spring Boot project is to use the Spring Initializr. This is a simple form that you can fill out, and then download a fully working Spring Boot project. We can get our initial build working by filling out the form as follows:

This will then give us a Maven project set up with:

  • Spring Boot 1.5.6
  • Spring 4.3.10
  • Kotlin 1.1.4
  • Embedded Tomcat 8.5.16

We can then build the application by executing mvn clean install, and start a development version using mvn spring-boot:run.

Adding GraphQL to the build

Adding GraphQL to the build is as simple as adding the appropriate dependencies, as follows:

    <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphiql-spring-boot-starter</artifactId>
            <version>3.6.0</version>
    </dependency>
    <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphql-java-tools</artifactId>
            <version>4.0.0</version>
    </dependency>
    <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphql-spring-boot-starter</artifactId>
            <version>3.6.0</version>
    </dependency>

These three dependencies give us everything that we need to not only get GraphQL available in our application, but also to serve GraphiQL to test it.

This will by default host the GraphQL API on the /graphql endpoint, and accept POST requests to it. This can be changed in *application.properties**,* but if you do so, then GraphiQL will no longer work with it.

Writing our initial schema

At this point, nothing has actually happened. We need to write our schema before any actual functionality changes happen.

Schemas are written in .graphqls files, and can be anywhere on the classpath. There can be as many of these as we like, so we can easily split our schema into functional areas if we like. The most recent version of GraphQL Java Tools also supports the extend type **syntax so that we can split the root Query and Mutation types across files as well.

Initially we are going to write a trivial schema to ensure that everything works correctly. As such, we will write a file src/main/resources/graphql/familytree.graphqls that looks as follows:

    type Query {
        # The API Version
        version: String!
    }

Writing our initial Query Resolver

We now need to have a Query Resolver to power this. Until this turns up in the Spring context, no GraphQL functionality is enabled. Once we have this then everything else starts working.

For this field, we simply need a class as follows:

    @Component
    class Query : GraphQLQueryResolver {
        fun version() = "1.0.0"
    }

The version() method directly corresponds to the same field in the GraphQL Schema.

We can now try this out in GraphQL by starting our service – mvn spring-boot:run – and visiting http://localhost:8080/graphiql. If you try the following query:

    {
      version
    }

You should see something like this:

Looking up People

Now that we have a working GraphQL API, we can do something more interesting. The first part of our family tree is to be able to retrieve a single person by their ID.

Firstly, we need to represent a Person in our system. The Kotlin class for this will be as follows:

    data class Person(
        val id: String,
        val name: String
    )

This is just a simple data class that gives us an ID and a name.

Next, we need to be able to load these. We are going to use a hard-coded DAO layer instead of a real database for simplicity’s sake. This will look as follows:

    @Component
    class PersonDao {
        private val data = mutableListOf(
            Person(id = "qeii", name = "Queen Elizabeth II"),
            Person(id = "pp", name = "Prince Philip"),
            Person(id = "pc", name = "Prince Charles"),
            Person(id = "pw", name = "Prince William")
        )

        fun getPersonById(id: String) = data.firstOrNull { person -> person.id == id }
    }

This gives some hard-coded data – taken from the British Royal Family – and a simple method to get one of these by ID.

We then need to wire this up to the GraphQL API. For this we need a schema definition. This can go in the existing file or a new one:

    type Person {
        id: ID!
        name: String!
    }

    extend type Query {
        getPersonById(id: ID!) : Person
    }

We then need a Query resolver to load the person from the DAO:

    @Component
    class PersonQueryResolver(
            private val personDao : PersonDao
    ) : GraphQLQueryResolver {
        fun getPersonById(id: String) = personDao.getPersonById(id)
    }

This is then everything needed to support this field. This time we can try this query:

    {
      getPersonById(id:"qeii") {
        name
      }
    }

to get this result:

Note how we’re asking for a single field from a single record, and that is all that we are getting back from the server. Even though our code always returns the entire record, the GraphQL Service only returns the exact data that was requested.

Relationships Between People

The final part of our API is to be able to see who is related to whom. This will be done using another DAO and Model class for simplicity.

Our model class will be as follows:

    data class Relationship(
        val from: String,
        val to: String,
        val relationship: String
    )

We are going to assume that any relationship is between exactly two people, and is of a specific type – e.g. PARENT, SPOUSE, etc.

Our DAO for this will be similar to before, with some hard-coded data:

    @Component
    class RelationshipDao {
        private val data = mutableListOf(
                Relationship(from = "qeii", to = "pp", relationship = "SPOUSE"),
                Relationship(from = "pp", to = "qeii", relationship = "SPOUSE"),
                Relationship(from = "qeii", to = "pc", relationship = "PARENT"),
                Relationship(from = "pp", to = "pc", relationship = "PARENT"),
                Relationship(from = "pc", to = "pw", relationship = "PARENT")
        )

        fun getRelationshipsFromPerson(personId: String) = 
                data.filter { relationship -> relationship.from == personId }

        fun getRelationshipsOfTypeFromPerson(personId: String, type: String) = 
                data.filter { relationship -> relationship.from == personId }
                        .filter { relationship -> relationship.relationship == type }
    }

Again, we have some hard-coded data that corresponds with our people records, and a couple of methods to access this data.

We can now update our schema to work with this data:

    type Person {
        id: ID!
        name: String!
        relationships(type: String): [Relationship]!
    }

    type Relationship {
        from: Person!
        to: Person!
        relationship: String!
    }

This lets us go from a person to their relationships, and then from a relationship to the people involved.

Finally, we need some resolvers. There will be two of these. Firstly, for resolving the Relationship from the Person record:

    @Component
    class PersonResolver(private val relationshipDao: RelationshipDao) : GraphQLResolver<Person> {
        fun relationships(person: Person, type: String?) = 
                when (type) {
                    null -> relationshipDao.getRelationshipsFromPerson(person.id)
                    else -> relationshipDao.getRelationshipsOfTypeFromPerson(person.id, type)
                }
    }

And then for resolving the Person from either side of a Relationship record:

    @Component
    class RelationshipResolver(private val personDao: PersonDao) : GraphQLResolver<Relationship> {
        fun getFrom(relationship: Relationship) = personDao.getPersonById(relationship.from)
        fun getTo(relationship: Relationship) = personDao.getPersonById(relationship.to)
    }

We can then see this in action by looking up the relationships of one of our people, using this query:

    {
      getPersonById(id:"qeii") {
        name
        relationships {
          from {
            name
          }
          to {
            name
          }
          relationship
        }
      }
    }

And we will see this result:

Or, if we want something a bit more targeted, we can write a query that only selects one type of relationship:

    {
      getPersonById(id:"qeii") {
        name
        relationships(type:"SPOUSE") {
          from {
            name
          }
          to {
            name
          }
          relationship
        }
      }
    }

And get this as the result:

Adding Mutations

So far we have only concentrated on reading data from the system. We can also add and change data in the system just as easily.

GraphQL uses the concept of Mutations for anything that will cause data to change. In reality there is no difference in how queries and mutations work from the point of view of the code. However, by convention a Query should never cause data to change whereas it is expected that a Mutation will always do so.

For our example, we will allow for API callers to create new people in our data store.

Firstly, we need to support this in our PersonDao class:

    fun createPerson(name: String): Person {
        val person = Person(id = UUID.randomUUID().toString(), name = name)
        data.add(person)
        return person
    }

We then need to add a Mutation to our schema. Because we don’t already have one to extend we’ll write it new here:

    type Mutation {
        createPerson(name: String!) : Person!
    }

And finally we need a resolver:

    @Component
    class PersonMutationResolver(private val personDao: PersonDao) : GraphQLMutationResolver {
        fun createPerson(name: String) = personDao.createPerson(name)
    }

That’s everything we need. We can execute this mutation to create a new person in our service:

    mutation {
      createPerson(name:"Princess Anne") {
        id
        name
        relationships {
          relationship
        }
      }
    }

and we will see this response.

Notice that we can access the complete graph from the brand new Person object purely on the return value from the mutation. This means that we could potentially create a Person with a relationship already in place, and navigate this without needing to make an additional request.

Summary

GraphQL is a powerful alternative to REST for writing APIs. Adding support for it into a Spring Boot application is a very simple prospect, and the libraries work seamlessly with the Kotlin language to make writing our code a very simple affair.

The full source code for this example can be downloaded from GitHub, or you can write your own.