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

Question:

I’ve generated a Python client library for this API by using the online Swagger Codegen at https://generator.swagger.io/. The API uses Bearer authentication:

openapi: 3.0.0
...

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

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

However, the Configuration class in generated Python client has no access_token field.

How to fill the Bearer access token when using the generated client library?

The codegen endpoint POST /gen/clients/{language} has the authorizationValue and securityDefinition parameters – do I need to configure these parameters somehow?

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

||

Answers:

First of all, since your API is OpenAPI 3.0 you need to use Swagger Codegen 3.x, i.e. https://generator3.swagger.io or swagger-codegen-cli-3.0.11.jar. The generator at https://generator.swagger.io is for OpenAPI 2.0 (swagger: '2.0').

That said, there’s a bug in the Python generator of Swagger Codegen 3.x, it doesn’t generate the code for Bearer authentication in OpenAPI 3.0 definitions. Please file a bug report at https://github.com/swagger-api/swagger-codegen-generators/issues

The authorizationValue and securityDefinition parameters of /gen/clients are not related to security definitions in OpenAPI files.

As a workaround, edit your OpenAPI YAML file and replace this part

  securitySchemes:
    sso_auth:
      type: http
      scheme: bearer

with:

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

Then generate a new Python client from the modified API definition.

Now, once you have installed the client package as explained in README.md, you should be able to set the token as follows:

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))
...
Answered By: Helen

In my case I could simply set access_token of Configuration object like this:

configuration = Configuration()
configuration.verify_ssl = ...
configuration.host = ...
configuration.access_token = token

Information taken from here, schema generated by fastapi.

enter image description here

Answered By: Tobias Ernst