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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40801442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:16:08  来源:igfitidea点击:

Add a header parameter in Swagger UI documentation with Springfox

springswagger-uispringfox

提问by Julien

I want to add a header parameter field in the auto-generated swagger ui documentation of my rest service. I use Spring and 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);
}

As you see I have already a bodytype parameter. I just want to add a headertype one.

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

回答by Enoobong

I prefer to use @ApiImplicitParamafter my @RequestMappingrather 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.

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

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

此外,如果您在 Swagger 自动提供字段的方法中需要它们 @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:

如果必须声明多个头参数,则需要使用@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<*>{}

回答by Julien

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

我刚刚补充说@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;)

( 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

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

回答by sujith kasthoori

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

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

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

为了避免这种情况并且您的 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;
   }

 }

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

您的 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  {
  ....
 }

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

您的 Swagger 仍然应该描述 API 的所有标头,为此您可以在 swagger Docket、SwaggerConfig 中添加参数 请注意忽略的参数类型,我们提到忽略 HeaderVo,因为这是应用程序内部的。招摇不需要表明

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

   }