首页 > 解决方案 > 如何在 swagger.json 中为 POST 请求传递 formData?

问题描述

在我的播放框架应用程序中,我在路由文件中注册了 API:

POST /api/rmt-create-request controllers.Api.CreateRMTRequestForm

在控制器的操作中,我使用以下代码访问通过表单提交提交的 formData:

public Result CreateRMTRequestForm()
    {
        Map<String, String[]> params = request().body().asMultipartFormData().asFormUrlEncoded();

当我使用 forntend 应用程序提交表单时,它作为 API 工作正常。

我正在尝试使用 swagger.ui 创建 API 文档,其中我在 swagger.json 文件中编写了以下 JSON 数据。

"paths": {"/api/rmt-create-request": {
      "post": {
        "tags": [
          "RMT APIs"
        ],
        "description" : "Return newly created request data",
        "operationId": "create-new-rmt-request",
        "consumes": ["application/x-www-form-urlencoded"],
        "parameters": [
          {
            "name": "rootNodeName",
            "in": "formData",
            "description": "Root node class name for item",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/rmt-request-data"
                }
              }
            }
          },
          "default": {
            "$ref": "#/components/responses/default"
          }
        }
      }
    },

在检查 RequestHeader 数据时,它没有显示值为'multipart/form-data' 的content-Type 属性以及 formData 没有附加,这使得控制器抛出空异常。

任何人都可以帮助 swagger.json 文件中缺少什么吗?

标签: javaplayframeworkswagger

解决方案


您正在混合使用 OpenAPI 2.0 和 3.0 语法。

在 OpenAPI 3.0 中,请求正文(包括表单数据)是使用requestBody关键字而不是in: formData参数来定义的。

此外,OAS3 不使用consumes. 操作使用的媒体类型在requestBody.

"paths": {
  "/api/rmt-create-request": {
    "post": {
      "tags": [
        "RMT APIs"
      ],
      "description": "Return newly created request data",
      "operationId": "create-new-rmt-request",
      "requestBody": {
        "content": {
          "multipart/form-data": {    // or  "application/x-www-form-urlencoded" - depending on what you need
            "schema": {
              "type": "object",
              "properties": {
                "rootNodeName": {
                  "type": "string",
                  "description": "Root node class name for item"
                }
              }
            }
          }
        }
      }
    }
  }
}

更多信息:描述请求正文


推荐阅读