Search code examples
javaspringswagger-codegen

How to use enum as parameter in spring controller that extends interface generated by swagger-codegen with "spring" language


Let's say i have a parameter defined with enum schema:

paths:
  /echo:
    get:
      parameters:
      - name: someEnum
        in: query
        required: true
        schema:
          type: string
          enum: [A, B, C]
      responses:
        200:
          description: Success
          content:
            text/plain:
              schema:
                type: string

Swagger codegen generates the following Java inteface for spring language:

    @ApiOperation(value = "", nickname = "echoGet", notes = "", response = String.class, tags={  })
    @ApiResponses(value = { 
        @ApiResponse(code = 200, message = "Success", response = String.class) })
    @RequestMapping(value = "/echo",
        produces = { "text/plain" }, 
        method = RequestMethod.GET)
    default ResponseEntity<String> echoGet(@NotNull @ApiParam(value = "", required = true, allowableValues = "A, B, C") @Valid @RequestParam(value = "someEnum", required = true) String someEnum) {
        if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) {
        } else {
            log.warn("ObjectMapper or HttpServletRequest not configured in default EchoApi interface so no example is generated");
        }
        return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
    }

Type of someEnum in generated interface is String. How to replace it with Java enum with "A", "B", "C" values?


Solution

  • add a named type to schema and use it:

    paths:
      /echo:
        get:
          parameters:
            - name: someEnum
              in: query
              required: true
              schema:
                $ref: '#/components/schemas/MyEnum'
          responses:
            200:
              description: Success
              content:
                text/plain:
                  schema:
                    type: string
    components:
      schemas:
        MyEnum:
          type: string
          enum: [A,B,C]