Groovy / Maven

Micronaut GraphQL

Learn how to use Micronaut GraphQL.

Iván López
On this guide
In this section

Getting Started

In this guide, we will create a Micronaut application written in Groovy that uses GraphQL to expose some data.

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives 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.

What you will need

To complete this guide, you will need the following:

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide --build=maven --lang=groovy
Note
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

GraphQL

Add the following dependency:

pom.xml
<dependency>
    <groupId>io.micronaut.graphql</groupId>
    <artifactId>micronaut-graphql</artifactId>
    <scope>compile</scope>
</dependency>

By default, the GraphQL endpoint /graphql is enabled, so you don’t need to add any extra configuration.

Describe your schema

Create the file schema.graphqls in src/main/resources directory:

src/main/resources/schema.graphqls

Configure Jackson

For Jackson serialization with GraphQL it’s necessary to add the following configuration:

src/main/resources/application.properties
jackson.serialization-inclusion=ALWAYS

This prevents Jackson from removing null or empty values from the response. These are often required by GraphQL clients.

Book and Author classes

Create Book and Author classes that will mimic the data we want to expose:

groovy/src/main/groovy/example/micronaut/Book.groovy
package example.micronaut

import groovy.transform.Immutable
import io.micronaut.core.annotation.Introspected

@Introspected
@Immutable
class Book {

    String id
    String name
    int pageCount
    Author author
}
groovy/src/main/groovy/example/micronaut/Author.groovy
package example.micronaut

import groovy.transform.Immutable
import io.micronaut.core.annotation.Introspected

@Introspected
@Immutable
class Author {

    String id
    String firstName
    String lastName
}

Data repository

To keep this example simple, instead of retrieving the information from a database we will keep it in memory and just return it from there. In a real-world example you will use any external storage: relational database, SQL database, etc.

Create DbRepository

groovy/src/main/groovy/example/micronaut/DbRepository.groovy

Data Fetchers

With a Data Fetcher we bind the GraphQL schema, and our domain model and execute the appropriate queries in our datastore to retrieve the requested data.

Create class GraphQLDataFetchers

groovy/src/main/groovy/example/micronaut/GraphQLDataFetchers.groovy

Factory

Create the following factory that will bind the GraphQL schema to the code and types.

groovy/src/main/groovy/example/micronaut/GraphQLFactory.groovy

Running the Application

To run the application, use the ./mvnw mn:run command, which starts the application on port 8080.

We want to execute a GraphQL query to retrieve a book by its id:

query {
  bookById(id:"book-1") {
    name,
    pageCount,
    author {
      firstName
      lastName
    },
  }
}

Run the following curl request:

curl -X POST 'http://localhost:8080/graphql' \
     -H 'content-type: application/json' \
     --data-binary '{"query":"{ bookById(id:\"book-1\") { name, pageCount, author { firstName, lastName} } }"}'
{"data":{"bookById":{"name":"Harry Potter and the Philosopher's Stone","pageCount":223,"author":{"firstName":"Joanne","lastName":"Rowling"}}}}

One of the nice features about GraphQL is that the client can decide the fields, and the order they want to retrieve. Now we send the following request:

curl -X POST 'http://localhost:8080/graphql' \
     -H 'content-type: application/json' \
     --data-binary '{"query":"{ bookById(id:\"book-1\") { pageCount, name, id } }"}'
{"data":{"bookById":{"pageCount":223,"name":"Harry Potter and the Philosopher's Stone","id":"book-1"}}}

Notice that now the application only responds with pageCount, name and id fields, in that order.

Test the application

For testing the application we will use Micronaut HTTP Client to send a POST request to the /graphql endpoint. Create the following class:

groovy/src/test/groovy/example/micronaut/GraphQLControllerSpec.groovy
package example.micronaut

import io.micronaut.core.type.Argument
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import spock.lang.Specification

import jakarta.inject.Inject

@MicronautTest
class GraphQLControllerSpec extends Specification {

    @Inject
    @Client("/")
    HttpClient client

    void 'test graphQL controller'() {
        when:
        def body = makeRequest("book-1")

        then:
        body.data.bookById.name == "Harry Potter and the Philosopher's Stone"
        body.data.bookById.pageCount == 223
        body.data.bookById.author.firstName == 'Joanne'
        body.data.bookById.author.lastName == 'Rowling'
    }

    void 'test graphQL controller empty response'() {
        when:
        def body = makeRequest("missing-id")

        then:
        body.data.containsKey("bookById")
        body.data.bookById == null
    }

    private Map<String, Object> makeRequest(String id) {
        String query = """{ "query": "{ bookById(id:\\"$id\\") { name, pageCount, author { firstName, lastName} } }" }"""
        HttpRequest<String> request = HttpRequest.POST('/graphql', query)
        HttpResponse<Map<String, Object>> rsp = client.toBlocking().exchange(request, Argument.mapOf(String, Object))

        assert rsp.status() == HttpStatus.OK
        assert rsp.body()
        rsp.body()
    }
}

To run the tests:

./mvnw test

GraphiQL

As an extra feature that will help you during development, you can enable GraphiQL. GraphiQL is the GraphQL integrated development environment, and it helps to execute GraphQL queries.

It should only be used for development, so it’s not enabled by default. Add the following configuration to enable it:

src/main/resources/application.properties
graphql.graphiql.enabled=true

Start the application again and open http://localhost:8080/graphiql in your browser. You can write your GraphQL queries with integrated auto-completion and execute them to get the results in an easier and nicer way:

graphiql 01

Next Steps

Take a look at the Micronaut GraphQL documentation.

Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

License

Note
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).