Set List of Objects in Swagger API response

14,041

Solution 1

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" : ""
    }
]

Solution 2

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))
            )}
)

Solution 3

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

@ApiOperation(value = "retrieve items", response = Item.class, responseContainer = "List")
Share:
14,041
Mohd. Samar
Author by

Mohd. Samar

Updated on June 17, 2022

Comments

  • Mohd. Samar
    Mohd. Samar almost 2 years

    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.

  • jics
    jics about 2 years
    This should be the right answer