Documenting RESTful APIs

duration 20 minutes

Explore how to document and filter RESTful APIs from code or static files by using MicroProfile OpenAPI.

What you’ll learn

You will learn how to document and filter RESTful APIs from annotations, POJOs, and static OpenAPI files by using MicroProfile OpenAPI.

The OpenAPI specification, previously known as the Swagger specification, defines a standard interface for documenting and exposing RESTful APIs. This specification allows both humans and computers to understand or process the functionalities of services without requiring direct access to underlying source code or documentation. The MicroProfile OpenAPI specification provides a set of Java interfaces and programming models that allow Java developers to natively produce OpenAPI v3 documents from their JAX-RS applications.

You will document the RESTful APIs of the provided inventory service, which serves two endpoints, inventory/systems and inventory/properties. These two endpoints function the same way as in the other MicroProfile gudes.

Before you proceed, note that the 1.0 version of the MicroProfile OpenAPI specification does not define how the /openapi endpoint may be partiontioned in the event of multiple JAX-RS applications running on the same server. In other words, you must stick to one JAX-RS application per server instance as the behaviour for handling multiple applications is currently undefined.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone
cd guide-microprofile-openapi

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project, which is what you will build.

Try what you’ll build

The finish directory in the root directory of this guide contains the fully documented inventory service. Feel free to give it a try before you proceed.

To try out the service, navigate to the finish directory and then run the Maven install and liberty:start-server goals to build and run the service in Open Liberty:

mvn install liberty:start-server

Next, point your browser to the http://localhost:9080/openapi URL and you’ll see the RESTful APIs of the inventory service. You can also point to the http://localhost:9080/openapi/ui URL for a more interactive view of the deployed APIs.

When you are done checking out the service and its APIs, stop Open Liberty:

mvn liberty:stop-server

Generating the OpenAPI document for the inventory service

You can generate an OpenAPI document in various ways. First, because all JAX-RS annotations are processed by default, you can augment your existing JAX-RS annotations with OpenAPI annotations to enrich your APIs with a minimal amount of work. Second, you can use a set of predefined models to manually create all elements of the OpenAPI tree. Finally, you can filter various elements of the OpenAPI tree, changing them to your liking or removing them entirely.

Before you proceed, deploy the inventory service to see the bare-bones OpenAPI document that is generated. To deploy the inventory service, run the Maven install phase and the liberty:start-server goal:

mvn install liberty:start-server

The install phase builds the application and packages it into the target/mp-openapi.war file. It also downloads Open Liberty into the target/liberty/wlp directory and configures it to run the application. The liberty:start-server goal starts an Open Liberty server instance.

Because the JAX-RS framework handles basic API generation for JAX-RS annotations, a skeleton OpenAPI tree will be generated from the inventory service. You can use this tree as a starting point and augment it with annotations and code to produce a complete OpenAPI document.

Now, point to the http://localhost:9080/openapi URL to see the generated OpenAPI tree. You can also point to the http://localhost:9080/openapi/ui URL for a more interactive view of the APIs.

Augmenting the existing JAX-RS annotations with OpenAPI annotations

Because all JAX-RS annotations are processed by default, you can augment the existing code with OpenAPI annotations without needing to rewrite portions of the OpenAPI document that are already covered by the JAX-RS framework.

Add OpenAPI annotations to the two JAX-RS methods, getPropertiesForHost() and listContents(), in the src/main/java/io/openliberty/guides/inventory/ file:

package io.openliberty.guides.inventory;

import java.util.Properties;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;

import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
import io.openliberty.guides.inventory.model.InventoryList;

public class InventoryResource {

    InventoryManager manager;

        value = {
                responseCode = "404",
                description = "Missing description",
                content = @Content(mediaType = "text/plain")),
                responseCode = "200",
                description = "JVM system properties of a particular host.",
                content = @Content(mediaType = "application/json",
                schema = @Schema(implementation = Properties.class))) })
        summary = "Get JVM system properties for particular host",
        description = "Retrieves and returns the JVM system properties from the system "
        + "service running on the particular host.")
    public Response getPropertiesForHost(
            description = "The host for whom to retrieve the JVM system properties for.",
            required = true,
            example = "foo",
            schema = @Schema(type = SchemaType.STRING))
        @PathParam("hostname") String hostname) {
        Properties props = manager.get(hostname);
        if (props == null) {
            return Response.status(Response.Status.NOT_FOUND)
                            .entity("ERROR: Unknown hostname or the system service may "
                                + "not be running on " + hostname)
        return Response.ok(props).build();

        responseCode = "200",
        description = "host:properties pairs stored in the inventory.",
        content = @Content(
            mediaType = "application/json",
            schema = @Schema(
                type = SchemaType.OBJECT,
                implementation = InventoryList.class)))
        summary = "List inventory contents.",
        description = "Returns the currently stored host:properties pairs in the "
        + "inventory.")
    public InventoryList listContents() {
        return manager.list();


There is quite a bit more annotations now, so lets break them down:



A container for multiple responses from an API operation. This annotation is optional, but it can be helpful to organize a method with multiple responses.


Describes a single response from an API operation.


Provides a schema and examples for a particular media type.


Defines the input and output data types.


Describes a single API operation on a path.


Describes a single operation parameter.

At this point, you can run the mvn compile command to rebuild the application. Then, refresh the http://localhost:9080/openapi URL to see the updated OpenAPI tree. The two endpoints at which your JAX-RS methods are served are now more meaningful:

    summary: Get JVM system properties for particular host
    description: Retrieves and returns the JVM system properties from the system
      service running on the particular host.
    operationId: getPropertiesForHost
    - name: hostname
      in: path
      description: The host for whom to retrieve the JVM system properties for.
      required: true
        type: string
      example: foo
        description: Missing description - to be filtered.
          text/plain: {}
        description: JVM system properties of a particular host.
              $ref: '#/components/schemas/Properties'
    summary: List inventory contents.
    description: Returns the currently stored host:properties pairs in the inventory.
    operationId: listContents
        description: host:properties pairs stored in the inventory.
              $ref: '#/components/schemas/InventoryList'

OpenAPI annotations can also be added to POJOs to describe what they represent. Currently, your OpenAPI document doesn’t have a very meaningful description of the InventoryList POJO and hence it’s very difficult to tell excatly what that POJO is used for. To describe the InventoryList POJO in more detail, augment the src/main/java/io/openliberty/guides/inventory/model/ file with some OpenAPI annotations:

package io.openliberty.guides.inventory.model;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


@Schema(name="InventoryList", description="POJO that represents the inventory contents.")
public class InventoryList {

    @Schema(required = true)
    private List<System> systems = new ArrayList<System>();

    public List<System> getSystems() {
        return systems;

    public int getTotal() {
        return systems.size();

    public void addToInventoryList(String hostname, Properties systemProps) {
        Properties props = new Properties();
        props.setProperty("", systemProps.getProperty(""));
        props.setProperty("", systemProps.getProperty(""));

        System host = new System(hostname, props);
        if (!systems.contains(host)) {

    @Schema(name="System", description="POJO that represents a single inventory entry.")
    class System {

        @Schema(required = true)
        private final String hostname;

        @Schema(required = true)
        private final Properties properties;

        public System(String hostname, Properties properties) {
            this.hostname = hostname;
   = properties;

        public String getHostname() {
            return hostname;

        public Properties getProperties() {
            return properties;

        public boolean equals(Object host) {
            if (host instanceof System) {
                return hostname.equals(((System) host).getHostname());
            return false;

Again, run the mvn compile command and refresh the http://localhost:9080/openapi URL to see the updated OpenAPI tree:

      - systems
      type: object
          type: array
            $ref: '#/components/schemas/System'
          type: integer
      description: POJO that represents the inventory contents.
      type: object
        type: string
      - hostname
      - properties
      type: object
          type: string
          type: object
            type: string
      description: POJO that represents a single inventory entry.

Filtering the OpenAPI tree elements

Filtering of certain elements and fields of the generated OpenAPI document can be done by using the OASFilter interface.

Implement the OASFilter interface in the src/main/java/io/openliberty/guides/inventory/filter/ file:

package io.openliberty.guides.inventory.filter;

import java.util.Arrays;

import org.eclipse.microprofile.openapi.OASFactory;
import org.eclipse.microprofile.openapi.OASFilter;
import org.eclipse.microprofile.openapi.models.OpenAPI;
import org.eclipse.microprofile.openapi.models.responses.APIResponse;
import org.eclipse.microprofile.openapi.models.servers.Server;
import org.eclipse.microprofile.openapi.models.servers.ServerVariable;
import org.eclipse.microprofile.openapi.models.servers.ServerVariables;

public class InventoryOASFilter implements OASFilter {

  public APIResponse filterAPIResponse(APIResponse apiResponse) {
    if ("Missing description".equals(apiResponse.getDescription())) {
      apiResponse.setDescription("Invalid hostname or the system service may not "
          + "be running on the particular host.");
    return apiResponse;

  public void filterOpenAPI(OpenAPI openAPI) {
        OASFactory.createObject(Info.class).title("Inventory App").version("1.0")
                      "App for storing JVM system properties of various hosts.")
                                .name("Eclipse Public License - v 1.0").url(

                  .description("Simple Open Liberty.").variables(
                                                  "Server HTTP port.")


The filterAPIResponse() method allows filtering of APIResponse elements. When you override this method, it will be called once for every APIResponse element in the OpenAPI tree. In this case, you are matching the 404 response that is returned by the /inventory/systems/{hostname} endpoint and setting the previously missing description. To remove an APIResponse element or another filterable element, simply return null.

The filterOpenAPI() method allows filtering of the singleton OpenAPI element. Unlike other filter methods, when you override filterOpenAPI(), it is called only once as the last method for a particular filter. Hence, make sure that it doesn’t override any other filter operations that are called before it. Your current OpenAPI document doesn’t provide much information on the application itself or on what server and port it runs on. This information is usually provided in the info and servers elements, which are currently missing. Use the OASFactory class to manually set these and other elements of the OpenAPI tree from the org.eclipse.microprofile.openapi.models package. The OpenAPI element is the only element that cannot be removed since that would mean removing the whole OpenAPI tree.

Each filtering method is called once for each corresponding element in the model tree. You can think of each method as a callback for various key OpenAPI elements.

Before you can use the filter class that you created, create the src/main/webapp/META-INF/ configuration file with the following content:

mp.openapi.filter = io.openliberty.guides.inventory.filter.InventoryOASFilter

This configuration file is picked up automatically by MicroProfile Config and registers your filter by passing in the fully qualified name of the filter class into the mp.openapi.filter property.

Finally, run the mvn compile command and refresh the http://localhost:9080/openapi URL to see the updated OpenAPI tree:

  title: Inventory App
  description: App for storing JVM system properties of various hosts.
    name: Eclipse Public License - v 1.0
  version: "1.0"
- url: http://localhost:{port}
  description: Simple Open Liberty.
      description: Server HTTP port.
  description: Invalid hostname or the system service may not be running on
    the particular host.
    text/plain: {}

For more information about which elements you can filter, see the MicroProfile 1.3 API.

To learn more about MicroProfile Config, visit the MicroProfile Config GitHub repository and try one of the MicroProfile Config guides.

Using pregenerated OpenAPI documents

As an alternative to generating the OpenAPI model tree from code, you can provide a valid pregenerated OpenAPI document to describe your APIs. This document must be named openapi with a yml, yaml, or json extension and be placed under the META-INF directory. Depending on the scenario, the document might be fully or partially complete. If the document is fully complete, then you can disable annotation scanning entirely by setting the mp.openapi.scan.disable MicroProfile Config property to true. If the document is partially complete, then you can augment it with code.

You can find a complete OpenAPI document in the src/main/webapp/META-INF/openapi.yaml file. This document is the same as your current OpenAPI document with additional APIs for the /inventory/properties endpoint. To make use of this document, open this document in your favorite text editor and uncomment all of its lines. Since this document is complete, you can also set the mp.openapi.scan.disable property to true in the src/main/webapp/META-INF/ file:

mp.openapi.filter = io.openliberty.guides.inventory.filter.InventoryOASFilter
mp.openapi.scan.disable = true

Run the mvn compile command and refresh the http://localhost:9080/openapi URL to see the updated OpenAPI tree:

    summary: Get JVM system properties.
    description: Returns the JVM system properties for the host running this service.
    operationId: getProperties
        description: JVM system properties of the host running this service.
              $ref: '#/components/schemas/Properties'

Testing the service

No automated tests are provided to verify the correctness of the generated OpenAPI document. Manually verify the document by visiting the http://localhost:9080/openapi or the http://localhost:9080/openapi/ui URL.

A few tests are included for you to test the basic functionality of the inventory service. If a test failure occurs, then you might have introduced a bug into the code. These tests will run automatically as a part of the Maven build process when you run the mvn install command. You can also run these tests separately from the build by using the mvn verify command, but first make sure that the server is stopped.

Great work! You’re done!

You have just documented and filtered the APIs of the inventory service from both the code and a static file by using MicroProfile OpenAPI.

Feel free to try one of the related MicroProfile guides. They demonstrate additional technologies that you can learn and expand on top of what you built here.

For more in-depth examples of MicroProfile OpenAPI, try one of the demo applications avilable in the MicroProfile OpenAPI GitHub repository.

Contribute to this guide

Is something missing or broken? Raise an issue, or send us a pull request.