spring 如何在带有Swagger注解的Swagger中设置描述和示例?

zz2j4svz  于 2023-10-15  发布在  Spring
关注(0)|答案(7)|浏览(103)

我正在使用Sping 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;
}

**@ApiParam的example属性是由我手动插入的,因为codegen忽略了yaml的这一部分(这是另一个问题:为什么编辑器忽略了示例部分?).**这里是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
        }

最后,这是斯瓦格所展示的:

最后,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}")}))})
xggvc2p6

xggvc2p61#

我在为body对象生成示例时也遇到了类似的问题--在swagger 1.5.x中,注解@Example@ExampleProperty毫无理由地不起作用。(我使用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;;
}
qxsslcnc

qxsslcnc2#

实际上,@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}"
    )
  )
)

这导致对于相应的方法生成以下swagger:

/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参数使用一个专用的域类型。正如在评论中已经提到的,swagger将自动拾取域类型的结构,并在swagger-ui中打印一些不错的信息:

rjzwgtxy

rjzwgtxy3#

你试过以下方法吗?

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

祝你愉快

vbopmzt1

vbopmzt14#

使用swagger 3.0.0在rest方法上尝试此方法

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

mnowg1ta5#

Swagger.v3Kotlin/Kotlin示例:

@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> { ... }
c90pui9n

c90pui9n6#

如果你使用的是swagger 2.9.2,那么Examples就不能在那里工作。这些注解将被忽略

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-快照。您需要像这样更改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

q9rjltbz

q9rjltbz7#

我使用的是swagger.version 1.5.22,springfox-swagger 2 2.9.2和springfox-swagger-ui 2.9.2。对我来说,@schema可以代替@ApiModelProperty。假设请求体使用abcd来类。

public class ABCDto {
    @Schema(name = "id", example = "1", required = true)
    @JsonProperty("id")
    private String id;
}

相关问题