Add a header parameter in Swagger UI documentation with Springfox

swagger-ui add authorization header spring boot
swagger-ui add authorization header java
swagger header parameter annotation
swagger request headers example
swagger add header
java swagger add custom header
springfox-swagger-ui customization
swagger add static header

I want to add a header parameter field in the auto-generated swagger ui documentation of my rest service. I use Spring and Springfox.

public ResponseEntity<User> saveNewUser(
        @ApiParam(value = "the user to create", required = true) @RequestBody User user) throws RestServiceException {

    userService.save(user);
    return new ResponseEntity<User>(user, HttpStatus.OK);
}

As you see I have already a body type parameter. I just want to add a header type one.

I prefer to use @ApiImplicitParam after my @RequestMapping rather than as function parameters because generally you might process your headers in a filter (eg authentication) and you are not needing the values in that method.

Besides if you need them in the method Swagger auto provides the field for a @HeaderParam

This style also Improves readability and flexibility when some calls need headers and other don't.

Example

@PostMapping
@ApiImplicitParam(name = "Authorization", value = "Access Token", required = true, allowEmptyValue = false, paramType = "header", dataTypeClass = String::class, example = "Bearer access_token")
fun addJob(jobRequest: Job): ResponseEntity<*>{}

If all or most for your endpoints need header that I'll rather configure it as seen here

If you have to declare several header params, you need to use the @ApiImplicitParams annotation:

@PostMapping
@ApiImplicitParams(
  @ApiImplicitParam(name = "Authorization", value = "Access Token", required = true, allowEmptyValue = false, paramType = "header", dataTypeClass = String::class, example = "Bearer access_token"),
  @ApiImplicitParam(name = "X-Custom-Header", value = "A Custom Header", required = true, allowEmptyValue = false, paramType = "header", dataTypeClass = String::class, example = "my header example")
)
fun addJob(jobRequest: Job): ResponseEntity<*>{}

Spring + Springfox + Header Parameters, Adding a @HeaderParam method parameter as above springfox picks it up and when I look at the swagger-ui it has a field for the header. This is  @Saveen I'm not sure If I understand what you mean, but this code will add the same parameter to all the APIs you have. if doesn't cancel your function parameters, it only adds this one with the others associated with each API function.

I just added @RequestHeader(value="myHeader") String headerStr :

public ResponseEntity<User> saveNewUser(
        @RequestHeader(value="myHeader") String headerStr,
        @ApiParam(value = "the user to create", required = true) @RequestBody User user) throws RestServiceException {

    userService.save(user);
    return new ResponseEntity<User>(user, HttpStatus.OK);
}

(import org.springframework.web.bind.annotation.RequestHeader;)

You can also add a global header on every service in your documentation with the solution described here : Spring + Springfox + Header Parameters

how to set request headers on Swagger UI · Issue #1566 · swagger , I am trying to setup SwaggerUI for exposing my APIs. I require to add authorization token in the request headers while making the API calls, have been copied from // http://springfox.github.io/springfox/docs/current/#getting-​started // in an https://github.com/swagger-api/swagger-ui#header-parameters​  In ASP.net WebApi, the simplest way to pass-in a header on Swagger UI is to implement the Apply() method on the IOperationFilter interface. Add this to your project: In SwaggerConfig.cs, register the filter from above using c.OperationFilter<>(): Hi thanks for sharing this, it's just what i needed.

If you are having more header parameters, then every API will have that many @RequestHeader

To avoid this and your API looks simple you can use HeaderInterceptor to capture the header information.

In preHandle() ,  you need to extract the headerInfo in to a an Object and set it as RequestAttribute

  public class MyHeaderInterceptor extends HandlerInterceptorAdapter {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception { 

    HeaderVo headerVo = HeaderVo.createReqHeaderinput(
            request.getHeader("authorization"),
            request.getHeader("contentType"),                
            request.getHeader("myHeaderParam0"),
            request.getHeader("myHeaderParam1"), 
            request.getHeader("myHeaderParam3"),
            request.getHeader("myHeaderParam4"),
            request.getHeader("myHeaderParam5")

            );

     // You can do any validation of any headerInfo here.
     validateHeader(headerVo);

     request.setAttribute("headerName", headerVo);
     return true;
   }

 }

Your API will looks like the below with a @RequestAttribute("headerName")

public @ResponseBody
ResponseEntity<MyResponse> getSomeApi(
        //Headers common for all the API's       

        @RequestAttribute("headerName") HeaderVo header ,
        @ApiParam(value = "otherAPiParam", required = true, defaultValue = "") 
        @PathVariable(value = "otherAPiParam") String otherAPiParam,
        @ApiParam(value = "otherAPiParam1", required = true, defaultValue = "") 
        @RequestParam(value = "otherAPiParam1") String otherAPiParam1,
        @ApiParam(value = "otherAPiParam2, required = true, defaultValue = "")
        @RequestParam(value = "otherAPiParam2") String otherAPiParam2
     ) throws MyExcp  {
  ....
 }

Your Swagger still should describes all headers of the API, for that you can add parameters in swagger Docket, SwaggerConfig Please note ignoredParameterTypes, we mentioned to ignore HeaderVo, because that is internal to the application. swagger doesnt require to show that

@Bean
public Docket postsApi() {

    //Adding Header
    ParameterBuilder aParameterBuilder = new ParameterBuilder();
    List<Parameter> aParameters = new ArrayList<Parameter>();

    aParameters.clear();

    aParameterBuilder.name("myHeaderParam0").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
    aParameters.add(aParameterBuilder.build());
    aParameterBuilder.name("myHeaderParam1").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
    aParameters.add(aParameterBuilder.build());
   ....
   ....

    return new Docket(DocumentationType.SWAGGER_2).groupName("public-api")
            .apiInfo(apiInfo()).select().paths(postPaths()).build().ignoredParameterTypes(HeaderVo.class).globalOperationParameters(aParameters);

   }

Spring Swagger add static header to all rest service, to add a header parameter field in the auto-generated swagger ui documentation of my rest service. I use Spring and Springfox. public ResponseEntity<User>  Springfox supports both version 1.2 and version 2.0 of the Swagger specification. Where possible, the Swagger 2.0 specification is preferable. The swagger-core annotations, as provided by swagger-core, are typically used to decorate the java source code of an API which is bing 'swaggered'.

Springfox Reference Documentation, To update the docs for an existing release pass the updateMode switch module which produces Swagger 2.0 API documentation. rule builder that substitutes a generic type with one type parameter with the type parameter. And configure the Docket to be secured via the AUTHORIZATION header:. Replace a String parameter documentation with the corresponding full type model? ("io.springfox:springfox-swagger-ui:${springfoxVersion}") to set custom

Set Request Headers in Swagger-UI – chouhans, facing a issue with setting Global Request headers to Springfox's Swagger-UI at https://springfox.github.io/springfox/docs/current/#quick-start-guides passAs - you can pass as header or query parameter */ // For version  To get the Authorization header value(JWT), user first needs to login. The /login is provided by Spring Security. Once user successfully logs in, Authorization header will be returned. So my Swagger UI Documentation needs to document the /login URL which is provided by Spring Security.

Documenting Spring Boot REST API with Swagger and SpringFox , I want to add a header parameter field in the auto-generated swagger ui documentation of my rest service. I use Spring and Springfox. In a similar way, you can define custom response headers. Header parameter can be primitives, arrays and objects. Arrays and objects are serialized using the simple style. For more information, see Parameter Serialization. Note: Header parameters named Accept, Content-Type and Authorization are not allowed. To describe these headers, use the corresponding OpenAPI keywords: