Micronaut HTTP Client

Learn how to use Micronaut low-level HTTP Client. Simplify your code with the declarative HTTP client.

Authors: Sergio del Amo, Iván López

Micronaut Version: 4.2.0

1. Getting Started

In this guide, we will create a Micronaut application written in Kotlin to consume the GitHub API with the Micronaut HTTP Client.

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. Writing the Application

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

mn create-app example.micronaut.micronautguide \
    --features=http-client,graalvm \
    --build=maven \
    --lang=kotlin \
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.
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.

If you use Micronaut Launch, select Micronaut Application as application type and add http-client, 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.

4.1. Dependency

To use the Micronaut HTTP Client based on Netty, add the following dependency:


To use the Micronaut HTTP Client based on Java HTTP Client, add the following dependency:


4.2. GitHub API

In this guide, you will consume the GitHub API from a Micronaut application.

In this guide, you will fetch Micronaut Core releases via the List releases endpoint.

This returns a list of releases, which does not include regular Git tags that have not been associated with a release.

This API resource can be consumed by both authenticated and anonymous clients. Initially, you will consume it anonymously, later we will discuss authentication.

Create a record to parse the JSON response into an object:

package example.micronaut

import io.micronaut.serde.annotation.Serdeable

data class GithubRelease(val name: String, val url: String)

4.3. Configuration

Modify src/main/resources/application.properties to create some configuration parameters.


To encapsulate type-safe configuration retrieval, we use a @ConfigurationProperties object:

package example.micronaut

import io.micronaut.context.annotation.ConfigurationProperties
import io.micronaut.context.annotation.Requires

@Requires(property = GithubConfiguration.PREFIX)
class GithubConfiguration {
    var organization: String? = null
    var repo: String? = null
    var username: String? = null
    var token: String? = null

    companion object {
        const val PREFIX = "github"

4.3.1. JSON Codec Configuration

Add configuration to treat application/vnd.github.v3+json as JSON.


4.3.2. HTTP Client Service Configuration

Add configuration to associate a service identifier to the GitHub API URL.


4.4. Low Level Client

Initially, you will create a Bean which uses the low-level Client API.

Create GithubLowLevelClient:

package example.micronaut

import io.micronaut.core.type.Argument
import io.micronaut.http.HttpHeaders.ACCEPT
import io.micronaut.http.HttpHeaders.USER_AGENT
import io.micronaut.http.HttpRequest
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.http.uri.UriBuilder
import jakarta.inject.Singleton
import org.reactivestreams.Publisher
import java.net.URI

@Singleton (1)
class GithubLowLevelClient(@param:Client(id = "github") private val httpClient: HttpClient,  (2)
                           configuration: GithubConfiguration) {  (3)
    private val uri: URI = UriBuilder.of("/repos")

    fun fetchReleases(): Publisher<List<GithubRelease>> {
        val req: HttpRequest<*> = HttpRequest.GET<Any>(uri) (4)
            .header(USER_AGENT, "Micronaut HTTP Client") (5)
            .header(ACCEPT, "application/vnd.github.v3+json, application/json") (6)
        return httpClient.retrieve(req, Argument.listOf(GithubRelease::class.java)) (7)
1 Use jakarta.inject.Singleton to designate a class as a singleton.
2 Inject HttpClient via constructor injection. The @Client id member uses github; the service identifier set in the configuration.
3 Inject the previously defined configuration parameters.
4 Creating HTTP Requests is easy thanks to the Micronaut framework fluid API.
5 GitHub API requires to set the User-Agent header.
6 GitHub encourages to explicitly request the version 3 via the Accept header. With @Header, you add the Accept: application/vnd.github.v3+json HTTP header to every request.
7 Use retrieve to perform an HTTP request for the given request object and convert the full HTTP response’s body into the specified type. e.g. List<GithubRelease>.

4.5. Declarative Client

It is time to take a look at support for declarative clients via the Client annotation.

Create GithubApiClient which clearly illustrates how a declarative Micronaut HTTP Client, which is generated at compile-time, simplifies our code.

package example.micronaut

import io.micronaut.core.async.annotation.SingleResult
import io.micronaut.http.HttpHeaders.ACCEPT
import io.micronaut.http.HttpHeaders.USER_AGENT
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Header
import io.micronaut.http.annotation.Headers
import io.micronaut.http.client.annotation.Client
import org.reactivestreams.Publisher;

@Client(id = "github") (1)
    Header(name = USER_AGENT, value = "Micronaut HTTP Client"), (2)
    Header(name = ACCEPT, value = "application/vnd.github.v3+json, application/json") (3)
interface GithubApiClient {

    @Get("/repos/\${github.organization}/\${github.repo}/releases") (4)
    @SingleResult (5)
    fun fetchReleases(): Publisher<List<GithubRelease>> (6)
1 URL of the remote service
2 GitHub API requires to set the User-Agent header.
3 GitHub encourages to explicitly request the version 3 via the Accept header. With @Header, you add the Accept: application/vnd.github.v3+json HTTP header to every request.
4 You can use configuration parameter interpolation when you define the path of the GET endpoint.
5 Annotation to describe that an API emits a single result even if the return type is an org.reactivestreams.Publisher.
6 You can return any reactive type of any implementation (RxJava, Reactor…​), but it’s better to use the Reactive Streams public interfaces like Publisher.

4.6. Controller

Create a Controller. It uses both (low-level and declarative clients). The Micronaut framework supports Reactive Streams implementations such as RxJava or Project Reactor. Thus, you can efficiently compose multiple HTTP client calls without blocking (which will limit the throughput and scalability of your application).

package example.micronaut

import io.micronaut.core.async.annotation.SingleResult
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import org.reactivestreams.Publisher

@Controller("/github") (1)
class GithubController(private val githubLowLevelClient: GithubLowLevelClient, (2)
                       private val githubApiClient: GithubApiClient) {

    @Get("/releases-lowlevel") (3)
    @SingleResult (4)
    fun releasesWithLowLevelClient(): Publisher<List<GithubRelease>> {
        return githubLowLevelClient.fetchReleases()

    @Get("/releases") (5)
    @SingleResult (4)
    fun fetchReleases(): Publisher<List<GithubRelease>> {
        return githubApiClient.fetchReleases()
1 The class is defined as a controller with the @Controller annotation mapped to the path /github.
2 Inject beans via constructor injection.
3 The @Get annotation maps the index method to all requests that use an HTTP GET
4 Annotation to describe that an API emits a single result even if the return type is an org.reactivestreams.Publisher.
5 The @Get annotation maps the fetchReleases method to an HTTP GET request on /releases.

4.7. Tests

Create a test to verify that both clients work as expected, and the controller echoes the output of the GitHub API in a Reactive way.

package example.micronaut

import io.micronaut.context.ApplicationContext
import io.micronaut.context.annotation.Requires
import io.micronaut.core.io.ResourceLoader
import io.micronaut.core.type.Argument
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpStatus
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces
import io.micronaut.http.client.BlockingHttpClient
import io.micronaut.http.client.HttpClient
import io.micronaut.runtime.server.EmbeddedServer
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Test
import java.util.regex.Pattern

class GithubControllerTest {
            Pattern.compile("Micronaut (Core |Framework )?v?\\d+.\\d+.\\d+( (RC|M)\\d)?")

    fun verifyGithubReleasesCanBeFetchedWithLowLevelHttpClient() {
        val config = mapOf("micronaut.codec.json.additional-types" to listOf("application/vnd.github.v3+json"),
            "spec.name" to "GithubControllerTest")  (1)
        val github : EmbeddedServer = ApplicationContext.run(EmbeddedServer::class.java, config)
        val embeddedServer : EmbeddedServer  = ApplicationContext.run(EmbeddedServer::class.java,
            mapOf("micronaut.http.services.github.url" to "http://localhost:${github.port}")
        ) (2)
        val httpClient : HttpClient = embeddedServer.applicationContext
            .createBean(HttpClient::class.java, embeddedServer.url)
        val client = httpClient.toBlocking()
        assertReleases(client, "/github/releases")
        assertReleases(client, "/github/releases-lowlevel")

    fun assertReleases(client: BlockingHttpClient, path: String) {
        val request : HttpRequest<Any> = HttpRequest.GET(path)
        val rsp = client.exchange(request, (4)
            Argument.listOf(GithubRelease::class.java)) (5)
        assertEquals(HttpStatus.OK, rsp.status)   (6)
        val releases = rsp.body()
        assertReleases(releases.toList()) (7)

    fun assertReleases(releases: List<GithubRelease>) {
            .map { it.name }
            .all { MICRONAUT_RELEASE.matcher(it).find() })

    @Requires(property = "spec.name", value = "GithubControllerTest") (1)
    class GithubReleases(val resourceLoader : ResourceLoader) {
        fun coreReleases() : String {
            return resourceLoader.getResource("releases.json").orElseThrow().readText() (3)

1 Combine @Requires and properties (either via the @Property annotation or by passing properties when starting the context) to avoid bean pollution.
2 This test mocks an HTTP Server for GitHub with an extra Micronaut Embedded Server. This allows you to test how your application behaves with a specific JSON response or avoid issues such as rate limits which can make your tests flaky.
3 Create a sample releases.json file in src/test/resources directory. To get some test data call github api with curl or provide a few entries yourself.
4 Sometimes, receiving just the object is not enough, and you need information about the response. In this case, instead of retrieve you should use the exchange method.
5 Micronaut HTTP Client simplifies binding a JSON array to a list of POJOs by using Argument::listOf.
6 Use status to check the HTTP status code.
7 Use .body() to retrieve the parsed payload.

5. Testing the Application

To run the tests:

./mvnw test

6. HTTP Client Filter

Often, you need to include the same HTTP headers or URL parameters in a set of requests against a third-party API or when calling another Microservice. To simplify this, the Micronaut framework includes the ability to define HttpClientFilter classes that are applied to all matching HTTP clients.

For a real world example, let us provide GitHub Authentication via an HttpClientFilter. Follow the steps in to create your own Personal Token. Then you can use those credentials to access the GitHub API using Basic Auth.

Create a Filter:

package example.micronaut

import io.micronaut.context.annotation.Requires
import io.micronaut.http.MutableHttpRequest
import io.micronaut.http.annotation.ClientFilter
import io.micronaut.http.annotation.RequestFilter

@ClientFilter("/repos/**") (1)
@Requires(condition = GithubFilterCondition::class) (2)
class GithubFilter(val configuration: GithubConfiguration) { (3)

    @RequestFilter (4)
    fun doFilter(request: MutableHttpRequest<*>) {
        request.basicAuth(configuration.username, configuration.token) (5)
1 Annotate the class with @ClientFilter and define the ANT Matcher pattern to intercept all the calls to the desire URI.
2 Kotlin doesn’t support runtime repeatable annotations (see KT-12794. We use a custom condition to enable the bean where appropriate.
3 Constructor injection of the configuration parameters.
4 A request filter is called before the request is sent out.
5 Enhance every request sent to GitHub API providing Basic Authentication.

Create a custom Condition:

package example.micronaut

import io.micronaut.context.condition.Condition
import io.micronaut.context.condition.ConditionContext
import io.micronaut.context.exceptions.NoSuchBeanException

class GithubFilterCondition : Condition { (1)

    override fun matches(context: ConditionContext<*>?): Boolean {
        if (context != null && context.beanContext != null) {
            try {
                val githubConfiguration: GithubConfiguration =
                    context.beanContext.getBean(GithubConfiguration::class.java) (2)
                if (githubConfiguration.token != null && githubConfiguration.username != null) {
                    return true (3)
            } catch (e: NoSuchBeanException) {
        return false

1 Implement Micronaut Condition.
2 Get the GithubConfiguration bean from the application context.
3 Only return true when the token and the username exist.

6.1. Configuration Parameters

Add your GitHub username and token to src/main/resource/application.properties

  organization: micronaut-projects
  repo: micronaut-core
  username: yourgithubusername
  token: xxxxxxxxxxxx

Add a logger to src/main/resources/logback.xml to see the HTTP client output.

<logger name="io.micronaut.http.client" level="TRACE"/>

If you run again the tests, you will see the that the Filter is invoked and HTTP Basic Auth is used against GitHub API.

13:09:56.662 [default-nioEventLoopGroup-1-4] DEBUG i.m.h.client.netty.DefaultHttpClient - Sending HTTP GET to https://api.github.com/repos/micronaut-projects/micronaut-core/releases
13:09:56.663 [default-nioEventLoopGroup-1-4] TRACE i.m.h.client.netty.DefaultHttpClient - User-Agent: Micronaut HTTP Client
13:09:56.663 [default-nioEventLoopGroup-1-4] TRACE i.m.h.client.netty.DefaultHttpClient - Accept: application/json
13:09:56.663 [default-nioEventLoopGroup-1-4] TRACE i.m.h.client.netty.DefaultHttpClient - Authorization: MASKED
13:09:56.664 [default-nioEventLoopGroup-1-4] TRACE i.m.h.client.netty.DefaultHttpClient - host: api.github.com

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

7.1. GraalVM installation

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

Java 17
sdk install java 17.0.8-graal
Java 17
sdk use java 17.0.8-graal

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

The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.

Alternatively, you can use the GraalVM Community Edition:

Java 17
sdk install java 17.0.8-graalce
Java 17
sdk use java 17.0.8-graalce

7.2. Native executable generation

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.

8. Next steps

9. Help with the Micronaut Framework

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