These tutorials target Micronaut Framework 3. Read, Guides for Micronaut Framework 4.

Creating a ToDo application with Micronaut GraphQL

Build a TODO application with Micronaut GraphQL.

Authors: Sergio del Amo, Tim Yates

Micronaut Version: 3.9.2

1. Getting Started

In this guide, you will create a Micronaut application written in Java that uses GraphQL to create a todo application.

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.

You will be using:

  • A PostgreSQL instance provided by Test Resources and running in Docker.

  • Micronaut Data to persist our ToDos to this database.

  • Flyway to handle our database migrations.

  • Micronaut GraphQL to expose our data.

  • Testcontainers to run a PostgreSQL instance for local dev, and tests.

The application will expose a GraphQL endpoint at /graphql for the data to be consumed and modified.

2. What you will need

To complete this guide, you will need the following:

  • Some time on your hands

  • A decent text editor or IDE

  • JDK 1.8 or greater installed with JAVA_HOME configured appropriately

3. 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.

4. Writing the Application

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

mn create-app example.micronaut.micronautguide \
    --features=graphql,data-jdbc,flyway,postgres,graalvm \
    --build=maven
    --lang=java
If you don’t specify the --build argument, Gradle is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.

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

If you use Micronaut Launch, select Micronaut Application as application type and add graphql, data-jdbc, flyway, postgres, and graalvm features.

If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features and apply those changes to your application.

5. Persistence layer

5.1. Database Migration with Flyway

We need a way to create the database schema. For that, we use Micronaut integration with Flyway.

Flyway automates schema changes, significantly simplifying schema management tasks, such as migrating, rolling back, and reproducing in multiple environments.

Add the following snippet to include the necessary dependencies:

pom.xml
<dependency>
    <groupId>io.micronaut.flyway</groupId>
    <artifactId>micronaut-flyway</artifactId>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-mysql</artifactId>
    <scope>runtime</scope>
</dependency>

We will enable Flyway in application.yml and configure it to perform migrations on one of the defined data sources.

src/main/resources/application.yml
flyway:
  datasources:
    default:
      enabled: true (1)
1 Enable Flyway for the default datasource.
Configuring multiple data sources is as simple as enabling Flyway for each one. You can also specify directories that will be used for migrating each data source. Review the Micronaut Flyway documentation for additional details.

Flyway migration will be automatically triggered before your Micronaut application starts. Flyway will read migration commands in the resources/db/migration/ directory, execute them if necessary, and verify that the configured data source is consistent with them.

Create the following migration files with the database schema creation:

src/main/resources/db/migration/V1__schema.sql
CREATE TABLE author (1)
(
    id       BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    username VARCHAR(255) NOT NULL
);

CREATE TABLE to_do (2)
(
    id        BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    title     VARCHAR(255) NOT NULL,
    completed BOOLEAN      NOT NULL,
    author_id BIGINT REFERENCES author (id)
);
1 Authors will be stored in table separate to the ToDos. They just have a username.
2 ToDos have a title, completion status, and a foreign-key reference to the author.

5.2. Entities

Create an Entity class to represent an Author:

src/main/java/example/micronaut/Author.java
package example.micronaut;

import io.micronaut.data.annotation.GeneratedValue;
import io.micronaut.data.annotation.Id;
import io.micronaut.data.annotation.MappedEntity;

import javax.validation.constraints.NotNull;

import static io.micronaut.data.annotation.GeneratedValue.Type.AUTO;

@MappedEntity (1)
public class Author {

    @Id (2)
    @GeneratedValue(AUTO)
    private Long id;

    @NotNull
    private final String username;

    public Author(@NotNull String username) {
        this.username = username;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }
}
1 Annotate the class with @MappedEntity to map the class to the table defined in the schema.
2 Specifies the ID of an entity

And another to represent a ToDo:

src/main/java/example/micronaut/ToDo.java
package example.micronaut;

import io.micronaut.data.annotation.GeneratedValue;
import io.micronaut.data.annotation.Id;
import io.micronaut.data.annotation.MappedEntity;

import javax.validation.constraints.NotNull;

import static io.micronaut.data.annotation.GeneratedValue.Type.AUTO;

@MappedEntity (1)
public class ToDo {

    @Id (2)
    @GeneratedValue(AUTO)
    private Long id;

    @NotNull
    private String title;

    private boolean completed;

    private final long authorId;

    public ToDo(String title, long authorId) {
        this.title = title;
        this.authorId = authorId;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public boolean isCompleted() {
        return completed;
    }

    public void setCompleted(boolean completed) {
        this.completed = completed;
    }

    public long getAuthorId() {
        return authorId;
    }
}
1 Annotate the class with @MappedEntity to map the class to the table defined in the schema.
2 Specifies the ID of an entity

5.3. Repositories

Create a JdbcRepository for each of our Entity classes.

The simplest of these is the ToDoRepository which just requires the default methods:

src/main/java/example/micronaut/ToDoRepository.java
package example.micronaut;

import io.micronaut.data.jdbc.annotation.JdbcRepository;
import io.micronaut.data.model.query.builder.sql.Dialect;
import io.micronaut.data.repository.PageableRepository;

import static io.micronaut.data.model.query.builder.sql.Dialect.POSTGRES;

@JdbcRepository(dialect = POSTGRES) (1)
public interface ToDoRepository extends PageableRepository<ToDo, Long> { (2)
}
1 @JdbcRepository with a specific dialect.
2 By extending CrudRepository you enable automatic generation of CRUD (Create, Read, Update, Delete) operations.

Then create a Repository for the Authors. This requires extra finders for this to simplify the GraphQL wiring in the next step:

src/main/java/example/micronaut/AuthorRepository.java
package example.micronaut;

import io.micronaut.data.jdbc.annotation.JdbcRepository;
import io.micronaut.data.repository.CrudRepository;

import java.util.Collection;
import java.util.Optional;

import static io.micronaut.data.model.query.builder.sql.Dialect.POSTGRES;

@JdbcRepository(dialect = POSTGRES) (1)
public interface AuthorRepository extends CrudRepository<Author, Long> { (2)

    Optional<Author> findByUsername(String username); (3)

    Collection<Author> findByIdIn(Collection<Long> ids); (4)

    default Author findOrCreate(String username) { (5)
        return findByUsername(username).orElseGet(() -> save(new Author(username)));
    }
}
1 @JdbcRepository with a specific dialect.
2 By extending CrudRepository you enable automatic generation of CRUD (Create, Read, Update, Delete) operations.
3 When creating todos a method is required to search for an exisiting username.
4 When GraphQL loads a ToDo, it use this to fetch the authors if they are required in the response.
5 Find an existing author, or else create a new one when creating a ToDo.

6. GraphQL

The initial Micronaut application create-app step already added the GraphQL dependency:

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

So the default GraphQL endpoint /graphql is enabled, and extra configuration is not required.

6.1. Describe your schema

Create the file schema.graphqls:

src/main/resources/schema.graphqls
type Query {
    toDos: [ToDo!]! (1)
}

type Mutation {
    createToDo(title: String!, author: String!): ToDo  (2)
    completeToDo(id: ID!): Boolean!  (3)
}

type ToDo { (4)
    id: ID!
    title: String!
    completed: Boolean!
    author: Author!
}

type Author { (5)
    id: ID!
    username: String!
}
1 Declare a toDos query function to fetch all the todos as a list.
2 Declare a createToDo mutation function to create and return a new ToDo.
3 Declare a completeToDo mutation function to mark a ToDo as done (and return a boolean indicating success).
4 Declare a ToDo type.
5 Declare an Author type.

6.2. Data Fetchers

For each query and mutator in the schema, create a DataFetcher which will bind the GraphQL schema to our domain model. These will execute the appropriate queries in the datastore.

6.2.1. Queries

Create class ToDosDataFetcher to implement the toDos query:

src/main/java/example/micronaut/ToDosDataFetcher.java
package example.micronaut;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import jakarta.inject.Singleton;

@Singleton (1)
public class ToDosDataFetcher implements DataFetcher<Iterable<ToDo>> {

    private final ToDoRepository toDoRepository;

    public ToDosDataFetcher(ToDoRepository toDoRepository) { (2)
        this.toDoRepository = toDoRepository;
    }

    @Override
    public Iterable<ToDo> get(DataFetchingEnvironment env) {
        return toDoRepository.findAll();
    }
}
1 Use jakarta.inject.Singleton to designate a class as a singleton.
2 Use constructor injection to inject a bean of type ToDoRepository.

6.2.2. Mutations

Create CreateToDoDataFetcher for the creation of ToDos:

src/main/java/example/micronaut/CreateToDoDataFetcher.java
package example.micronaut;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import jakarta.inject.Singleton;
import javax.transaction.Transactional;

@Singleton (1)
public class CreateToDoDataFetcher implements DataFetcher<ToDo> {

    private final ToDoRepository toDoRepository;
    private final AuthorRepository authorRepository;

    public CreateToDoDataFetcher(ToDoRepository toDoRepository, (2)
                                 AuthorRepository authorRepository) {
        this.toDoRepository = toDoRepository;
        this.authorRepository = authorRepository;
    }

    @Override
    @Transactional
    public ToDo get(DataFetchingEnvironment env) {
        String title = env.getArgument("title");
        String username = env.getArgument("author");

        Author author = authorRepository.findOrCreate(username); (3)

        ToDo toDo = new ToDo(title, author.getId());

        return toDoRepository.save(toDo); (4)
    }
}
1 Use jakarta.inject.Singleton to designate a class as a singleton.
2 Use constructor injection to inject a bean of type ToDoRepository.
3 Find the existing author or create a new one.
4 Persist the new ToDo.

And CompleteToDoDataFetcher to mark ToDos as complete:

src/main/java/example/micronaut/CompleteToDoDataFetcher.java
package example.micronaut;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import jakarta.inject.Singleton;

@Singleton (1)
public class CompleteToDoDataFetcher implements DataFetcher<Boolean> {

    private final ToDoRepository toDoRepository;

    public CompleteToDoDataFetcher(ToDoRepository toDoRepository) { (2)
        this.toDoRepository = toDoRepository;
    }

    @Override
    public Boolean get(DataFetchingEnvironment env) {
        long id = Long.parseLong(env.getArgument("id"));
        return toDoRepository
                .findById(id) (3)
                .map(this::setCompletedAndUpdate)
                .orElse(false);
    }

    private boolean setCompletedAndUpdate(ToDo todo) {
        todo.setCompleted(true); (4)
        toDoRepository.update(todo); (5)
        return true;
    }
}
1 Use jakarta.inject.Singleton to designate a class as a singleton.
2 Use constructor injection to inject a bean of type ToDoRepository.
3 Find the existing ToDo based on its id.
4 If found, set completed.
5 And update the version in the database.

6.2.3. Wiring

GraphQL allows data to be fetched on demand. In this example, a user may request a list of ToDos, but not require the author to be populated. A method is required to optionally load Authors based on their ID.

To do this, register a DataLoader that finds authors based on a collection of ids:

src/main/java/example/micronaut/AuthorDataLoader.java
package example.micronaut;

import io.micronaut.scheduling.TaskExecutors;
import jakarta.inject.Named;
import jakarta.inject.Singleton;
import org.dataloader.MappedBatchLoader;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;

import static java.util.stream.Collectors.toMap;

@Singleton (1)
public class AuthorDataLoader implements MappedBatchLoader<Long, Author> {

    private final AuthorRepository authorRepository;
    private final ExecutorService executor;

    public AuthorDataLoader(
            AuthorRepository authorRepository,
            @Named(TaskExecutors.IO) ExecutorService executor (2)
    ) {
        this.authorRepository = authorRepository;
        this.executor = executor;
    }

    @Override
    public CompletionStage<Map<Long, Author>> load(Set<Long> keys) {
        return CompletableFuture.supplyAsync(() -> authorRepository
                        .findByIdIn(keys)
                        .stream()
                        .collect(toMap(Author::getId, Function.identity())),
                executor
        );
    }

}
1 Use jakarta.inject.Singleton to designate a class as a singleton.
2 Inject the IO executor service.

This is registered in the DataLoaderRegistry under the key author

src/main/java/example/micronaut/DataLoaderRegistryFactory.java
package example.micronaut;

import io.micronaut.context.annotation.Factory;
import io.micronaut.runtime.http.scope.RequestScope;
import org.dataloader.DataLoader;
import org.dataloader.DataLoaderRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Factory (1)
public class DataLoaderRegistryFactory {

    private static final Logger LOG = LoggerFactory.getLogger(DataLoaderRegistryFactory.class);

    @SuppressWarnings("unused")
    @RequestScope (2)
    public DataLoaderRegistry dataLoaderRegistry(AuthorDataLoader authorDataLoader) {
        DataLoaderRegistry dataLoaderRegistry = new DataLoaderRegistry();
        dataLoaderRegistry.register(
                "author",
                DataLoader.newMappedDataLoader(authorDataLoader)
        ); (3)

        LOG.trace("Created new data loader registry");

        return dataLoaderRegistry;
    }

}
1 A class annotated with the @Factory annotated is a factory. It provides one or more methods annotated with a bean scope annotation (e.g. @Singleton). Read more about Bean factories.
2 This registry has request scope, so a new one will be created for every request.
3 Register the AuthorDataLoader whenever the loader for "author" is requested.

Add an AuthorDataFetcher which requests and uses this loader to populate a ToDo if the author when required.

src/main/java/example/micronaut/AuthorDataFetcher.java
package example.micronaut;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import jakarta.inject.Singleton;
import org.dataloader.DataLoader;

import java.util.concurrent.CompletionStage;

@Singleton (1)
public class AuthorDataFetcher implements DataFetcher<CompletionStage<Author>> {

    @Override
    public CompletionStage<Author> get(DataFetchingEnvironment environment) {
        ToDo toDo = environment.getSource();
        DataLoader<Long, Author> authorDataLoader = environment.getDataLoader("author"); (2)
        return authorDataLoader.load(toDo.getAuthorId());
    }
}
1 Use jakarta.inject.Singleton to designate a class as a singleton.
2 Uses the author data loader defined above in the Factory.

6.3. GraphQL Factory

Finally, create a factory class that will bind the GraphQL schema to the code, types and fetchers.

src/main/java/example/micronaut/GraphQLFactory.java
package example.micronaut;

import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import graphql.schema.idl.errors.SchemaMissingError;
import io.micronaut.context.annotation.Bean;
import io.micronaut.context.annotation.Factory;
import io.micronaut.core.io.ResourceResolver;
import jakarta.inject.Singleton;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

@Factory (1)
public class GraphQLFactory {

    @Singleton (2)
    public GraphQL graphQL(ResourceResolver resourceResolver,
                           ToDosDataFetcher toDosDataFetcher,
                           CreateToDoDataFetcher createToDoDataFetcher,
                           CompleteToDoDataFetcher completeToDoDataFetcher,
                           AuthorDataFetcher authorDataFetcher) {
        SchemaParser schemaParser = new SchemaParser();
        SchemaGenerator schemaGenerator = new SchemaGenerator();

        // Load the schema
        InputStream schemaDefinition = resourceResolver
                .getResourceAsStream("classpath:schema.graphqls")
                .orElseThrow(SchemaMissingError::new);

        // Parse the schema and merge it into a type registry
        TypeDefinitionRegistry typeRegistry = new TypeDefinitionRegistry();
        typeRegistry.merge(schemaParser.parse(new BufferedReader(new InputStreamReader(schemaDefinition))));

        // Create the runtime wiring.
        RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
                .type("Query", typeWiring -> typeWiring  (3)
                        .dataFetcher("toDos", toDosDataFetcher))

                .type("Mutation", typeWiring -> typeWiring (4)
                        .dataFetcher("createToDo", createToDoDataFetcher)
                        .dataFetcher("completeToDo", completeToDoDataFetcher))

                .type("ToDo", typeWiring -> typeWiring (5)
                        .dataFetcher("author", authorDataFetcher))

                .build();

        // Create the executable schema.
        GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);

        // Return the GraphQL bean.
        return GraphQL.newGraphQL(graphQLSchema).build();
    }
}
1 A class annotated with the @Factory annotated is a factory. It provides one or more methods annotated with a bean scope annotation (e.g. @Singleton). Read more about Bean factories.
2 Use jakarta.inject.Singleton to designate a class as a singleton.
3 Wire up the query behavior.
4 Wire up each mutators.
5 Wire up how to populate a ToDo with authors if they are requested.

7. Test Resources

When the application is started locally — either under test or by running the application — resolution of the datasource URL is detected and the Test Resources service will start a local PostgreSQL docker container, and inject the properties required to use this as the datasource.

For more information, see the JDBC section of the Test Resources documentation.

8. Running the Application

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

When the application first runs, you will see in the logs that the migrations have been performed.

9. Test the application

9.1. Manual smoke tests

Formulate a GraphQL query to retrieve all the current ToDos (there will be none to start with)

Query
query {
  toDos {
    title,
    completed,
    author {
       username
    }
  }
}

Run the following cURL request:

curl -X POST 'http://localhost:8080/graphql' \
     -H 'content-type: application/json' \
     --data-binary '{"query":"{ toDos { title, completed, author { username } } }"}'
Response
{"data":{"toDos":[]}}

Create a ToDo, by issuing a mutation query and return the ID of the newly created ToDo:

GraphQL Query
mutation {
  createToDo(title: "Create GraphQL Guide", author: "Tim Yates") {
    id
  }
}

Which translates to this cURL command:

curl -X POST 'http://localhost:8080/graphql' \
     -H 'content-type: application/json' \
     --data-binary '{"query":"mutation { createToDo(title:\"Create GraphQL Guide\", author:\"Tim Yates\") { id } }"}'
Response
{"data":{"createToDo":{"id":"1"}}}

This new ToDo then appears in the list of all ToDos with completed set to false:

curl -X POST 'http://localhost:8080/graphql' \
     -H 'content-type: application/json' \
     --data-binary '{"query":"{ toDos { title, completed, author { username } } }"}'
Response
{"data":{"toDos":[{"title":"Create GraphQL Guide","completed":false,"author":{"username":"Tim Yates"}}]}}

Mark it as completed by using this query with the ID from above:

GraphQL query
mutation {
  completeToDo(id: 1)
}
curl -X POST 'http://localhost:8080/graphql' \
     -H 'content-type: application/json' \
     --data-binary '{"query":"mutation { completeToDo(id: 1) }"}'
Response
{"data":{"completeToDo":true}}

Check this has been persisted in our model:

Query
curl -X POST 'http://localhost:8080/graphql' \
     -H 'content-type: application/json' \
     --data-binary '{"query":"{ toDos { title, completed } }"}'
Response
{"data":{"toDos":[{"title":"Create GraphQL Guide","completed":true}]}}

9.2. Automated tests

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

src/test/java/example/micronaut/GraphQLControllerTest.java
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.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

@MicronautTest (1)
class GraphQLControllerTest {

    @Inject
    @Client("/")
    HttpClient client; (2)

    @Test
    void testGraphQLController() {
        // when:
        List<Map> todos = getTodos();

        // then:
        assertTrue(todos.isEmpty());

        // when:
        Long id = createToDo("Test GraphQL", "Tim Yates");

        // then: (check it's a UUID)
        assertEquals(1, id);

        // when:
        todos = getTodos();

        // then:
        assertEquals(1, todos.size());

        Map<?,?> todo = todos.get(0);

        assertEquals("Test GraphQL", todo.get("title"));
        assertFalse(Boolean.parseBoolean(todo.get("completed").toString()));
        assertEquals("Tim Yates", ((Map)todo.get("author")).get("username"));

        // when:
        Boolean completed = markAsCompleted(id);

        // then:
        assertTrue(completed);

        // when:
        todos = getTodos();

        // then:
        assertEquals(1, todos.size());
        todo = todos.get(0);
        assertEquals("Test GraphQL", todo.get("title"));
        assertTrue(Boolean.parseBoolean(todo.get("completed").toString()));
        assertEquals("Tim Yates", ((Map)todo.get("author")).get("username"));
    }

    private HttpResponse<Map> fetch(String query) {
        HttpRequest<String> request = HttpRequest.POST("/graphql", query);
        HttpResponse<Map> response = client.toBlocking().exchange(request, Argument.of(Map.class));
        assertEquals(HttpStatus.OK, response.status());
        assertNotNull(response.body());
        return response;
    }

    private List<Map> getTodos() {
        String query = "{\"query\":\"query { toDos { title, completed, author { id, username } } }\"}";
        HttpResponse<Map> response = fetch(query);
        return (List<Map>) ((Map) response.getBody().get().get("data")).get("toDos");
    }

    private long createToDo(String title, String author) {
        String query = "{\"query\": \"mutation { createToDo(title: \\\"" + title + "\\\", author: \\\"" + author + "\\\") { id } }\" }";
        HttpResponse<Map> response = fetch(query);
        return Long.parseLong(((Map)((Map) response.getBody(Map.class).get().get("data")).get("createToDo")).get("id").toString());
    }

    private Boolean markAsCompleted(Long id) {
        String query = "{\"query\": \"mutation { completeToDo(id: \\\"" + id + "\\\") }\" }";
        HttpResponse<Map> response = fetch(query);
        return (Boolean) ((Map) response.getBody(Map.class).get().get("data")).get("completeToDo");
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
2 Inject the HttpClient bean and point it to the embedded server.

To run the tests:

./mvnw test

10. GraphiQL

As an extra feature that will help during development, you can enable GraphiQL. GraphiQL is the GraphQL integrated development environment, and it executes 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.yml
graphql:
  graphiql.enabled: true

Start the application again and open http://localhost:8080/graphiql in a browser. GraphQL queries can be executed with integrated auto-completion:

graphiql todo

11. Generate a Micronaut Application Native Executable with GraalVM

We will use GraalVM, the polyglot embeddable virtual machine, to generate a native executable of our Micronaut application.

Compiling native executables ahead of time with GraalVM improves startup time and reduces the memory footprint of JVM-based applications.

Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.

11.1. Native executable generation

The easiest way to install GraalVM on Linux or Mac is to use SDKMan.io.

Java 11
sdk install java 22.3.r11-grl
If you still use Java 8, use the JDK11 version of GraalVM.
Java 17
sdk install java 22.3.r17-grl

For installation on Windows, or for manual installation on Linux or Mac, see the GraalVM Getting Started documentation.

After installing GraalVM, install the native-image component, which is not installed by default:

gu install native-image

To generate a native executable using Maven, run:

./mvnw package -Dpackaging=native-image

The native executable is created in the target directory and can be run with target/micronautguide.

Start the native executable and execute the same cURL request as before. You can also use the included GraphiQL browser to execute the queries.

12. Next steps

Take a look at the Micronaut GraphQL documentation.

13. Help with the Micronaut Framework

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