Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 633
incompletablefuture Avatar asked Nov 07 '22 09:11

incompletablefuture


1 Answers

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

like image 190
brianbro Avatar answered Nov 12 '22 15:11

brianbro