Set List of Objects in Swagger API response
Asked Answered
L

3

18

I want to send a list of objects in the response of an API using Swagger.

@ApiResponse(code = 200, message = ApiResponseMessages.ITEM_FETCHED, 
response = "")

I have a class -

class Item{
   int id;
   String item_name;
}

I want a response like -

{
    {
       "id" : 0,
       "item_name" : ""
    }
    {
       "id" : 0,
       "item_name" : ""
    }
    {
       "id" : 0,
       "item_name" : ""
    }
}

How can i do this. Any help would be appreciated.

Lyndell answered 21/2, 2019 at 10:44 Comment(0)
P
30

You also can set a ApiReponse like this:

@ApiResponse(code = 200, message = ApiResponseMessages.ITEM_FETCHED,
             response = Item.class, responseContainer = "List"
            )

It's will return:

[
    {
       "id" : 0,
       "item_name" : ""
    },
    {
       "id" : 0,
       "item_name" : ""
    },
    {
       "id" : 0,
       "item_name" : ""
    }
]
Poorhouse answered 18/6, 2019 at 19:34 Comment(0)
M
16

For the new package: io.swagger.v3.oas.annotations.responses.ApiResponse

You need to do this (with @ArraySchema annotation):

@ApiResponse(responseCode = "200", description = "",
            content = {@Content(
                mediaType = "application/json",
                array = @ArraySchema(schema = @Schema(implementation = Bar.class))
            )}
)
Miele answered 7/4, 2021 at 14:30 Comment(1)
This should be the right answerDiffract
Z
7

You can use of responseContainer = "List" as below:

@ApiOperation(value = "retrieve items", response = Item.class, responseContainer = "List")
Zachary answered 12/6, 2020 at 18:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.