Swagger 中的 HEAD 方法没有 "Try it out" 按钮 UI

No "Try it out" button for HEAD method in Swagger UI

我有一个定义 HEAD 操作的 Swagger 规范:

head:
  description: show flight exist or not.

  parameters:
    - name: flight_no
      in: path
      type: string
      description: Flight_no
      required: true
  produces:
    - application/json
    - application/xml

  responses:
    200:
      description: success response
      schema:
        type: array
        items:
          $ref: '#/definitions/Data'
    '404':
      description: flight does not exist

在 Swagger UI v.2 中,此 HEAD 操作没有 "try it out" 按钮。如何为 HEAD 添加 "try it out"?

你可以试试 Swagger UI 3.0 – HEAD 在这个版本中默认有 "try it out"。

如果您使用 Swagger UI 2.0,默认情况下禁用 HEAD。您需要在 index.html:

中的 Swagger UI 初始化代码中的 supportedSubmitMethods 列表中显式启用它
window.swaggerUi = new SwaggerUi({
  url: url,
  dom_id: "swagger-ui-container",
  supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch', 'head'],
  //                                                                   ^
  // ------------------------------------------------------------------┘


顺便说一下,HEAD 响应中的 schema 并不是很有用,因为 HEAD 不应该 return 一个实际的 body – 只有 headers。您应该将 200 响应更改为:

responses:
  200:
    description: success response

加起来,在 java 中,您可以在 swagger 配置 class 中添加一个 bean 来做到这一点:

@Configuration
@EnableSwagger2
public class SwaggerConfig { 

    @Bean
    UiConfiguration uiConfig()
    {
      return new UiConfiguration( null, UiConfiguration.Constants.NO_SUBMIT_METHODS );
    }
}

基本上它会将 supportedSubmitMethods 放到 []

您需要将 DEFAULT_SUBMIT_METHODS 扩展 "head" 个值。

    @EnableSwagger2
    @Configuration
    public class SwaggerConfig  {

        @Bean
        UiConfiguration uiConfiguration() {
            return new UiConfiguration( null, new String[] {"get", "post", "put", "delete", "patch", "head"} );
        }
    }