Using @ApiImplicitParams with Swagger 2

In the last post we saw how to use Swagger 2 with SpringFox and JAX-RS. Using annotations for methods usually pulls in all the parameters for that method. There may be certain instances where you may have to pass in extra header param for a method to work. Can we do that using Swagger 2 annotations?

How do we pass in header param without adding it as a method param?

Use the @ApiImplicitParam annotation to pass in header parameters as required.  For this use case we want to pass “Pragma” header  with a user selectable value as part of the request.

Advertisements

We are going to add to the same application we used in the previous post on swagger.

The following snippet of code shows the annotation that is used to set the header param.

@GET                //JAX-RS Annotation
@Path("/{name}")   //JAX-RS Annotation
@ApiOperation(            //Swagger Annotation
        value = "Say hello by entering your name",
        response = Hello.class)
@ApiResponses(value = {       //Swagger Annotation
        @ApiResponse(code = 200, message = "Resource found"),
        @ApiResponse(code = 404, message = "Resource not found")
})
@ApiImplicitParams({
   @ApiImplicitParam(name = "Pragma", required = true, value = "(Required) Title of the item.",
      paramType = "header", dataType = "String", allowableValues = "no-cache, no-store")
})
public Response sayHello(@ApiParam @PathParam("name") String name) {
    LOGGER.info("v1/hello/{} - {}", name, MediaType.APPLICATION_JSON);
    return this.buildResponse(name, MediaType.APPLICATION_JSON);
}

Now compile and build the application.

swagger 7

The Pragma header is now displayed in the UI. Click on the drop down and you can see the available options for this parameter

swagger 8

When request is submitted the request header is populated as shown below.

swagger 9

More documentation on @ApiImplicitParam can be found at http://docs.swagger.io/swagger-core/current/apidocs/io/swagger/annotations/ApiImplicitParam.html

We would look at more annotations in future posts.

Advertisements

Leave a Reply

Your email address will not be published. Required fields are marked *