Content negotiation in a Micronaut application

Learn how to respond with HTML or JSON depending on the request Accept HTTP header.

Authors: Sergio del Amo

Micronaut Version: 5.0.0

1. Getting Started

In this guide, we will create a Micronaut application written in Kotlin.

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=views-thymeleaf \
    --build=gradle \
    --lang=kotlin \
    --test=junit
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.

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

To use the Thymeleaf Java template engine to render views in a Micronaut application, add the following dependency on your classpath.

build.gradle
implementation("io.micronaut.views:micronaut-views-thymeleaf")

6. Controller

Create a controller that responds with HTML or JSON depending on the request Accept HTTP header.

src/main/kotlin/example/micronaut/MessageController.kt
package example.micronaut

import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces
import io.micronaut.views.ModelAndView

@Controller (1)
class MessageController {

    @Produces(value = [MediaType.TEXT_HTML, MediaType.APPLICATION_JSON]) (2)
    @Get (3)
    fun index(request: HttpRequest<*>): HttpResponse<*> { (4)
        val model = mapOf("message" to "Hello World")
        val body = if (accepts(request, MediaType.TEXT_HTML_TYPE)) {
            ModelAndView("message.html", model)
        } else {
            model
        }
        return HttpResponse.ok(body)
    }

    private fun accepts(request: HttpRequest<*>, mediaType: MediaType): Boolean =
        request.headers
            .accept()
            .any { it.name.contains(mediaType.name) }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /.
2 Use the @Produces annotation to indicate the possible response content types. It matches the Accept header of the request, as you will see in the test.
3 The @Get annotation maps the method to an HTTP GET request.
4 You can bind the HTTP Request as a method parameter in a controller’s method.

For HTML, the previous controller uses a Thymeleaf view:

src/main/resources/views/message.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1 th:text="${message}"></h1>
</body>
</html>

7. Test

Write a test that verifies the response content type depending on the request Accept HTTP header.

src/test/kotlin/example/micronaut/MessageControllerTest.kt
package example.micronaut

import io.micronaut.http.HttpRequest
import io.micronaut.http.MediaType
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertDoesNotThrow
import org.junit.jupiter.api.Test

@MicronautTest (1)
class MessageControllerTest(@Client("/") val httpClient: HttpClient) { (2)

    @Test
    fun contentNegotiation() {
        val client = httpClient.toBlocking()

        val expectedJson = """{"message":"Hello World"}"""
        val json = assertDoesNotThrow<String> {
            client.retrieve(HttpRequest.GET<Any>("/")
                .accept(MediaType.APPLICATION_JSON)) (3)
        }
        assertEquals(expectedJson, json)

        val expectedHtml = """
            <!DOCTYPE html>
            <html lang="en">
            <body>
            <h1>Hello World</h1>
            </body>
            </html>
        """.trimIndent() + "\n"
        val html = assertDoesNotThrow<String> {
            client.retrieve(HttpRequest.GET<Any>("/")
                .accept(MediaType.TEXT_HTML))
        }
        assertEquals(expectedHtml, html)
    }
}
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.
3 Creating HTTP Requests is easy thanks to the Micronaut framework fluid API.

8. Testing the Application

To run the tests:

./gradlew test

Then open build/reports/tests/test/index.html in a browser to see the results.

9. Native Tests

The io.micronaut.application Micronaut Gradle Plugin automatically integrates with GraalVM by applying the Gradle plugin for GraalVM Native Image building.

This plugin supports running tests on the JUnit Platform as native images. This means that tests will be compiled and executed as native code.

To execute the tests, execute:

./gradlew nativeTest

Then open build/reports/tests/test/index.html in a browser to see the results.

INFO: A test may be disabled within a GraalVM native image via the @DisabledInNativeImage annotation.

10. Next Steps

Explore more features with Micronaut Guides.

Read more about Micronaut Views.

11. Help with the Micronaut Framework

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

12. License

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