incompletablefuture
incompletablefuture

Reputation: 124

How to make OpenAPI specification using generics in Java

I use generics in my controller. For instance, from some end-points I return Response<News> and Response<Tag>.

Well, Swagger generates this part of yaml automatically

responses:
        200:
          description: default response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ResponseNews'

and

responses:
        200:
          description: default response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ResponseTags'

This is my Response entity in Java.

public class Response<T> {
    private List<T> data;
    private Boolean moreDataExists;
}

This is how Swagger generates components.

ResponseNews:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/News'
        moreDataExists:
          type: boolean

ResponseTags:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/Tags'
        moreDataExists:
          type: boolean

Well, it's almost duplicated code. And I want to avoid it, and use in description of my end-points only Response, and show my users explicitly that I use generics.

Something like that:

responses:
        200:
          description: default response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Response'
                  contains: 
                    $ref: '#/components/schemas/News'

I am ready to do it without even Swagger, just manually. Is there a way to do it, maybe using inheritance or polymorphism?

Upvotes: 7

Views: 8081

Answers (1)

brianbro
brianbro

Reputation: 4769

You can adapt the response by using @ApiResponse swagger annotation where you can pass the schema of any custom object you want.

Upvotes: 1

Related Questions