javaspring-bootmavenopenapiopenapi-generator

Enum query param does not work - openapi-generator


I use openapi-generator-maven-plugin version 7.0.0 for OpenAPI swagger spec to Java code generation.

<plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>${openapi.generator.version}</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

I defined a query param as an Enum value

  parameters:
    - in: query
      name: status
      required: false
      example: scheduled, active
      schema:
        type: string
        enum: [scheduled, active]

but in the plugin-generated class, the property is not defined as an Enum

@Parameter(name = "status", in = ParameterIn.QUERY) @Valid @RequestParam(value = "status", required = false) String status

So, the schema doesn't stop sending any values for this parameter.

I followed the rules in the Swagger doc for Enum but suppose that's something plugin generation-specific

Is there any way to define a param as Enum type and allow the query param to accept only predefined values?


Solution

  • I tried on my own and I find this solution to your problem.
    First of all I defined the enum under the component/schemas section like:

    component:
      schemas:
        status:
          type: string
          enum: [scheduled, active]
          default: active
    

    Just insert the default attribute to set that value as the default one for your request.

    Then just add the reference in the path (do not insert the enum inside the {}) and complete the definition with all the responses you need:

    paths:
      /insertYourPathHere:
        get:
          parameters:
            - name: productCode
              in: query
              required: false
              schema:
                $ref: '#/components/schemas/status'
          responses: # add your api responses here
    

    Finally, insert your yaml inside the src/main/resources folder and run the application with goal: clean install
    All your classes will be created and you will have this:

    @Parameter(name = "status", description = "", schema = @Schema(description = "", allowableValues = { "scheduled", "active" }, defaultValue = "active")) @Valid @RequestParam(value = "status", required = false, defaultValue = "active") Status status
    

    One final consideration.
    If the parameter sent in the request will not match one of the value of your enum, an IllegalArgumentException exception will be raised. So only the defined value of your enum will be accepted.