Creating your first Pyronaut application

Learn how to create a Hello World Pyronaut application with a controller and a functional test.

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

4.1. Controller

To create a microservice that responds with "Hello World", you first need a controller.

src/example/micronaut/hello_controller.py
from micronaut.http import MediaType
from micronaut.http.annotation import Get
from micronaut.http.annotation import Produces

@Get("/hello")  (1)
@Produces(MediaType.TEXT_PLAIN) (2)
def index() -> str:
    return "Hello World"  (3)
1 The @Get annotation maps the index method to an HTTP GET request on /hello.
2 By default, a Micronaut response uses application/json as Content-Type. We are returning a String, not a JSON object, so we set it to text/plain with the @Produces annotation.
3 A String "Hello World" is returned as the result.

4.2. Test

Create a test to verify that when you make a GET request to /hello you get Hello World as a response:

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

from micronaut.runtime.server import EmbeddedServer
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 base_url(my_context) -> str:
    server = my_context[EmbeddedServer]
    return f"http://localhost:{server.getPort()}"


def test_hello_world_response(base_url: str):
    response = requests.get(f"{base_url}/hello")  (2)

    assert response.text == "Hello World"  (3)
1 Start the application for the pytest fixture.
2 Send an HTTP request with the requests library.
3 Verify the response body.

5. Testing the Application

To run the tests:

pyronaut install
pyronaut validate-config
pyronaut test

6. Running the Application

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

You can execute the endpoint exposed by the native executable:

curl localhost:8080/hello
Hello World

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