Search code examples
swaggerswagger-2.0springfoxspringfox-boot-starter

Swagger @ApiResponse should show List of ErrorObject i.e List<MyErrorObject> ? How is this possible?


The swagger version I am using is as below and My question is related to the @ApiResponse annotation.

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.9.2</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.9.2</version>
  <scope>compile</scope>
</dependency>

When a user accesses my api and if the user provides invalid details/input, my application is returning a list of errors in the users input. Each error is captured in a an error object

MyErrorObject 
{
  Date date;
  String errorCode;
  String errorMessage;
  //getters //setters
}

-so my application response incase of invalid user input will look something like below -

[
    {
        "date": "2021-09-22",
        "errorCode": "6548",
        "errorMessage": "there are no booking available in selected city"
    },
    {
        "date": "2021-09-22",
        "errorCode": "2649",
        "errorMessage": "your age does not allow you to travel to this location"
    }
]

---Now back to my question - using swagger @ApiResponse annotation, I want the api users to know the response format. So, I tried below

@ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST,
          message = ErrorConstants.NotAllowed, response=List<MyErrorObject>.class)

But above did not work, I am seeing below compile time error -

Syntax error, insert "}" to complete MemberValueArrayInitializer

I tried - other combinations too like below but no luck -

@ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST,
          message = ErrorConstants.NotAllowed, response=List<MyErrorObject.class>)

So, what is the right way to represent a list of errors using @ApiResponse annotation?? So the error response on swagger doc looks something like below -

[
 {
  "date": "Date",
  "errorCode": "string",
  "errorMessage": "string"
 }
]

Solution

  • From the definition of the ApiResponse.class, it's evident they have a responseContianer attribute that you can set to achieve the desired result.

    @ApiResponse(
        code = HttpURLConnection.HTTP_BAD_REQUEST,
        message = ErrorConstants.NotAllowed, 
        response = MyErrorObject.class,
        responseContainer = "List"
    )