Micronaut JSON Schema

Generate a JSON Schema specification of your Java objects at compilation thanks to Micronaut JSON Schema.

Authors: Sergio del Amo

Micronaut Version: 4.6.3

1. Getting Started

This tutorial shows how to generate a JSON Schema of a Java class at compile-time using Micronaut JSON Schema. The example shows a JSON Schema, such as the one found in the Getting Started Tutorial on the Json Schema Website.

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=validation,json-schema \
    --build=gradle \
    --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 validation, and json-schema 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. JSON Schema dependencies

The jsonschema feature adds the following dependencies:

build.gradle
annotationProcessor("io.micronaut.jsonschema:micronaut-json-schema-processor")
build.gradle
implementation("io.micronaut.jsonschema:micronaut-json-schema-annotations")

4.2. JSON Schema annotation

First create a class:

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


import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.jsonschema.JsonSchema;
import jakarta.validation.constraints.*;

import java.util.Set;

/**
 *
 * @param productId  The unique identifier for a product (1)
 * @param productName Name of the product
 * @param price The price of the product
 * @param tags Product tags
 */
@JsonSchema(description = "A product from Acme's catalog") (2)
public record Product(
        @NotNull (3)
        Long productId,

        @NonNull
        @NotBlank
        String productName,

        @NotNull (3)
        @Positive (4)
        Double price,

        @Size(min = 1) (4)
        Set<String> tags
) {
}
1 You can use javadoc description or Jackson’s @JsonPropertyDescription to influence the JSON Schema property description.
2 Annotate with @JsonSchema to trigger the creation of a schema for it during build time:
3 You can use Nullability annotations or validation annotations to influence whether a property is required in the JSON Schema specification.
4 Validation annotations influence the generated JSON Schema.

At compilation-time a JSON Schema is generated at compile-time. You can test it as follows:

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

import io.micronaut.core.io.ResourceLoader;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;

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

@MicronautTest(startApplication = false) (1)
class JsonSchemaGeneratedTest {

    @Test
    void buildGeneratesJsonSchema(ResourceLoader resourceLoader) {
        assertTrue(resourceLoader.getResource("META-INF/schemas/product.schema.json").isPresent());
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context. This test does not need the embedded server. Set startApplication to false to avoid starting it.

4.3. Expose JSON Schema

We can expose the Json Schema generated at compile-time as a static resource with the following configuration:

src/main/resources/application.properties
micronaut.router.static-resources.jsonschema.mapping=/schemas/**
micronaut.router.static-resources.jsonschema.paths=classpath\:META-INF/schemas

You can test the JSON Schema specification is exposed:

src/test/java/example/micronaut/JsonSchemaExposedTest.java
package example.microanut;

import io.micronaut.http.client.BlockingHttpClient;
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.Test;

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

@MicronautTest (1)
class JsonSchemaExposedTest {

    @Test
    void productJsonSchemaExposed(@Client("/") HttpClient httpClient) { (2)
        BlockingHttpClient client = httpClient.toBlocking();
        assertDoesNotThrow(() -> client.exchange("/schemas/product.schema.json"));
    }
}
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.

4.4. Test

Last, let’s write a test that verifies the generated JSON Schema matches our expectations:

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

import io.micronaut.http.HttpRequest;
import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;

@MicronautTest (1)
class ProductSchemaTest {

    @Test
    void testProductSchema(@Client("/")HttpClient httpClient) (2)
            throws JSONException {
        BlockingHttpClient client = httpClient.toBlocking();
        HttpRequest<?> request = HttpRequest.GET("/schemas/product.schema.json");
        String json = assertDoesNotThrow(() -> client.retrieve(request));
        assertNotNull(json);
        String expected = """
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "http://localhost:8080/schemas/product.schema.json",
  "title": "Product",
  "description": "A product from Acme's catalog",
  "type": ["object"],
  "properties": {
    "productId": {
      "description": "The unique identifier for a product // <1>",
      "type": ["integer"]
    },
    "productName": {
      "description": "Name of the product",
      "type": ["string"]
    },
    "price": {
      "description": "The price of the product",
      "type": ["number"],
      "exclusiveMinimum": 0
    },
    "tags": {
      "type": ["array"],
      "items": {
        "type": ["string"]
      },
      "minItems": 1,
      "uniqueItems": true
    }
  },
  "required": [ "productId", "productName", "price" ]
}""";
        JSONAssert.assertEquals(expected, json, JSONCompareMode.LENIENT);
    }
}
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.

4.4.1. JSON Assert

The previous test uses JSON Assert:

Write JSON tests as if you are comparing a string. Under the covers, JSONassert converts your string into a JSON object and compares the logical structure and data with the actual JSON.

You need to add the dependency to your test classpath:

build.gradle
testImplementation("org.skyscreamer:jsonassert:1.5.3")

5. Testing the Application

To run the tests:

./gradlew test

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

6. Next steps

Read more about Micronaut JSON Schema and JSON Schema.

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