Home > Mobile >  java springdoc @ApiResponses how to define a List as return object using
java springdoc @ApiResponses how to define a List as return object using

Time:11-02

I'm using SpringBoot with the following dependency

    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>1.5.12</version>
    </dependency>

The controller class (@RestController) has one entry point (@GetMapping), and this entry point should return a List of the object : MyClass.java. I added Swagger annotations above the method in order to create API documentation via a swagger UI page.

The swagger documentation should indicate that the return object is of type

List< MyClass>

But how should I do that ? If I do

"@Schema(implementation = List< MyClass >.class)"

there is a compile error.

Swagger annotations:

@Operation(....)
@ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "successful operation",
                content = { @Content(mediaType = "application/json",
                        schema = @Schema(implementation = ????)) }),
        @ApiResponse(...),
        @ApiResponse(...)

@GetMapping(value = "/aaa", produces = MediaType.APPLICATION_JSON_VALUE)
public List<MyClass> getAaa(...)
{
    return ...
}

CodePudding user response:

You need to use an ArraySchema annotation for this and assign it to the array attribute instead of the schema attribute of the @Content annotation. You don't need to specify List.class only its type parameter MyClass.class.

    @Operation(
            summary = "Get a list of users",
            description = "Get a list of users registered in the system",
            responses = {@ApiResponse(
                    responseCode = "200",
                    description = "The response for the user request",
                    content = {
                            @Content(
                                    mediaType = "application/json",
                                    array = @ArraySchema(schema = @Schema(implementation = User.class))
                            )
                    })
            }
    )
    @GET
    @SecurityRequirement(name = "JWT")
    @Path("/user")
    public List<User> getUsers() {
        return null;
    }
  • Related