Contents
Overview
The OpenAPI specification defines a standard way to express the interface exposed by a REST service.
The MicroProfile OpenAPI spec explains how MicroProfile embraces OpenAPI, adding annotations, configuration, and a service provider interface (SPI).
Helidon MP implements the MicroProfile OpenAPI specification.
The OpenAPI support in Helidon MP performs two main tasks:
Build an in-memory model of the REST API your service implements.
Expose the model in text format (typically YAML) via the
/openapiendpoint.
To construct the model, Helidon gathers information about the service API from whichever of these sources are present in the application:
a model reader
The SPI defines an interface you can implement in your application for programmatically providing part or all of the model;
a static OpenAPI document file packaged as part of your service;
OpenAPI annotations;
a filter class
The SPI defines an interface you can implement in your application which can mask parts of the model.
Maven Coordinates
To enable MicroProfile OpenAPI either add a dependency on the helidon-microprofile bundle or add the following dependency to your project’s pom.xml (see Managing Dependencies).
<dependencies>
<dependency>
<groupId>org.eclipse.microprofile.openapi</groupId>
<artifactId>microprofile-openapi-api</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.microprofile.openapi</groupId>
<artifactId>helidon-microprofile-openapi</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>- Defines the MicroProfile OpenAPI annotations so you can use them in your code.
- Adds the Helidon MP OpenAPI runtime support.
Usage
OpenAPI support in Helidon MP
You can very simply add support for OpenAPI to your Helidon MP application. This document shows what changes you need to make to your application and how to access the OpenAPI document for your application at runtime.
Changing your application
To use OpenAPI from your Helidon MP app, in addition to adding dependencies as described above:
- Furnish OpenAPI information about your application’s endpoints.
- Update your application’s configuration (optional).
Furnish OpenAPI information about your endpoints
Helidon MP OpenAPI combines information from all of the following sources as it builds its in-memory model of your application’s API. It constructs the OpenAPI document from this internal model. Your application can use one or more of these techniques.
Annotate the endpoints in your app
You can add MicroProfile OpenAPI annotations to the endpoints in your source code. These annotations allow the Helidon MP OpenAPI runtime to discover the endpoints and information about them via CDI at app start-up.
Here is one of the endpoints, annotated for OpenAPI, from the example mentioned earlier:
@GET
@Operation(summary = "Returns a generic greeting",
description = "Greets the user generically")
@APIResponse(description = "Simple JSON containing the greeting",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = GreetingMessage.class)))
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getDefaultMessage() {...}@Operationgives information about this endpoint.@APIResponsedescribes the HTTP response and declares its media type and contents.
You can also define any request parameters the endpoint expects, although this endpoint uses none.
This excerpt shows only a few annotations for illustration. The Helidon MP OpenAPI example illustrates more, and the MicroProfile OpenAPI spec describes them all.
Provide a static OpenAPI file
Add a static file at META-INF/openapi.yml, META-INF/openapi.yaml, or META-INF/openapi.json. Tools such as Swagger let you describe your app’s API and they then generate an OpenAPI document file which you can include in your application so OpenAPI can use it.
Write and configure a model reader class
Write a Java class that implements the OpenAPI org.eclipse.microprofile.openapi.OASModelReader interface. Your model reader code programmatically adds elements to the internal model that OpenAPI builds.
Provide a static OpenAPI file
Add a static file at META-INF/openapi.yml, META-INF/openapi.yaml, or META-INF/openapi.json. Tools such as Swagger let you describe your app’s API and they then generate an OpenAPI document file which you can include in your application so OpenAPI can use it.
Write and configure a model reader class
Write a Java class that implements the OpenAPI org.eclipse.microprofile.openapi.OASModelReader interface. Your model reader code programmatically adds elements to the internal model that OpenAPI builds.
Change your application’s MP configuration to set mp.openapi.model.reader as the fully-qualified class name of your class.
Write and configure a filter class
Write a Java class that implements the OpenAPI org.eclipse.microprofile.openapi.OASFilter interface. As OpenAPI composes its internal model, it invokes your filter with each model element before adding the element to the model. Your filter can accept the element as-is, modify it, or suppress it.
Change your application’s configuration to set mp.openapi.filter as the full-qualified class name of your class.
Update your application configuration
Beyond the two config properties that denote the model reader and filter, Helidon MP OpenAPI supports a number of other mandated settings. These are described in the configuration section of the MicroProfile OpenAPI spec.
Accessing the REST Endpoint
Once you add the MP OpenAPI dependency to your project, your application will automatically respond to the built-in endpoint — /openapi — and it will return the OpenAPI document describing the endpoints in your application.
By default, per the MicroProfile OpenAPI spec, the default format of the OpenAPI document is YAML. There is not yet an adopted IANA YAML media type, but a proposed one specifically for OpenAPI documents that has some support is application/vnd.oai.openapi. That is what Helidon returns, by default.
In addition, a client can specify the HTTP header Accept as either application/vnd.oai.openapi+json or application/json to request JSON. Alternatively, the client can pass the query parameter format as either JSON or YAML to receive application/json or application/vnd.oai.openapi (YAML) output, respectively.
API
The MicroProfile OpenAPI specification gives a listing and brief examples of the annotations you can add to your code to convey OpenAPI information.
The MicroProfile OpenAPI JavaDocs give full details of the annotations and the other classes and interfaces you can use in your code.
Configuration
Helidon OpenAPI configuration supports the following settings:
Type: io.helidon.microprofile.openapi.MPOpenAPISupport
mp.openapiConfiguration options
| key | type | default value | description |
|---|---|---|---|
application-path-disable | boolean | false | Sets whether the app path search should be disabled. |
cors | Assigns the CORS settings for the OpenAPI endpoint. | ||
custom-schema-registry-class | string | Sets the custom schema registry class. | |
filter | string | Sets the developer-provided OpenAPI filter class name. | |
model.reader | string | Sets the developer-provided OpenAPI model reader class name. | |
scan.classes | string[] | Specify the list of classes to scan. | |
scan.disable | boolean | false | Disable annotation scanning. |
scan.exclude.classes | string[] | Specify the list of classes to exclude from scans. | |
scan.exclude.packages | string[] | Specify the list of packages to exclude from scans. | |
scan.packages | string[] | Specify the list of packages to scan. | |
schema.* | string | Sets the schema for the indicated fully-qualified class name (represented here by '*'); value is the schema in JSON format. Repeat for multiple classes. | |
servers | string[] | Sets servers. | |
servers.operation.* | string[] | Sets alternative servers to service the indicated operation (represented here by '*'). Repeat for multiple operations. | |
servers.path.* | string[] | Sets alternative servers to service all operations at the indicated path (represented here by '*'). Repeat for multiple paths. | |
static-file | string | META-INF/openapi.* | Sets the file system path of the static OpenAPI document file. Default types are |
web-context | string | /openapi | Sets the web context path for the OpenAPI endpoint. |
Examples
Helidon MP includes a complete OpenAPI example based on the MP quick-start sample app. The rest of this section shows, step-by-step, how one might change the original QuickStart service to adopt OpenAPI.
Helidon MP Basic OpenAPI Example
This example shows a simple greeting application, similar to the one from the Helidon MP QuickStart, enhanced with OpenAPI support.
@Path("/greeting")
@PUT
@Operation(summary = "Set the greeting prefix",
description = "Permits the client to set the prefix part of the greeting (\"Hello\")")
@RequestBody(
name = "greeting",
description = "Conveys the new greeting prefix to use in building greetings",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = GreetingUpdateMessage.class),
examples = @ExampleObject(
name = "greeting",
summary = "Example greeting message to update",
value = "{\"greeting\": \"New greeting message\"}")))
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateGreeting(JsonObject jsonObject) {
...
}- With
@Operationannotation we document the current method. - With
@RequestBodyannotation we document the content produced. Internal annotations@Content,@Schemaand@ExampleObjectsare used to give more details about the returned data.
If we want to hide a specific path an OASFilter is used.
The OASFilter interface allows application developers to receive callbacks for various key OpenAPI elements. The interface has a default implementation for every method, which allows application developers to only override the methods they care about. To use it, simply create an implementation of this interface and register it using the mp.openapi.filter configuration key, where the value is the fully qualified name of the filter class.
The following example filter prevents information about a given path from appearing in the OpenAPI document.
import org.eclipse.microprofile.openapi.models.Operation;
import org.eclipse.microprofile.openapi.models.PathItem;
public class SimpleAPIFilter implements OASFilter {
@Override
public PathItem filterPathItem(PathItem pathItem) {
for (Map.Entry<PathItem.HttpMethod, Operation> methodOp
: pathItem.getOperations().entrySet()) {
if (SimpleAPIModelReader.DOOMED_OPERATION_ID
.equals(methodOp.getValue().getOperationId())) {
return null;
}
}
return OASFilter.super.filterPathItem(pathItem);
}
}You can implement a model reader to provide all or part of the in-memory OpenAPI model programmatically. Helidon OpenAPI merges the model from the model reader with models from the other sources (a static file and annotations).
The example model reader below creates an OpenAPI object describing two paths. It turns out that the filter described earlier will suppress one of the paths, but the model reader does not know or care.
import org.eclipse.microprofile.openapi.OASFactory;
import org.eclipse.microprofile.openapi.OASModelReader;
import org.eclipse.microprofile.openapi.models.OpenAPI;
import org.eclipse.microprofile.openapi.models.PathItem;
import org.eclipse.microprofile.openapi.models.Paths;
/**
* Defines two paths using the OpenAPI model reader mechanism, one that should
* be suppressed by the filter class and one that should appear in the published
* OpenAPI document.
*/
public class SimpleAPIModelReader implements OASModelReader {
/**
* Path for the example endpoint added by this model reader that should be visible.
*/
public static final String MODEL_READER_PATH = "/test/newpath";
/**
* Path for an endpoint that the filter should hide.
*/
public static final String DOOMED_PATH = "/test/doomed";
/**
* ID for an endpoint that the filter should hide.
*/
public static final String DOOMED_OPERATION_ID = "doomedPath";
/**
* Summary text for the endpoint.
*/
public static final String SUMMARY = "A sample test endpoint from ModelReader";
@Override
public OpenAPI buildModel() {
/*
* Add two path items, one of which we expect to be removed by
* the filter and a very simple one that will appear in the
* published OpenAPI document.
*/
PathItem newPathItem = OASFactory.createPathItem()
.GET(OASFactory.createOperation()
.operationId("newPath")
.summary(SUMMARY));
PathItem doomedPathItem = OASFactory.createPathItem()
.GET(OASFactory.createOperation()
.operationId(DOOMED_OPERATION_ID)
.summary("This should become invisible"));
OpenAPI openAPI = OASFactory.createOpenAPI();
Paths paths = OASFactory.createPaths()
.addPathItem(MODEL_READER_PATH, newPathItem)
.addPathItem(DOOMED_PATH, doomedPathItem);
openAPI.paths(paths);
return openAPI;
}
}Having written the filter and model reader classes, identify them by adding configuration to META-INF/microprofile-config.properties as the following example shows.
mp.openapi.filter=io.helidon.microprofile.examples.openapi.basic.internal.SimpleAPIFilter
mp.openapi.model.reader=io.helidon.microprofile.examples.openapi.basic.internal.SimpleAPIModelReaderNow just build and run:
mvn package
java -jar target/helidon-examples-microprofile-openapi-basic.jarTry the endpoints:
curl -X GET http://localhost:8080/greet
{"message":"Hello World!"}
curl -X GET http://localhost:8080/openapi
[lengthy OpenAPI document]The output describes not only then endpoints from GreetResource but also one contributed by the SimpleAPIModelReader.
Full example is available in our official repository
Additional Information
Building the Jandex index
A Jandex index stores information about the classes and methods in your app and what annotations they have. It allows CDI to process annotations faster during your application’s start-up.
Add the Jandex maven plug-in to the <build><plugins> section of your pom.xml:
<plugin>
<groupId>org.jboss.jandex</groupId>
<artifactId>jandex-maven-plugin</artifactId>
<version>{jandex-plugin-version}</version>
<executions>
<execution>
<id>make-index</id>
<goals>
<goal>jandex</goal>
</goals>
</execution>
</executions>
</plugin>When you build your app maven should include the index META-INF/jandex.idx in the JAR.
Note
If you do not modify your build to create the index then the Helidon MP OpenAPI runtime automatically creates one in memory during app start-up. This slows down your app start-up and, depending on how CDI is configured, might inadvertently miss information.
We strongly recommend using the Jandex plug-in to build the index into your app.