Chapter 7. Adding MicroProfile OpenAPI annotations to your REST controller code

You can add MicroProfile OpenAPI annotations to your rest controller code to generate a more detailed OpenAPI schema for your rest endpoints.

Procedure

  1. Add the @OpenApiDefinition annotation at the class level of your GreetingController. Include the data that is shown in the example in the annotation:

    @OpenAPIDefinition(
        info = @Info(
            title="Greeting API",
            version = "1.0.1",
            contact = @Contact(
                name = "Greeting API Support",
                url = "http://exampleurl.com/contact",
                email = "techsupport@example.com"),
            license = @License(
                name = "Apache 2.0",
                url = "https://www.apache.org/licenses/LICENSE-2.0.html"))
    )
  2. Annotate your endpoint definitions using the @Tag annotation. Give a name and a description for each endpoint:

    @Tag(name = "Hello", description = "Just say hello")
    @GetMapping(produces=MediaType.TEXT_PLAIN_VALUE)
    public String hello() {
        return "hello";
    }
    
    @GetMapping(value = "/{name}", produces=MediaType.APPLICATION_JSON_VALUE)
    @Tag(name = "Hello to someone", description = "Just say hello to someone")
    public Greeting hello(@PathVariable(name = "name") String name) {
        return new Greeting("hello " + name);
    }

    The data that you provided in the annotations appears in the generated OpenAPI schema:

    openapi: 3.0.3
    info:
      title: Greeting API
      contact:
        name: Greeting API Support
        url: http://exampleurl.com/contact
        email: techsupport@example.com
      license:
        name: Apache 2.0
        url: https://www.apache.org/licenses/LICENSE-2.0.html
      version: 1.0.1
    tags:
    - name: Hello
        description: Just say hello
    - name: Hello to someone
        description: Just say hello to someone
    paths:
      /greeting:
        get:
          tags:
          - Hello
          responses:
            '200':
              description: OK
              content:
                text/plain:
                  schema:
                    type: string
      /greeting/{name}:
        get:
          tags:
          - Hello to someone
          parameters:
          - name: name
            in: path
            required: true
            schema:
              type: string
          responses:
            '200':
              description: OK
              content:
                application/json:
                  schema:
                    $ref: '#/components/schemas/Greeting'
    
    components:
      schemas:
        Greeting:
          type: object
          properties:
            message:
              type: string