Creating a Micronaut GraalPy application using a Python package

Learn how to create a simple Micronaut GraalPy application using a third party Python package.

Authors: Tomas Stupka

Micronaut Version: 4.6.3

1. Getting Started

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

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=graalpy \
    --build=maven \
    --lang=java \
    --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 graalpy 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. GraalPy Maven Plugin

Insert a <packages> element into the GraalPy Maven Plugin <configuration> element, specifying the Python packages to download and install as shown below:

src/main/../../pom.xml
      <plugin>
          <groupId>org.graalvm.python</groupId>
          <artifactId>graalpy-maven-plugin</artifactId>
          <version>${graalpy.maven.plugin.version}</version>
      
          <executions>
            <execution>
              <goals>
                <goal>process-graalpy-resources</goal>
              </goals>
            </execution>
          </executions>
      </plugin>

Adding <package>pygal==3.0.4</package> instructs the plugin to download and install the Python Pygal package at build time. The package is included in the Java resources and becomes available to GraalPy.

4.2. Python code

We are going to use the StackedBar class from Pygal package to render a graph in Svg format.

4.3. Java binding

Python code can be accessed programmatically using the GraalVM SDK Polyglot API, which enables you to embed Python into your applications.

In order to make it work, we first need a Java interface providing the intended binding to Python.

Create a Java interface with the following code:

src/main/java/example/micronaut/PygalModule.java
package example.micronaut;

import io.micronaut.graal.graalpy.annotations.GraalPyModule;

@GraalPyModule("pygal") (1)
interface PygalModule {
    StackedBar StackedBar(); (2)

    interface StackedBar { (3)
        void add(String title, int[] i); (4)
        Svg render(); (5)
    }

    interface Svg { (6)
        String decode(); (7)
    }
}
1 The @GraalPyModule annotation indicates that the bean created from the interface is intended to import the pygal Python package and expose it to the Java code using the Target type mapping.
2 Java method matching the StackedBar Python class constructor.
3 Java interface with methods matching functions from the StackedBar Python class we want to use.
4 Java method matching the StackedBar.add(title, values) Python function.
5 Java method matching the StackedBar.render() Python function.
6 Java interface with methods matching functions from the Svg Python class we want to use.
7 Java method matching the Svg.decode() Python function.

4.4. Controller

To create a microservice that provides the graph rendered by Pygal you also need a controller.

Create a controller:

src/main/java/example/micronaut/PygalController.java
package example.micronaut;

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Produces;
import io.micronaut.scheduling.TaskExecutors;
import io.micronaut.scheduling.annotation.ExecuteOn;

@Controller("/pygal") (1)
class PygalController {

    private final PygalModule pygal;

    PygalController(PygalModule pygal) {  (2)
        this.pygal = pygal;
    }

    @ExecuteOn(TaskExecutors.BLOCKING)
    @Get (3)
    @Produces("image/svg+xml") (4)
    public String index() {
        PygalModule.StackedBar stackedBar = pygal.StackedBar(); (5)
        stackedBar.add("Fibonacci", new int[] {0, 1, 1, 2, 3, 5, 8}); (6)
        PygalModule.Svg svg = stackedBar.render(); (7)
        return svg.decode(); (8)
    }

}
1 The class is defined as a controller with the @Controller annotation mapped to the path /pygal.
2 Use constructor injection to inject a bean of type PygalModule.
3 The @Get annotation maps the index method to an HTTP GET request on /pygal.
4 By default, a Micronaut response uses application/json as Content-Type. We are returning svg/xml, so we have to set it.
5 Use the PygalModule bean to create a PygalModule.StackedBar instance.
6 Add graph title and data.
7 Render the graph.
8 Return the graphs svg/xml representation decoded as a string.

4.5. Test

Create a test to verify that when you make a GET request to /pygal you get the svg/xml response:

src/test/java/example/micronaut/PygalControllerTest.java
package example.micronaut;

import io.micronaut.http.HttpRequest;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.runtime.server.EmbeddedServer;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertTrue;

@MicronautTest (1)
class PygalControllerTest {

    @Test
    void testPygalResponse(@Client("/") HttpClient client) { (2)
        String response = client.toBlocking().retrieve(HttpRequest.GET("/pygal")); (3)
        assertTrue(response.contains("<svg xmlns:xlink"));
        assertTrue(response.contains("<title>Pygal</title>"));
        assertTrue(response.contains("<g class=\"graph stackedbar-graph vertical\">"));
    }
}
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.

5. Testing the Application

To run the tests:

./mvnw test

6. Running the Application

To run the application, use the ./mvnw mn:run command, which starts the application on port 8080.

Open http://localhost:8080/pygal in a web browser of your choice execute the endpoint. You should see a stacked bar chart.

graalpy pygal

7. Next steps

Read more about Micronaut testing.

8. Help with the Micronaut Framework

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

9. License

All guides are released with an Apache license 2.0 license for the code and a Creative Commons Attribution 4.0 license for the writing and media (images…​).