Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set List of Objects in Swagger API response

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.

like image 743
Mohd. Samar Avatar asked Feb 21 '19 10:02

Mohd. Samar


People also ask

How do I document a spring REST API using Swagger?

First, we'll start with some explanations of the OpenAPI Specification and Swagger API Response. Then, we'll implement a simple example using Spring Boot to document a spring REST API using OpenApi 3.0. After that, we'll use Swagger's annotations to set the response body to deliver a list of objects. 2. Implementation

What is the API in Swagger?

The Swagger representation of the API is comprised of two file types: The Resource Listing - This is the root document that contains general API information and lists the resources. Each resource has its own URL that defines the API operations on it.

How does Swagger work with deliveryoptionssearchmodel?

Or, if your method returned a larger object, composed of DeliveryOptionsSearchModel and few others, then Swagger would use this provider for one part of the response example, and other provider (s) (or default rough examples) for all other parts of the large object.

What is Swagger 1 1?

1. Introduction Swagger™ is a project used to describe and document RESTful APIs. The Swagger specification defines a set of files required to describe such an API. These files can then be used by the Swagger-UI project to display the API and Swagger-Codegen to generate clients in various languages.


2 Answers

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))
            )}
)
like image 122
rios0rios0 Avatar answered Oct 15 '22 21:10

rios0rios0


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" : ""
    }
]
like image 32
Daniel Asanome Avatar answered Oct 15 '22 19:10

Daniel Asanome