【问题标题】:How to describe list of particular objects using Swagger in Spring Boot?如何在 Spring Boot 中使用 Swagger 描述特定对象的列表?
【发布时间】:2023-03-22 11:35:01
【问题描述】:

我使用 Swagger 描述了我的控制器,但是当我尝试提取控制器的 .yaml 描述时,作为端点的响应,我找到了对象列表。如何让 Swagger 将这些列表描述为特定对象的列表,例如汽车列表、房屋列表、动物列表等,然后描述汽车、房屋或动物等特定对象是什么。 我的情况是:

/dummy_endpoint:
get:
  tags:
    - foo-controller
  summary: Get foo list
  description: Send GET request to obtain foo list
  operationId: findAllFooUsingGET
  produces:
     - application/json
  responses:
    '200':
      description: Foo list obtained successfully
      schema:
        type: array
        items:
          type: object
    '401':
      description: Unauthorized
    '403':
      description: Forbidden
    '404':
      description: Not Found

我想得到什么:

/dummy_endpoint:
  get:
    tags:
      - foo-controller
    summary: Get foo list
    description: Send GET request to obtain foo list
    operationId: findAllFooUsingGET
    produces:
      - application/json
    responses:
      '200':
        description: Foo list obtained successfully
        schema:
          type: array
          items:
            type: Foo
      '401':
        description: Unauthorized
      '403':
        description: Forbidden
      '404':
        description: Not Found
definitions:
  Foo:
    type: object
    properties:
      id:
        type: integer
        format: int32
      name:
        type: String

【问题讨论】:

  • 你用的是什么版本的swagger?
  • 我用的是2.0版本。

标签: rest swagger swagger-ui openapi


【解决方案1】:

解决我的问题的方法是使用 @ResponseApi 注释中的 responseContainer 属性,我将响应容器类型(如 List、Array 等)放入 response存储到容器中的对象的属性类型。

【讨论】:

    【解决方案2】:

    我假设 OpenAPI 版本为 2.0(基于示例中的语法)。如果您使用的是 3.0,请告诉我。

    您正在寻找的是ref。在输入和输出模型部分签入Swagger specification,在数组和多值参数部分签入here

    例如:

    ...
    responses:
      '200':
        description: Foo list obtained successfully
        schema:
          type: array
          items:
            $ref: "#/definitions/Foo"
    ...
    definitions:
      Foo:
        type: object
        properties:
          ...
    

    【讨论】:

    • 有没有办法自动添加这些 ref 参数,例如通过 @ApiResponse 注释?
    • 您是在谈论 Java 的 API 吗?
    • 可用,@ApiResponse 注释中有 schema 的值。 HereOperation Annotations 部分中的示例(第二个与 User 类的输出)。对于您的情况schema = @Schema(implementation = Foo.class).
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    相关资源
    最近更新 更多