How to add an example in @ApiResponse with Swagger?
Asked Answered
T

4

9

I would like to add an example with Swagger in my method, I have tried a few things, but they didn't work.

I have my Interface, where I define the method:

@Api(value = "test API")
@RequestMapping("/api/v1/product")
public interface TestController {

    @ApiOperation(
            value = "Service that return a Product",
            notes = "This service returns a Product by the ID",
            nickname = "getProductById",
            response = ProductResponse.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "The request has succeeded.", response = ProductResponse.class),
            @ApiResponse(code = 500, message = "Internal server error.", response = ProductResponse.class) })
    @GetMapping(
            value = "/productById",
            produces = { "application/json" }
    )
    ResponseEntity<ProductResponse> getProductById(@RequestParam(value = "productId", required = true) String productId);

The ProductResponse class is the following:

@Getter
@Setter
@AllArgsConstructor
public class ProductResponse {

    private Product product;
    private CustomException customException;

}

The Product class is the following:

@Getter
@Setter
@AllArgsConstructor
public class Product {

    @JsonProperty("id")
    private String id;

    @JsonProperty("productName")
    private String productName;

    @JsonProperty("productDescription")
    private String productDescription;

    @JsonProperty("unitPrice")
    private Double unitPrice;

And the CustomException class is the following:

@Getter
public class CustomException {

    private final String message;
    private final String errorCode;
    private final String errorType;
    private final Exception exceptionDetail;
    
    public CustomException(String message, String errorCode, String errorType, Exception exceptionDetail) {
        this.message = message;
        this.errorCode = errorCode;
        this.errorType = errorType;
        this.exceptionDetail = exceptionDetail;
    }

When the response is 200, the response is like:

{
  "product": {
    "id": "12345",
    "productName": "Product name",
    "productDescription": "This is a description",
    "unitPrice": 3.25
  },
  "customException": null
}

But when the response is 500, the response is like:

{
  "product": "null,",
  "customException": {
    "message": "/ by zero",
    "errorCode": "500",
    "errorType": "Internal server error",
    "exceptionDetail": null,
    "cause": null,
    "stackTrace": [
      {
        "classLoaderName": "app",
        "moduleName": null,
        "moduleVersion": null,
        "methodName": "getProductById",
        "fileName": "TestControllerImpl.java",
        "lineNumber": 33,
        "className": "com.myproject.testmicroservice.controller.impl.TestControllerImpl",
        "nativeMethod": false
      }
    ]
  }
}

How can I add a custom example in the @ApiResponse annotation?

Trochelminth answered 13/7, 2022 at 11:15 Comment(0)
H
6

You are probably missing the @Operation annotation, where inside you put the @ApiResponse.

Example:

  import io.swagger.v3.oas.annotations.responses.ApiResponse;
  import io.swagger.v3.oas.annotations.Operation;

  @Operation(responses = {
      @ApiResponse(responseCode = "200", content = @Content(examples = {
          @ExampleObject(name = "getUserAttribute",
                         summary = "Retrieves a User's attributes.",
                         description = "Retrieves a User's attributes.",
                         value = "[{\"value\": [\"area1\", \"area2\", \"area3\"], \"key\":\"GENERAL_AREAS\"}, {\"value\":\"933933933\", \"key\":\"FONyE\"}]")
      }, mediaType = MediaType.APPLICATION_JSON_VALUE))})
  public ResponseEntity<List<UserPreferenceDto>> getUserPreferenceByCode(
      @Pattern(regexp = "\\w+") @PathVariable String userCode, @Parameter(hidden = true) Pageable pageable) {

     ...
  }
Hypersensitize answered 18/7, 2022 at 8:6 Comment(0)
D
6

Good evening hope you are doing well. In the case you are describing, I would do something like this

@ApiResponses(value = { 
  @ApiResponse(responseCode = "200", description = "Found the book", 
    content = { @Content(mediaType = "application/json", 
      schema = @Schema(implementation = Book.class)) }),
  @ApiResponse(responseCode = "400", description = "Invalid id supplied", 
    content = @Content),

the approach described is explained here. I think that paragraph 9. Generate Documentation Using @Operation and @ApiResponses is of particular interest in your case. I hope this helps, Have a good night

Demo answered 23/7, 2022 at 0:58 Comment(1)
This response it good for the situation where we do not want to give a response for that HTTP 400 response, but in the question what is asked is to give a different sample for HTTP 400 as for HTTP 200 responses.Verjuice
F
0

You can try something like this. In your controller you already have @ApiResponses annotation. What you need to do is add @ApiModel to your Product class and then add

@ApiModelProperty(notes = "Your comments", required = true, example = "example value")

to members of your Product class i.e. ProductResponse and CustomException. One thing that you will need to verify is whether @ApiModelProperty can be set on custom objects like ProductResponse and CustomException. If not you will need to set @ApiModelProperty 1 level deep.

As shown in article, the examples are auto populated from model property to response.

PS: As of now, I do not have setup of a swagger project so can only help you theoretically.

Foyer answered 19/7, 2022 at 11:7 Comment(0)
P
0

may be this late answer but incase any one need it, you can add the requestBody description along with content type within @Operation

@io.swagger.v3.oas.annotations.Operation(summary = "", description = "",
        requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE)))
Pierette answered 19/1, 2023 at 4:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.