Serving static resources in a Pyronaut application

Learn how to expose static resources such as CSS or images in a Pyronaut application.

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=validation,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.

5.1. Thymeleaf template

Create a Thymeleaf template in config/views/index.html:

config/views/index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>A hearty welcome!</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="/css/style.css"> (1)
    </head>
    <body>
        <section>
            <img width="253" height="200" src="/images/micronaut_stacked_black.png" alt="Micronaut Framework logo"> (2)
            <h1 th:text="${message}"></h1> (3)
        </section>
    </body>
</html>
1 Include the CSS file from our static assets
2 Include a PNG from our static assets
3 Use the th:text attribute to set the element’s text

6. Message service

Create a singleton service that generates the message.

src/example/micronaut/message_service.py
from typing import Annotated

from jakarta.inject import Singleton
from jakarta.validation.constraints import NotBlank
from micronaut.validation import Validated


@Validated
@Singleton  (1)
class MessageService:
    def say_hello(self, name: Annotated[str, NotBlank]) -> str:
        return f"Hello {name}!"
1 Use jakarta.inject.Singleton to designate a class as a singleton.

7. Controller

Create a controller that takes a name and generates our templated HTML page.

src/example/micronaut/main_controller.py
from typing import Annotated

from jakarta.validation.constraints import NotBlank
from micronaut.http import MediaType
from micronaut.http.annotation import Controller, Get
from micronaut.views import View

from .message_service import MessageService


@Controller  (1)
class MainController:
    def __init__(self, message_service: MessageService):  (2)
        self.message_service = message_service

    @View("index.html")  (3)
    @Get(value="/hello/{name}", produces=MediaType.TEXT_HTML)  (4)
    def index(self, name: Annotated[str, NotBlank]) -> dict[str, str]:  (5)
        return {"message": self.message_service.say_hello(name)}
1 The class is defined as a controller with the @Controller annotation mapped to the path /.
2 Injection for MessageService.
3 Use View annotation to specify which template to use to render the response.
4 The @Get annotation maps the sayHello method to an HTTP GET request on /hello/{name}.
5 Use jakarta.validation.constraints Constraints to ensure the data matches your expectations.

8. Assets

Then create a static CSS file in config/static/css/style.css:

config/static/css/style.css
html, body {
    margin: 0;
    padding: 0.5em;
    background: #eee;
    font-family: sans-serif;
    color: #333;
}

section {
    display: flex;
    flex-direction: column;
    text-align: center;
    justify-content: left;
    width: fit-content;
}

section h1 {
    margin: 0;
    padding: 0.5em;
    font-size: 1.5em;
    font-variant: small-caps;
}

And a static PNG file in config/static/images/micronaut_stacked_black.png:

micronaut stacked black

8.1. Configuration

We can then add a static-mapping to our application.toml so that any missing requests are attempted to be resolved from the static assets.

First configure a route /css/*.css to map any routes matching that pattern to be mapped to the static/css resources.

config/application.toml
[micronaut.router.static-resources.css]
mapping = "/css/*.css"
paths = "classpath:static/css"
  • The first line matches any request to the server that does not match a controller route.

  • The second line defines that the classpath inside a root static directory should be searched for the resource.

This means that a request to /css/style.css will be resolved to config/static/css/style.css (if that resource exists and there is no matching controller path).

And then configure a route /images/** to be mapped to the static/images resources. We use a wildcard here as images may have different file extensions.

config/application.toml
[micronaut.router.static-resources.images]
mapping = "/images/**"
paths = "classpath:static/images"

This means that a request to /images/some/image.png will be resolved to config/static/images/some/image.png (if that resource exists and there is no matching controller path).

8.2. A note on wildcard mappings

For every request, the framework searches for a controller route; if no route is found, it searches for a static resource. In the above configuration, we could have used a single wildcard mapping for all assets similar to:

A wasteful wildcard example
[micronaut.router.static-resources.assets]
mapping = "/**"
paths = "classpath:static"

However, searching for a static resource in every request is a waste. We know specific paths (e.g., /bogus) will not match any resource.

Therefore, as we only want to search for static resources for paths starting with /css or /images, we can limit our static resource mappings to these paths.

9. Testing

Create a test that verifies the MessageService is working as expected.

tests/example/micronaut/test_message_service.py
import pytest

from pyronaut.test import MicronautTest, micronaut_test_fixture

from example.micronaut.message_service import MessageService


@pytest.fixture
def my_context(request):
    fixture = micronaut_test_fixture(
        request,
        MicronautTest(start_application=False),  (1)
    )
    yield fixture
    fixture.stop()


@pytest.fixture
def service(my_context):
    return my_context[MessageService]  (2)


def test_it_works(service):
    assert service.say_hello("Tim") == "Hello Tim!"


def test_validation_with_blank(service):
    with pytest.raises(BaseException) as exc:
        service.say_hello("   ")

    assert "say_hello.name: must not be blank" in str(exc.value)
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
2 Inject the MessageService bean.

And another that verifies the generated HTML contains the expected text.

tests/example/micronaut/test_main_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_it_works(client):
    response = client.get("/hello/Tim")

    assert response.status_code == 200
    assert "<h1>Hello Tim!</h1>" in response.text
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.

And another that verifies the static resources are returned on the expected URLs.

tests/example/micronaut/test_static_resource.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_stylesheet_exists(client):
    response = client.get("/css/style.css")

    assert response.status_code == 200
    assert "html, body {" in response.text


def test_image_exists(client):
    response = client.get("/images/micronaut_stacked_black.png")

    assert response.status_code == 200
    with open("config/static/images/micronaut_stacked_black.png", "rb") as image:
        assert len(response.content) == len(image.read())
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.

10. Testing the Application

To run the tests:

pyronaut install
pyronaut validate-config
pyronaut test

11. Running the Application

To run the application, use the pyronaut dev command, which starts the application on port 8080.

Visit http://localhost:8080/hello/Micronaut and the browser displays our templated HTML page with styling and an image.

12. Next Steps

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