3

I am able to create a simple API interface using the requests module that authenticates correctly and receives a response from an API. However, when I attempt to use bravado, to create the client from a swagger file, and manually add an authorization token to the head, it fails with :

bravado.exception.HTTPUnauthorized: 401 Unauthorized: Error(code=u'invalid_credentials', message=u'Missing authorization header',

I believe I am adding the authorization headers correctly.

The code I'm using to create the client is below. As shown, I've tried to add an Authorization token two ways:

  • in the http_client setup via set_api_key
  • in the Swagger.from_url(...) step by adding request_headers.

However both options fail.

from bravado.requests_client import RequestsClient
from bravado.client import SwaggerClient

http_client = RequestsClient()
http_client.set_api_key(
    'https://api.optimizely.com/v2', 'Bearer <TOKEN>',
    param_name='Authorization', param_in='header'
)


headers = {
    'Authorization': 'Bearer <TOKEN>',
}

client = SwaggerClient.from_url(
    'https://api.optimizely.com/v2/swagger.json',
    http_client=http_client,
    request_headers=headers
)

My question is, how do I properly add authorization headers to a bravado SwaggerClient?

Charles Menguy
  • 40,830
  • 17
  • 95
  • 117
rmg
  • 1,009
  • 16
  • 31

2 Answers2

1

For reference, a possible solution is to add the _request_options with each request:

from bravado.client import SwaggerClient

headers = {
  'Authorization': 'Bearer <YOUR_TOKEN>'
}

requestOptions = {
   # === bravado config ===
   'headers': headers,
}

client = SwaggerClient.from_url("<SWAGGER_JSON_URL>")

result = client.<ENTITY>.<ACTION>(_request_options=requestOptions).response().result
print(result)

However, a better solution, which I still am unable to get to work, is to have it automatically authenticate with each request.

rmg
  • 1,009
  • 16
  • 31
1

Try again, fixing the host of the set_api_key line.

from bravado.requests_client import RequestsClient
from bravado.client import SwaggerClient

http_client = RequestsClient()
http_client.set_api_key(
    'api.optimizely.com', 'Bearer <TOKEN>',
    param_name='api_key', param_in='header'
)
client = SwaggerClient.from_url(
    'https://api.optimizely.com/v2/swagger.json',
    http_client=http_client,
)

Here you will find documentation about the method : https://github.com/Yelp/bravado/blob/master/README.rst#example-with-header-authentication

Claudio
  • 21
  • 2