Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
}
like image 511
Awethon Avatar asked Jan 26 '23 20:01

Awethon


1 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))
...
like image 143
Helen Avatar answered Jan 29 '23 11:01

Helen