Java 如何使用 Swagger 注释在 Swagger 中设置描述和示例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46584658/
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-08-12 02:25:08  来源:igfitidea点击:

How can I set a description and an example in Swagger with Swagger annotations?

javaspringswaggerswagger-codegen

提问by DarthRoman

I am creating a REST Api using Spring boot, and auto generating the swagger documentation in controllers using swagger codegen. However, I am not able to set a description and example for a parameter of type String in a POST request. Here is mi code:

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

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

The example property of the @ApiParam has been manually inserted by me, because the codegen was ignoring that part of the yaml (That is another question: why is the editor ignoring the example part?).Here is part of the yaml:

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

And finally, this is what swagger is showing:

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

enter image description here

在此处输入图片说明

Finally, the dependencies used in build.gradle are the following ones:

最后,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'

So, Question is:Does anybody know how I can set the description and an example of a body parameter using swagger annotations?

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

EDIT

编辑

I've achieved to change the description using @ApiImplicitParam instead of @ApiParam, but example is still missing:

我已经使用 @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}")}))})

回答by E. Bavoux

Have you tried the following ?

您是否尝试过以下方法?

@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}")

Have a nice day

祝你今天过得愉快

回答by Artem Trofimoff

I have similar issue with generating examples for body objects - annotation @Exampleand @ExamplePropertysimply doesn't work for no reason in swagger 1.5.x. (I use 1.5.16)

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

My current solution is:
use @ApiParam(example="...")for non-body objects, e.g.:

我目前的解决办法是:
使用@ApiParam(example="...")用于非人体的物体,如:

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

for bodyobjects create new class and annotate fields with @ApiModelProperty(value = " ", example = " "), e.g.:

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

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

回答by dpr

Actually the java doc for the exampleproperty of the @ApiParamannotation states that this is exclusively to be used for non-body parameters. Where the examplesproperty may be used for body parameters.

实际上,注释example属性的 java 文档@ApiParam指出,这仅用于非主体参数。该examples属性可用于身体参数。

I tested this annotation

我测试了这个注释

@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}"
    )
  )
)

which resulted in the following swagger to be generated for the corresponding method:

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

/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}"

However this value doesn't seem to be picked up by swagger-ui. I tried version 2.2.10 and the latest 3.17.4, but neither version used the x-examplesproperty of the swagger.

然而,这个值似乎没有被 swagger-ui 获取。我尝试了 2.2.10 版和最新的 3.17.4 版,但两个版本都没有使用x-examplesswagger的属性。

There are some references for x-example(the one used for non-body parameters) in the code of swagger-uibut no match for x-examples. That is this doesn't seem to be supported by swagger-ui at the moment.

swagger-uix-example代码中有一些参考(用于非主体参数的)但没有匹配的x-examples. 也就是说,目前 swagger-ui 似乎不支持这一点。

If you really need this example values to be present, your best option currently seems to be to change your method's signature and use a dedicated domain type for the body parameter. As stated in the comments already swagger will automatically pick up the structure of the domain type and print some nice information in swagger-ui:

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

Swagger-UI 2.2.10 with domain type info

带有域类型信息的 Swagger-UI 2.2.10

回答by Евгений Коптюбенко

If you are using swagger 2.9.2 then Examples are not working there. These annotations are ignored

如果您使用的是 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;
}

Try using swagger 3.0.0-Snapshot. You need to change maven dependencies like this:

尝试使用 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>

and change annotation on your Swagger config file to this: @EnableSwagger2WebMvc

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