【问题标题】:How to format a JSON array in the request body of a multipart/form-data request with OpenAPI 3?如何使用 OpenAPI 3 在多部分/表单数据请求的请求正文中格式化 JSON 数组?
【发布时间】:2021-09-18 07:22:32
【问题描述】:

我正在尝试为现有端点编写 OpenAPI 3 规范。端点使用multipart/form-data 中的Content-Type,其中一个参数接受JSON 数组字符串。以下 curl 显示了此端点正常工作的示例:

curl -X 'POST' \
  'https://testing.org/test/' \
  -H 'accept: */*' \
  -H 'Content-Type: multipart/form-data' \
  -F 'simple=abc' \
  -F 'complex=[{"key": "string", "size": 0}"]'

我的 OpenAPI 3 规范目前如下所示:

openapi: 3.0.3
info:
  title: Simple
  description: Testing
  version: '1.0'
servers:
  - url: 'https://testing.org'
paths:
  /test/:
    post:
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                simple: 
                  type: string
                complex:
                  type: array
                  items:
                      type: object
                      properties:
                        key: 
                          type: string
                        size: 
                          type: integer
            encoding:
              complex:
                contentType: application/json
      responses:
        '200':
          description: OK

但是,使用swagger editor 中的“测试它”功能会产生如下所示的请求:

curl -X 'POST' \
  'https://testing.org/test/' \
  -H 'accept: */*' \
  -H 'Content-Type: multipart/form-data' \
  -F 'simple=abc' \
  -F 'complex=["{\n  \"key\": \"string\",\n  \"size\": 0\n}"]'

complex 参数格式不正确。如果我删除了规范中的 encoding 部分,则请求如下所示:

curl -X 'POST' \
  'https://testing.org/test/' \
  -H 'accept: */*' \
  -H 'Content-Type: multipart/form-data' \
  -F 'simple=abc' \
  -F 'complex={
  "key": "string",
  "size": 0
}'

这是一个 JSON 对象,但不是 JSON 数组。

关于如何格式化 OpenAPI 3 规范以便将 complex 表单参数格式化为简单的 JSON 数组 [{"key": "string", "size": 0}"] 有任何建议吗?谢谢!

【问题讨论】:

    标签: json multipartform-data swagger-ui openapi


    【解决方案1】:

    您的 API 定义是正确的。它甚至可以在没有encoding 的情况下工作,因为对象和对象数组的Content-Type 默认为application/json

    问题是 Swagger UI 和 Swagger Editor 还不能正确支持多部分正文中的 JSON。以下是您可以跟踪的相关问题:

    【讨论】:

      猜你喜欢
      • 2016-12-17
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多