7

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?

  • You know you can just use the default Springboot ResponseEntity and return a `ResponseEntity>`.... the `moreDataExists` seems more like an endpoint specific kinda variable – RobOhRob Mar 02 '20 at 16:37
  • If you want to change manually, you can use [discriminator](https://swagger.io/specification/#discriminatorObject) if there is something that distinguishes what response you return. You can check this [example](https://redocly.github.io/redoc/#operation/addPet) in Redoc to see how this is interpreted. Change the "petType" value and notice the change of fields. – l-lin Mar 02 '20 at 16:54

1 Answers1

1

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

brianbro
  • 4,141
  • 2
  • 24
  • 37