Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Swagger @ApiResponses annotation in Kotlin?

How to convert the following Swagger annotations from Java to Kotlin?

 @ApiResponses(value = { @ApiResponse(code = 200, message = "Given admin user found"),
            @ApiResponse(code = 404, message = "..."),
            @ApiResponse(code = 500, message = "..."),
            @ApiResponse(code = 400, message = "..."),
            @ApiResponse(code = 412, message = "...") })

This does not works:

@ApiResponses(value = listOf( 
        ApiResponse(code = 200, message = "..."),
        ApiResponse(code = 404, message = "..."),
        ApiResponse(code = 500, message = "..."),
        ApiResponse(code = 400, message = "..."),
        ApiResponse(code = 412, message = "...") ))

The error is:

Type inference failed. Expected type mismatch: inferred type is List but ApiResponse was expected

It works when I use just one @ApiResponse instead of listOf(), but I have to define more @ApiResponse(s).

I use Swagger 2.5.0

like image 691
Frido Avatar asked Jul 28 '17 12:07

Frido


People also ask

What is the use of @ApiResponse?

We can use the @ApiResponse annotation to describe the concrete possible response of an operation. While the @ApiOperation annotation describes an operation and a general return type, the @ApiResponse annotation describes the rest of the possible return codes.

What is @ApiResponse annotation in spring boot?

@ApiResponses- This annotation is used to describe the expected responses for the REST API. The @ApiResponse describes a concrete possible response. It cannot be used directly on the method and needs to be included in the array value of @ApiResponses (whether there's one response or more).

What is @schema annotation in swagger?

The annotation may be used to define a Schema for a set of elements of the OpenAPI spec, and/or to define additional properties for the schema. It is applicable e.g. to parameters, schema classes (aka "models"), properties of such models, request and response content, header.


1 Answers

As stated in the Kotlin Language Reference:

If the value argument [of an Annotation] in Java has an array type, it becomes a vararg parameter in Kotlin

So, to make your example work, you need to put it like so:

@ApiResponses(
    ApiResponse(code = 200, message = "..."),
    ApiResponse(code = 404, message = "..."),
    ApiResponse(code = 500, message = "..."),
    ApiResponse(code = 400, message = "..."),
    ApiResponse(code = 412, message = "...")
)
like image 72
Robin Avatar answered Sep 19 '22 08:09

Robin