8

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?

2
  • You know you can just use the default Springboot ResponseEntity and return a ResponseEntity<List<News>>.... the moreDataExists seems more like an endpoint specific kinda variable Commented Mar 2, 2020 at 16:37
  • If you want to change manually, you can use discriminator if there is something that distinguishes what response you return. You can check this example in Redoc to see how this is interpreted. Change the "petType" value and notice the change of fields. Commented Mar 2, 2020 at 16:54

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.