Use OpenAPI Definition to Generate a Micronaut Client

Learn how to generate a Declarative Micronaut Client API from an OpenAPI definition and how to use it in your application

Authors: Andriy Dmytruk, Cédric Champeau

Micronaut Version: 4.4.0

1. Getting Started

OpenAPI is a specification for describing REST APIs. Many web APIs provide definitions for the available endpoints and parameters in form of OpenAPI documents. OpenAPI infrastructure includes numerous tooling, including the OpenAPI generator.

This guide will use the Micronaut OpenAPI Generator to generate a client API from an OpenAPI definition file. We will generate the client for Open Meteo, however the steps could easily be replicated with any other API with an OpenAPI definition.

After generation, we will see how to use the client inside a Micronaut application, including performing API calls in controller methods.

2. What you will need

To complete this guide, you will need the following:

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. Generating the Micronaut Client

We will generate a client for Open Meteo, an open-source weather API offering free non-commercial access.

To do this, we must download the official Open Meteo OpenAPI definition file.

4.1. Create a Micronaut application

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

mn create-app example.micronaut.micronautguide \
   --features=http-client,validation,reactor \
   --build=gradle --lang=java

Open the generated project and create a new folder, src/openapi, then copy the openapi.yml file into it, for example:

$ cd micronaut-guide
$ mkdir src/openapi
$ curl https://raw.githubusercontent.com/open-meteo/open-meteo/main/openapi.yml -o src/openapi/openmeteo.yml

4.2. Configure client generation

Add the Micronaut OpenAPI plugin to your plugins section:

build.gradle
plugins {
  id 'io.micronaut.openapi' version '...'
  ....
}

And configure your build to generate a client:

build.gradle
micronaut {
  ...
  openapi {
    client(file("src/openapi/openmeteo.yml")) {
      apiPackageName = "example.openmeteo.api"
      modelPackageName = "example.openmeteo.model"
    }
  }
}

Micronaut OpenAPI generator generates the client code in your build directory and adds it as a source set. Therefore, you can, for example run ./gradlew compileJava --console=verbose and see that the sources are generated and compiled:

> Task :generateClientOpenApiApis
...
> Task :generateClientOpenApiModels
...
> Task :compileJava
The Micronaut OpenAPI generator supports a large number of parameters. Please refer to the Micronaut OpenAPI Gradle plugin documentation for all possible options.

After generation finishes, you should see the following directory structure under your build/generated/openapi directory:

build/generated/openapi
├── generateClientOpenApiApis
│   └── src
│       └── main
│           └── java
│               └── example
│                   └── openmeteo
│                       └── api
│                           └── WeatherForecastApisApi.java  (1)
└── generateClientOpenApiModels
    └── src
        └── main
            └── java
                └── example
                    └── openmeteo
                        └── model                                 (2)
                            ├── CurrentWeather.java
                            ├── DailyResponse.java
                            ├── HourlyProperties.java
                            ├── HourlyResponse.java
                            ├── V1ForecastGet200Response.java
                            └── V1ForecastGet400Response.java
1 The example.openmeteo.api package contains API classes.
2 The example.openmeteo.model package contains data classes that are used in parameters or bodies of both requests and responses in the API.

The definition file is a document describing the OpenMeteo API according to the OpenAPI Specification.

If you want to learn about the structure of OpenAPI specification and how to simplify the creation of a Micronaut Server with it, read the "Use OpenAPI Definition to Generate a Micronaut Server" guide or the OpenAPI guide.

As you can see, different API files were generated for the OpenMeteo API.

The API files show that method definitions were generated corresponding to different paths and operations available in the API.

Using Micronaut Framework’s features, we can inject a client implementation of this interface and use it by calling the corresponding methods without worrying about how client-server communication is handled.

5. Configuration

Set openapi-micronaut-client-base-path to https://api.open-meteo.com in configuration.

src/main/resources/application.properties
openapi-micronaut-client.base-path=https://api.open-meteo.com

6. Testing the Client

Micronaut OpenAPI generator generated a weather forecast API class in the project. This API references other types that belong to the model types. Micronaut OpenAPI generator generated classes for those types from the OpenAPI definition.

We will show how to use the OpenMeteo API by writing a simple test using the generated Micronaut client.

src/test/java/example/micronaut/WeatherClientTest.java
@MicronautTest
class WeatherClientTest {
    @Test
    @DisplayName("Fetches weather for Montaigu-Vendée")
    void fetchesWeather(WeatherForecastApisApi api) {               (1)
        var forecast = api.v1ForecastGet(46.97386f, -1.3111076f,    (2)
                null,
                null,
                true,
                null,
                null,
                null,
                null,
                null);
        var weather = forecast.block().getCurrentWeather();        (3)
        assertTrue(weather.getTemperature() < 50);
    }
}
1 Inject the generated client in the test
2 Calls the client to fetch a weather forecast
3 Blocks and consumes the response

7. Next Steps

7.1. Learn How to Write OpenAPI Definition and Generate Server Based on It

  • understand OpenAPI definition files and write your definition files.

  • generate server API based on the definitions.

  • implement the functionality of the server based on the API and write comprehensive tests utilizing Micronaut Framework’s features.

7.2. Learn Micronaut

To learn more about Micronaut Framework and its features, visit Micronaut documentation or read one of the several Micronaut guides.

7.3. Micronaut OpenAPI

  • Use Micronaut OpenAPI module to generate OpenAPI definition documents from controllers with Micronaut annotations.

8. License

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