SmallRye OpenAPI

repository·main·Indexed 40 days ago

https://github.com/smallrye/smallrye-open-api

An implementation of the Eclipse MicroProfile OpenAPI specification that generates OpenAPI documentation from Java applications. It supports JAX-RS, Spring, and Vert.x, and provides a Gradle plugin for integration. Key features include configurable operationId generation strategies, automatic schema inheritance, unused component and tag removal, and a flexible scanning system via OpenApiConfig.

Tokens
6.2K
Snippets
19
Records
26
Agent score
100%

What's inside SmallRye OpenAPI

  1. Configure operationId generation strategy

    main

    Use the operationIdStrategy property to control how operationId is generated for OpenAPI operations. This helps minimize collision risks.

    Available strategies:

    • METHOD: Uses the method name.
    • CLASS_METHOD: Uses the class name and method name.
    • PACKAGE_CLASS_METHOD: Uses the fully qualified class name and method name.
  2. Install the SmallRye OpenAPI Maven Plugin

    main

    To generate an OpenAPI Schema during your Maven build, add the smallrye-open-api-maven-plugin to your pom.xml. By default, the generated schema files will be placed in target/generated/openapi.yaml and target/generated/openapi.json.

    <plugin>
        <artifactId>smallrye-open-api-maven-plugin</artifactId>
        <groupId>io.smallrye</groupId>
        <executions>
            <execution>
                <goals>
                    <goal>generate-schema</goal>
                </goals>
            </execution>
        </executions>
        <!-- Uncomment the dependency overrides for JDK 1.8 compatibility: -->
        <!--
        <dependencies>
            <dependency>
                <groupId>io.smallrye.config</groupId>
                <artifactId>smallrye-config</artifactId>
                <version>2.13.3</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.logging</groupId>
                <artifactId>jboss-logging</artifactId>
                <version>3.4.3.Final</version>
            </dependency>
        </dependencies>
        -->
    </plugin>
  3. Add Swagger UI to your project with SmallRye OpenAPI UI

    main

    SmallRye OpenAPI UI allows you to integrate a Swagger UI into your project to visualize and interact with your OpenAPI documentation. Once included, the UI is automatically available at the /openapi-ui endpoint.

    Note: This extension expects your OpenAPI specification to be available at the /openapi endpoint.

    <dependency>
        <groupId>io.smallrye</groupId>
        <artifactId>smallrye-open-api-ui</artifactId>
        <version>xyz</version>
        <scope>runtime</scope>
    </dependency>
  4. Filter OpenAPI resources using Scan Profiles

    main

    You can limit which REST endpoints and resources are included in the OpenAPI model using scan profiles. This is achieved by combining the x-smallrye-profile-{profileName} extension on methods with the mp.openapi.extensions.smallrye.scan.profiles or mp.openapi.extensions.smallrye.scan.exclude.profiles configuration properties.

    Step 1: Annotate your methods Use @Extension to assign a profile name to a method.

    @Path("/api")
    public class MyResource {
        @Path("/users")
        @GET
        @Extension(name = "x-smallrye-profile-user", value = "")
        public List<UserDTO> listUsers() { ... }
    
        @Path("/orders")
        @GET
        @Extension(name = "x-smallrye-profile-order", value = "")
        public List<OrderDTO> listOrders() { ... }
    }

    Step 2: Configure the scan

    • To include only the 'user' profile: Set mp.openapi.extensions.smallrye.scan.profiles=user.
    • To exclude the 'order' profile: Set mp.openapi.extensions.smallrye.scan.exclude.profiles=order.

    Note: Path items where all operations have been excluded will be removed from the model unless the path item is in the components section. Profiles are processed after the model is merged but before user-provided filters.

    import org.eclipse.microprofile.openapi.annotations.extensions.Extension;
    
    @Path("/api")
    public class MyResource {
        @Path("/users")
        @GET
        @Extension(name = "x-smallrye-profile-user", value = "")
        public List<UserDTO> listUsers() {
            // ...
        }
    
    @Path("/orders")
        @GET
        @Extension(name = "x-smallrye-profile-order", value = "")
        public List<OrderDTO> listOrders() {
            // ...
        }
    }
  5. Use x-smallrye-directives to retain components or tags

    main

    The retain directive allows you to prevent the automatic removal of unreferenced components or tags when using mp.openapi.extensions.smallrye.remove-unused-components or mp.openapi.extensions.smallrye.remove-unused-tags.enable.

    Using in Java: Apply the retain directive via the @Extension annotation on the @Schema annotation.

    @Schema(
        extensions = @Extension(name = "x-smallrye-directives", value = "retain,other-directive"),
        comment = "This class uses the `retain` directive to avoid removal")
    class MyUnusedBean {
        String name;
        Integer age;
    }

    Using in YAML/JSON: Add the x-smallrye-directives key to the component definition.

    openapi: 3.1.0
    components:
      schemas:
        MyUnusedBean:
          comment: This class uses the `retain` directive to avoid removal
          x-smallrye-directives:
            - retain
            - other-directive
  6. Try out the OpenAPI Gradle plugin via Gradle `includeBuild`

    main

    You can make the plugin available to your build without installing it to a repository by using Gradle's includeBuild feature.

    1. Configure settings: Add the following snippet to your Gradle project's settings.gradle[.kts], replacing FULL_PATH_TO_tools/gradle-plugin with the actual absolute path to the plugin source:

      includeBuild("FULL_PATH_TO_tools/gradle-plugin")
    2. Apply the plugin: In your target project's build.gradle[.kts], apply the plugin using the standard mechanism:

      plugins {
          id("io.smallrye.openapi")
      }
    includeBuild("FULL_PATH_TO_tools/gradle-plugin")
  7. Try out the OpenAPI Gradle plugin via local Maven repository

    main

    To use the OpenAPI Gradle plugin in a separate project using the local Maven repository, follow these steps:

    1. Deploy the plugin: Navigate to the plugin directory in the source repository and run the publish command:

      cd tools/gradle-plugin
      ./gradlew publishToMavenLocal
    2. Configure Gradle settings: In your target project's settings.gradle[.kts], ensure mavenLocal() is included in the pluginManagement repositories so Gradle can resolve the plugin:

      pluginManagement {
          repositories {
              gradlePluginPortal()
              mavenLocal()
          }
      }
    3. Apply the plugin: In your target project's build.gradle[.kts], apply the plugin using its ID and the exact version of the project you deployed:

      plugins {
          id("io.smallrye.openapi.gradleplugin") version "EXACT_VERSION_OF_THE_PROJECT"
      }
    cd tools/gradle-plugin
    ./gradlew publishToMavenLocal
  8. Configure Operation ID Generation Strategy

    main

    Specify a global strategy for generating operationIds when they are not provided via annotations or static input using mp.openapi.extensions.smallrye.operationIdStrategy.

    Allowed Values:

    • METHOD: Uses the REST endpoint method name (may cause duplicates if method names are not unique across the app).
    • CLASS_METHOD: Uses the simple class name + method name (may cause duplicates if class/method combinations are not unique).
    • PACKAGE_CLASS_METHOD: Uses the package + class + method name.
    • Custom Implementation: A fully-qualified class name of an implementation of io.smallrye.openapi.api.OperationIdGenerator.
    mp.openapi.extensions.smallrye.operationIdStrategy
  9. Remove Unused Tags from OpenAPI Model

    main

    Enable automatic removal of unused tags from the top-level tags array by setting mp.openapi.extensions.smallrye.remove-unused-tags.enable to true.

    • Definition of Unused: A tag is considered unused if it is not referenced by any operation in the paths section.
    • Behavior: Unused tags are removed after annotation scanning and after all configured OASFilter instances have run.
    • Retention: To keep an unreferenced tag, use the retain directive within the x-smallrye-directives extension.
    mp.openapi.extensions.smallrye.remove-unused-tags.enable
  10. Configure Automatic Schema Inheritance

    main

    Control how schema inheritance is handled in the OpenAPI model using mp.openapi.extensions.smallrye.auto-inheritance.

    Allowed Values:

    • NONE (default): Disables automatic inheritance. Parent class properties are included in the child class properties map unless @Schema(allOf = { ... }) is explicitly specified on the child.
    • BOTH: Enables automatic inheritance by placing both the child and parent class within the child schema's allOf property, unless @Schema(allOf = { ... }) is already specified.
    • PARENT_ONLY: Enables automatic inheritance by placing only the parent class within the child schema's allOf property, unless @Schema(allOf = { ... }) is already specified.

    Disabling for specific classes: To disable automatic inheritance for a specific class, set @Schema(allOf = void.class) on that class.

    mp.openapi.extensions.smallrye.auto-inheritance
  11. Configure Operation ID generation strategies

    main

    You can control how operationId values are generated using the getOperationIdStrategy() method. The available strategies are defined in the OperationIdStrategy class:

    • METHOD: Uses the resource method's name.
    • CLASS_METHOD: Uses the resource class's simple name and the resource method's name.
    • PACKAGE_CLASS_METHOD: Uses the resource class's fully-qualified name and the resource method's name.
    // Example of the strategy names used in configuration
    String strategy = OpenApiConfig.OperationIdStrategy.CLASS_METHOD;