KTunge
KTunge

Reputation: 11

How to add custom ApiResponse in Java jersey Swagger UI

I am using Swagger UI framework for documenting the APIs. One of the API I have is

@GET
@Path("/books/count")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get total book count in system")
@ApiResponses(value=@ApiResponse(code = 200, message = "Successful operation", response=**need custom response here**))
public Response getBookCount(){
int count = bookService.getCount();
JSONObject jsonObj = new JSONObject();
jsonObj.put("Count", count);

return Response.status(Status.OK).entity(jsonObj.toString()).build();
}

The above API returns a single Json object having 'Count' field. So, is it possible to have a Swagger-UI response something like -

@ApiResponses(value=@ApiResponse(code = 200, message = "Successful operation", response={"Count" : "int"}))

I do not want to write a Class here having int field Count because I have such more APIs having custom response of one or two fields only and I do not wish to write separate class for each custom response.

Please let me know if further input is required for this question.

Many thanks in advance.

Upvotes: 1

Views: 1528

Answers (1)

Ashish Karn
Ashish Karn

Reputation: 1143

You can do that by using a generic type or object. For me object makes more sense.

Please try with the below swagger.yml and code that will be generated from this will be of the generic type.

openapi: 3.0.1
info:
  title: Swagger Bookstore
  description: 'This is a sample server Bookstore server.'
  version: 1.0.0
servers:
- url: http://bookstore.swagger.io/v2
tags:
- name: book
  description: Everything about your Books
paths:
  /books/count:
    get:
      tags:
      - book
      summary: Get Books count
      description: Fetch total book count
      operationId: getBookCount
      responses:
        200:
          description: successful operation
          content:
            application/json:
              schema:
               $ref: '#/components/schemas/ApiResponse'
        400:
          description: Invalid response
          content: {}
components:
  schemas:
    ApiResponse:
      type: object
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
        response: 
          type: object

You can see ApiResponse has one field name response that is generic type as an object. Which can hold any type that you specify?

response: 
   type: object

and the code generated from this will be something like:

@ApiResponses(value=@ApiResponse(code = 200, message = "Successful operation", response={}))

So, here response={} can hold anything that you want. For example response={count=5} or any type that you specify.

Please try this will solve your issue.

Upvotes: 0

Related Questions