【问题标题】:Query string parameter in swagger documentation not sent as array in requestswagger 文档中的查询字符串参数未在请求中作为数组发送
【发布时间】:2019-09-24 06:57:55
【问题描述】:

我目前正在使用 Symfony 4.3.4API 平台 v2.3.6 进行项目。

我现在面临 1 个问题。假设我使用名为 products 的查询字符串参数向 enpoint 发送 GET 请求,因为我发送了 1 个或多个 产品 ID。

我想在我的控制器中获取 products 参数的值作为 PHP 数组

所以我的要求是

GET /my/endpoint?products[]=8f391c60-5467-4bf0-917f-e2151337fa7e&products[]=ddaa94e1-af79-4abf-9dfc-a28dd8077f45

在控制器中我执行转储:

dump($request->query->get("products"));

然后我得到:

array:2 [
  0 => "8f391c60-5467-4bf0-917f-e2151337fa7e"
  1 => "ddaa94e1-af79-4abf-9dfc-a28dd8077f45"
]

您可以看到我在查询字符串中传递产品 ID 的方式(如数组),我可以将产品参数检索为 PHP 数组。 我在这里关心的是招摇文档。 在 YAML 中使用此配置:

collectionOperations:
    operation_name:
        method: get
        path: /my/endpoint
        controller: App\Controller\MyEndpointController
        swagger_context:
            summary: My summary
            description:
                My endpoint description
            responses:
                parameters:
                    -
                        in: query
                        name: products
                        description: "The products IDs parameter"
                        schema:
                            type: array
                            items:
                                type: "string"
                                example: "019fcd9b-beea-4791-8a59-d4e2d02427d6"

在 API 文档页面中,当我选择 Try it out 时,我必须填写包含 products 的所有参数值。问题是 products 参数显示为 文本输入

如果我在参数的yaml配置中去掉schema键,我把type: arrayitems键直接放在与inname和@987654329相同的级别@:

parameters:
    -
        in: query
        name: products
        description: "The products IDs parameter"
        type: array
        items:
            type: "string"
            example: "019fcd9b-beea-4791-8a59-d4e2d02427d6"

然后 products 参数出现,带有一个按钮 Add item。每次单击此按钮时,我都可以填写产品 ID 以通过,这很好。问题是,当我单击 Execute(仍在 API 文档页面中)时出现错误,因为 API 平台不会将带有 products 参数的请求作为真正的数组发送,而是作为包含由 , 分隔的所有产品 ID 的字符串发送:

GET /my/endpoint?products=8f391c60-5467-4bf0-917f-e2151337fa7e,ddaa94e1-af79-4abf-9dfc-a28dd8077f45

这就是我想要的:

GET /my/endpoint?products[]=8f391c60-5467-4bf0-917f-e2151337fa7e&products[]=ddaa94e1-af79-4abf-9dfc-a28dd8077f45

对使用 API 平台实现这一目标的方法有任何想法吗?

【问题讨论】:

    标签: rest symfony swagger api-platform.com


    【解决方案1】:

    查询参数需要命名为products[](带方括号)并具有collectionFormat: multi属性:

    parameters:
      - in: query
        name: products[]
        type: array
        items:
          type: string
          format: uuid
        collectionFormat: multi
        # (Optional) Array example to display in Swagger UI
        x-example:
          - 8f391c60-5467-4bf0-917f-e2151337fa7e
          - ddaa94e1-af79-4abf-9dfc-a28dd8077f45
    

    请注意,OpenAPI 2.0 do not support 中的查询参数是 example 关键字,但某些工具(例如 Swagger UI)支持 x-example 扩展名来指定查询参数的示例值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多