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

How to set the Bearer token in the Python API client generated by Swagger Codegen 3.x?

我已经为 this API by using the online Swagger Codegen at https://generator.swagger.io/ 生成了一个 Python 客户端库。 API 使用 Bearer 认证:

openapi: 3.0.0
...

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

components:
  securitySchemes:
    sso_auth:
      type: http
      scheme: bearer

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

使用生成的客户端库时如何填写Bearer access token?


codegen 端点 POST /gen/clients/{language} 具有 authorizationValuesecurityDefinition 参数 - 我需要以某种方式配置这些参数吗?

"authorizationValue": {
  "value": "string",
  "type": "string",
  "keyName": "string"
},
"securityDefinition": {
  "type": "string",
  "description": "string"
}

首先,由于您的 API 是 OpenAPI 3.0,您需要使用 Swagger Codegen 3.x,即 https://generator3.swagger.io or swagger-codegen-cli-3.0.11.jar. The generator at https://generator.swagger.io 用于 OpenAPI 2.0 (swagger: '2.0').

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

提交错误报告

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


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

  securitySchemes:
    sso_auth:
      type: http
      scheme: bearer

与:

  securitySchemes:
    sso_auth:
      type: apiKey
      in: header
      name: Authorization

然后根据修改后的 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))
...