如何在 Swagger Codegen 3.x 生成的 Python API 客户端中设置 Bearer 令牌?

Awe*_*hon 4 python swagger bearer-token swagger-codegen

我使用https://generator.swagger.io/ 上的在线 Swagger Codegen为这个 API生成了一个 Python 客户端库。API 使用 Bearer 身份验证:

openapi: 3.0.0
...

paths:
  /sandbox/register:
    post:
      ...
      security:
        - sso_auth: []
      ...

components:
  securitySchemes:
    sso_auth:
      type: http
      scheme: bearer
Run Code Online (Sandbox Code Playgroud)

但是,Configuration生成的 Python 客户端中的类没有access_token字段。

使用生成的客户端库时如何填写不记名访问令牌?


代码生成端点POST /gen/clients/{language}具有authorizationValuesecurityDefinition参数 - 我是否需要以某种方式配置这些参数?

"authorizationValue": {
  "value": "string",
  "type": "string",
  "keyName": "string"
},
"securityDefinition": {
  "type": "string",
  "description": "string"
}
Run Code Online (Sandbox Code Playgroud)

Hel*_*len 8

首先,由于您的 API 是 OpenAPI 3.0,您需要使用 Swagger Codegen 3.x,即https://generator3.swagger.ioswagger-codegen-cli-3.0.11.jar. https://generator.swagger.io上的生成器适用于 OpenAPI 2.0 ( swagger: '2.0')。

也就是说,Swagger Codegen 3.x 的 Python 生成器中存在一个错误,它不会在 OpenAPI 3.0 定义中生成用于承载身份验证的代码。请在https://github.com/swagger-api/swagger-codegen-generators/issues提交错误报告

authorizationValuesecurityDefinition参数/gen/clients与 OpenAPI 文件中的安全定义无关。


作为解决方法,请编辑您的 OpenAPI YAML 文件并替换此部分

  securitySchemes:
    sso_auth:
      type: http
      scheme: bearer
Run Code Online (Sandbox Code Playgroud)

和:

  securitySchemes:
    sso_auth:
      type: apiKey
      in: header
      name: Authorization
Run Code Online (Sandbox Code Playgroud)

然后从修改后的 API 定义生成一个新的 Python 客户端。

现在,一旦您按照 中的说明安装了客户端软件包README.md,您应该能够按如下方式设置令牌:

import swagger_client
...

# Configure API key authorization: sso_auth
configuration = swagger_client.Configuration()
configuration.api_key['Authorization'] = 'YOUR_BEARER_TOKEN'
configuration.api_key_prefix['Authorization'] = 'Bearer'

# create an instance of the API class
api_instance = swagger_client.MarketApi(swagger_client.ApiClient(configuration))
...
Run Code Online (Sandbox Code Playgroud)