对于使用 application/x-www-form-urlencoded 内容类型的 API,如何修复从 openapi go 代码生成器获取的验证错误?

How to fix validation error getting from openapi go code generator for an API which consumes application/x-www-form-urlencoded content type?

我已经按照开放的 api 指南提到 here 来定义一个消耗 application/x-www-form-urlencoded 的 API 并写在下面 API:

{
    "openapi": "3.0.0",
    "info": {
        "version": "1.0.draft",
        "title": "user management api",
        "description": "This document defines interface to user management"
    },
    "servers": [{
        "url": "{apiRoot}/test",
        "variables": {
            "apiRoot": {
                "default": "https://example.com"
            }
        }
    }],
    "paths": {
        "/users/resetpassword": {
            "post": {
                "summary": "reset password of a user",
                "operationId": "resetUserPassword",
                "parameters": [{
                        "name": "username",
                        "in": "formData",
                        "required": true,
                        "schema": {
                            "type": "string"
                        }
                    },
                    {
                        "name": "password",
                        "in": "formData",
                        "required": true,
                        "schema": {
                            "type": "string"
                        }
                    }
                ],
                "responses": {
                    "204": {
                        "description": "User password has been changed"
                    }
                }
            }
        }
    }
}

运行 下面的命令使用 code generator:

从上面打开 API 文档生成 go 代码
docker run --rm -v ${PWD}:<file_path> openapitools/openapi-generator-cli generate -i <file_path> --skip-validate-spec -g go-server -o <file_out_path>

出现以下错误:

-attribute paths.'/users/resetpassword'(post).parameters.[username].in is not of type `string`
-attribute paths.'/users/resetpassword'(post).parameters.[password].in is not of type `string`

如何解决上述错误?

您混淆了 OpenAPI 2.0 和 OpenAPI 3.0 语法。

在 OpenAPI 3.0 中,请求主体(包括表单数据)是使用 requestBody 关键字定义的。将 parameters 部分替换为:

"requestBody": {
  "required": true,
  "content": {
    "application/x-www-form-urlencoded": {
      "schema": {
        "type": "object",
        "required": [
          "username",
          "password"
        ],
        "properties": {
          "username": {
            "type": "string"
          },
          "password": {
            "type": "string"
          }
        }
      }
    }
  }
}

YAML 版本:

requestBody:
  required: true
  content:
    application/x-www-form-urlencoded:
      schema:
        type: object
        required:
        - username
        - password
        properties:
          username:
            type: string
          password:
            type: string