使用Springfox在Swagger UI文档中添加头参数

时间:2016-11-25 09:22:23

标签: spring swagger-ui springfox

我想在我的休息服务的自动生成的swagger ui文档中添加标题参数字段。我使用Spring和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);
}

如您所见,我已经有 body 类型参数。我只想添加一个标题类型。

3 个答案:

答案 0 :(得分:6)

我刚刚添加了@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;

您还可以使用此处描述的解决方案在文档中的每个服务上添加全局标头:Spring + Springfox + Header Parameters

答案 1 :(得分:5)

我更喜欢在@ApiImplicitParam之后使用@RequestMapping而不是作为函数参数,因为通常您可以在过滤器中处理标头(例如,身份验证),并且不需要该方法中的值。

除了在方法Swagger auto中是否需要它们外,它还提供@HeaderParam字段

当某些调用需要标题而其他不需要时,这种样式还提高了可读性和灵活性。

示例

@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<*>{}

如果您的端点的全部或大部分都需要标头,则我会按照here

进行配置

如果必须声明多个标头参数,则需要使用@ApiImplicitParams批注:

@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<*>{}

答案 2 :(得分:1)

如果您有更多的标头参数,那么每个API都会有那么多的@RequestHeader

为避免这种情况,您的API看起来很简单,您可以使用HeaderInterceptor来捕获标头信息。

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;
   }

 }

您的API将如下所示,带有@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  {
  ....
 }

你的Swagger仍然应该描述API的所有标题,因为你可以在swagger Docket,SwaggerConfig中添加参数 请注意ignoredParameterTypes,我们提到忽略HeaderVo,因为它是应用程序的内部。 swagger并不需要表明

@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);

   }