Mayank Bist
Mayank Bist

Reputation: 181

How to write @ApiResponse which may return a Class or a List of that class using OpenAPI 3 Swagger in Spring Boot

As written in documentation we can use anyOf with @Schema if we want to define multiple responses.

    @ApiResponse(responseCode = "201", description = "OK",
        content = @Content(schema = @Schema(anyOf = {Product.class, Activity.class})))

My controller returns either a Product or a List<Product>. I would like to specify this in my OpenAPI 3 documentation. I would like to know if it's possible. If Yes, then how? If No, then is there any workaround?

I don't only want to specify List.class. I want to specify List<Product>.

P.S.:- Searching on Google didn't get me any results that I can use.

Upvotes: 3

Views: 7110

Answers (1)

Marcel Herhold
Marcel Herhold

Reputation: 166

Ok, thats a tough one.

Basically if you really want to return a List of Objects or one Object, then you can create a basic interface like this

public interface Response {
}

And then you can create your Object, which implements the response

public class Hello implements Response {
    private String message;

    public Hello(String message) {
        this.message = message;
    }

    public String getMessage() {
        return this.message;
    }
}

Finally we can create the List of our Object. For that we need to create a class, which extends the ArrayList and implements our Interface

public class HelloList extends ArrayList<Hello> implements Response {
}

After that we can just set our schema as implementation

@ApiResponse(responseCode = "200", description = "hello world", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Response.class)))

On the Clientside you need to check the instance of the Response-Object, so that you can parse either the Object or the List

Response response = someCall();
if (response instanceof Hello) {
    System.out.println(processHello((Hello) response);
}
if (response instanceof HelloList) {
    System.out.println(processHelloList((HelloList) response);
}

This example works, but its very very complex und confusing. A better way to design your api, would be to return just the list. I don't see the benefit to seperate one object or the list of it.

Upvotes: 4

Related Questions