Content negotiation in a Pyronaut application

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

1. Getting Started

In this guide, we will create a Python application built with Pyronaut.

2. What you will need

To complete this guide, you will need the following:

  • Some time on your hands

  • GraalPy installed and the Pyronaut CLI available locally

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 Pyronaut CLI (Command Line Interface) or Pyronaut Launch

pyronaut create example.micronaut.micronautguide --features=views-thymeleaf

5. Views

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

6. Controller

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

src/example/micronaut/message_controller.py
import java

from micronaut.http import HttpRequest, HttpResponse, MediaType
from micronaut.http.annotation import Controller, Get, Produces

ModelAndView = java.type("io.micronaut.views.ModelAndView")


@Controller  (1)
class MessageController:

    @Produces([MediaType.TEXT_HTML, MediaType.APPLICATION_JSON])  (2)
    @Get  (3)
    def index(self, request: HttpRequest) -> HttpResponse:  (4)
        model = {"message": "Hello World"}
        body = (
            ModelAndView("message.html", model)
            if accepts(request, MediaType.TEXT_HTML)
            else model
        )
        return HttpResponse.ok(body)


def accepts(request: HttpRequest, media_type: str) -> bool:
    return any(
        media_type in accepted.getName()
        for accepted in request.getHeaders().accept()
    )
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:

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

tests/example/micronaut/test_message_controller.py
import pytest
import requests

from pyronaut.test import MicronautTest, micronaut_test_fixture


@pytest.fixture
def my_context(request):
    fixture = micronaut_test_fixture(
        request,
        MicronautTest(environments=["test"], transactional=False),
    )  (1)
    yield fixture
    fixture.stop()


@pytest.fixture
def client(my_context):
    return requests.with_context(my_context)  (2)


def test_content_negotiation(client):
    response = client.get("/", headers={"Accept": "application/json"})  (3)

    assert response.status_code == 200
    assert response.headers["content-type"].startswith("application/json")
    assert response.json() == {"message": "Hello World"}

    response = client.get("/", headers={"Accept": "text/html"})

    assert response.status_code == 200
    assert response.headers["content-type"].startswith("text/html")
    assert response.text == """<!DOCTYPE html>
<html lang="en">
<body>
<h1>Hello World</h1>
</body>
</html>
"""
1 Create a Micronaut test fixture for the application under test.
2 Use requests.with_context(my_context) to call the application under test with a context-bound HTTP client.
3 Send requests with explicit Accept headers.

8. Testing the Application

To run the tests:

pyronaut install
pyronaut validate-config
pyronaut test

9. Next Steps

Explore more features with Micronaut Guides.

Read more about Micronaut Views.

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