Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a header parameter in Swagger UI documentation with 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.

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.

like image 634
Julien Avatar asked Nov 25 '16 09:11

Julien


People also ask

How do I pass multiple headers in swagger?

You can pass multiple header params on a single request, just use unique names for them (key is used in the above example). To be clear, both headers are added to Access-Control-Allow-Headers, and both can be recived separatelly by server, the case is that i'm not able to send them together.

What is Springfox Swagger UI?

Springfox is a set of Java libraries, that has evolved from the swagger-springmvc project. It automates the generation of specifications for JSON APIs, implemented with the Spring framework. Also, it provides libraries to integrate the Swagger UI to interact with APIs.


1 Answers

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<*>{}
like image 159
Enoobong Avatar answered Sep 19 '22 16:09

Enoobong