【问题标题】:How can I set a description and an example in Swagger with Swagger annotations?如何使用 Swagger 注释在 Swagger 中设置描述和示例?
【发布时间】:2017-10-05 11:37:21
【问题描述】:

我正在使用 Spring boot 创建一个 REST Api,并使用 swagger codegen 在控制器中自动生成 swagger 文档。但是,我无法在 POST 请求中为 String 类型的参数设置描述和示例。这是mi代码:

import io.swagger.annotations.*;

@Api(value = "transaction", tags = {"transaction"})
@FunctionalInterface
public interface ITransactionsApi {
    @ApiOperation(value = "Places a new transaction on the system.", notes = "Creates a new transaction in the system. See the schema of the Transaction parameter for more information ", tags={ "transaction", })
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "Another transaction with the same messageId already exists in the system. No transaction was created."),
        @ApiResponse(code = 201, message = "The transaction has been correctly created in the system"),
        @ApiResponse(code = 400, message = "The transaction schema is invalid and therefore the transaction has not been created.", response = String.class),
        @ApiResponse(code = 415, message = "The content type is unsupported"),
        @ApiResponse(code = 500, message = "An unexpected error has occurred. The error has been logged and is being investigated.") })

    @RequestMapping(value = "/transaction",
        produces = { "text/plain" },
        consumes = { "application/json" },
        method = RequestMethod.POST)
    ResponseEntity<Void> createTransaction(
        @ApiParam(
            value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required." ,
            example = "{foo: whatever, bar: whatever2}")
        @Valid @RequestBody String kambiTransaction) throws InvalidTransactionException;
}

@ApiParam 的 example 属性是我手动插入的,因为 codegen 忽略了 yaml 的那部分(这是另一个问题:为什么编辑器忽略了 example 部分?)。 这是yaml的一部分:

paths:
  /transaction:
    post:
      tags:
        - transaction
      summary: Place a new transaction on the system.
      description: >
        Creates a new transaction in the system. See the schema of the Transaction parameter
        for more information
      operationId: createTransaction
      parameters:
        - $ref: '#/parameters/transaction'
      consumes:
        - application/json
      produces:
        - text/plain
      responses:
        '200':
          description: Another transaction with the same messageId already exists in the system. No transaction was created.
        '201':
          description: The transaction has been correctly created in the system
        '400':
          description: The transaction schema is invalid and therefore the transaction has not been created.
          schema:
            type: string
            description: error message explaining why the request is a bad request.
        '415':
          description: The content type is unsupported
        '500':
          $ref: '#/responses/Standard500ErrorResponse'

parameters:
  transaction:
    name: kambiTransaction
    in: body
    required: true
    description: A JSON value representing a kambi transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required.
    schema:
      type: string
      example:
        {
          foo*: whatever,
          bar: whatever2
        }

最后,这就是 swagger 所展示的:

最后,build.gradle中用到的依赖如下:

compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'

所以,问题是: 有谁知道我如何使用 swagger 注释来设置 body 参数的描述和示例?

编辑

我已经使用@ApiImplicitParam 而不是@ApiParam 来更改描述,但仍然缺少示例:

@ApiImplicitParams({
    @ApiImplicitParam(
        name = "kambiTransaction",
        value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with * means that they are required. See the schema of KambiTransaction for more information.",
        required = true,
        dataType = "String",
        paramType = "body",
        examples = @Example(value = {@ExampleProperty(mediaType = "application/json", value = "{foo: whatever, bar: whatever2}")}))})

【问题讨论】:

  • 在您的示例中,您说kambiTransaction 的类型为String,但您的方法使用application/json。那就是你想发送一个用 JSON 包裹的纯文本字符串(包含 JSON - 如示例值所示)?为什么不为kambiTransaction 创建一个域类。 Swagger 会自动将类的结构打印为 JSON 示例。
  • 我会支持@dpr。正确的方法是构建一个模型类并在类上使用注释ApiModel,在字段上使用ApiModelProperty。 ApiModelProperty 接受值和示例参数。

标签: java spring swagger swagger-codegen


【解决方案1】:

我在为 body 对象生成示例时遇到了类似的问题 - 注释 @Example@ExampleProperty 在 swagger 1.5.x 中无缘无故地不起作用。 (我用的是 1.5.16)

我目前的解决方案是:
非实体对象使用@ApiParam(example="..."),例如:

public void post(@PathParam("userId") @ApiParam(value = "userId", example = "4100003") Integer userId) {}

body 对象创建新类并使用 @ApiModelProperty(value = " ", example = " ") 注释字段,例如:

@ApiModel(subTypes = {BalanceUpdate.class, UserMessage.class})
class PushRequest {
    @ApiModelProperty(value = "status", example = "push")
    private final String status;;
}

【讨论】:

    【解决方案2】:

    实际上,@ApiParam 注释的 example 属性的 java 文档指出,它专门用于非正文参数。其中examples 属性可用于正文参数。

    我测试了这个注解

    @ApiParam(
      value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required.",
      examples = @Example(value = 
        @ExampleProperty(
          mediaType = MediaType.APPLICATION_JSON,
          value = "{foo: whatever, bar: whatever2}"
        )
      )
    )
    

    这导致为相应的方法生成以下招摇:

    /transaction:
      post:
      ...
        parameters:
        ...
        - in: "body"
          name: "body"
          description: "A JSON value representing a transaction. An example of the expected\
            \ schema can be found down here. The fields marked with an * means that\
            \ they are required."
          required: false
          schema:
            type: "string"  
          x-examples:
            application/json: "{foo: whatever, bar: whatever2}"
    

    但是,swagger-ui 似乎没有接受这个值。我尝试了 2.2.10 版本和最新的 3.17.4 版本,但两个版本都没有使用 swagger 的 x-examples 属性。

    code of swagger-ui 中有一些对x-example(用于非正文参数的)的引用,但与x-examples 不匹配。也就是说,目前 swagger-ui 似乎不支持这一点。

    如果您确实需要显示此示例值,那么目前最好的选择似乎是更改方法的签名并为 body 参数使用专用的域类型。如 cmets 中所述,swagger 会自动拾取域类型的结构并在 swagger-ui 中打印一些不错的信息:

    【讨论】:

    • 有什么办法可以将资源文件内容添加到@ExampleObject?我正在尝试使用refresources file 添加@ExampleObject,但由于某种原因它无法正常工作。我已经发布了我的问题:stackoverflow.com/q/71616547/7584240
    【解决方案3】:

    您尝试过以下方法吗?

    @ApiModelProperty(
        value = "A JSON value representing a transaction. An example of the expected schema can be found down here. The fields marked with an * means that they are required.",
        example = "{foo: whatever, bar: whatever2}")
    

    祝你有美好的一天

    【讨论】:

    • 完美运行,但仅适用于原始类型。
    • 有什么办法可以将资源文件内容添加到@ExampleObject?我正在尝试使用refresources file 添加@ExampleObject,但由于某种原因它不起作用。我已经发布了我的问题:stackoverflow.com/q/71616547/7584240
    【解决方案4】:

    Swagger.v3 Kotlin/Micronaut 示例:

    @Post("/get-list")
    fun getList(
            @RequestBody(description = "Get list of ...",
                    content = [Content(
                            mediaType = "application/json",
                            schema = Schema(implementation = RequestDTO::class),
                            examples = [ExampleObject(value = """
                                {
                                    "pagination": {
                                        "page": 0,
                                        "perPage": 10
                                    },
                                    "filter": {
                                        "property_1": "string",
                                        "property_2": "string"
                                    },
                                    "sort": {
                                        "field": "property_1",
                                        "order": "DESC"
                                    }
                                }
                            """)]
                    )]) @Body request: RequestDTO): Response<SomeDTO> { ... }
    

    【讨论】:

      【解决方案5】:

      如果您使用的是 swagger 2.9.2,那么示例在那里不起作用。这些注释被忽略

      protected Map<String, Response> mapResponseMessages(Set<ResponseMessage> from) {
        Map<String, Response> responses = newTreeMap();
        for (ResponseMessage responseMessage : from) {
          Property responseProperty;
          ModelReference modelRef = responseMessage.getResponseModel();
          responseProperty = modelRefToProperty(modelRef);
          Response response = new Response()
              .description(responseMessage.getMessage())
              .schema(responseProperty);
          **response.setExamples(Maps.<String, Object>newHashMap());**
          response.setHeaders(transformEntries(responseMessage.getHeaders(), toPropertyEntry()));
          Map<String, Object> extensions = new VendorExtensionsMapper()
              .mapExtensions(responseMessage.getVendorExtensions());
          response.getVendorExtensions().putAll(extensions);
          responses.put(String.valueOf(responseMessage.getCode()), response);
        }
        return responses;
      }
      

      尝试使用 swagger 3.0.0-Snapshot。 您需要像这样更改 Maven 依赖项:

      <dependency>
                  <groupId>io.springfox</groupId>
                  <artifactId>springfox-swagger2</artifactId>
                  <version>3.0.0-SNAPSHOT</version>
              </dependency>
              <dependency>
                  <groupId>io.springfox</groupId>
                  <artifactId>springfox-swagger-ui</artifactId>
                  <version>3.0.0-SNAPSHOT</version>
              </dependency>
              <dependency>
                  <groupId>io.springfox</groupId>
                  <artifactId>springfox-spring-webmvc</artifactId>
                  <version>3.0.0-SNAPSHOT</version>
              </dependency>
      

      并将 Swagger 配置文件上的注释更改为:@EnableSwagger2WebMvc

      【讨论】:

      • 仍然忽略 @ApiParam( value = "A JSON value", examples = @Example(value = @ExampleProperty(mediaType = MediaType.APPLICATION_JSON, value = "{foo:whatever, bar) 中的示例/值: 随便2}")))
      【解决方案6】:

      使用 swagger 3.0.0 试试这个而不是其他方法

      @Operation(
              summary = "Finds a person",
              description = "Finds a person by their Id.",
              tags = { "People" },
              responses = {
                  @ApiResponse(
                      description = "Success",
                      responseCode = "200",
                      content = @Content(mediaType = "application/json", schema = @Schema(implementation = Person.class))
                  ),
                  @ApiResponse(description = "Not found", responseCode = "404", content = @Content),
                  @ApiResponse(description = "Internal error", responseCode = "500", content = @Content)
              }
          )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-20
        • 1970-01-01
        相关资源
        最近更新 更多