如何将授权头添加到bravadocreated API客户端

2024-04-25 17:58:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我能够使用requests模块创建一个简单的API接口,该模块能够正确地进行身份验证并从API接收响应。但是,当我尝试使用bravado,从一个swagger文件创建客户机,并手动向头部添加授权令牌时,它失败了:

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

我相信我添加的授权头是正确的。你知道吗

下面是我用来创建客户机的代码。如图所示,我尝试通过两种方式添加授权令牌:

  • http_client设置中,通过set_api_key
  • Swagger.from_url(...)步骤中,添加request_headers。你知道吗

然而,这两种选择都失败了。你知道吗

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
)

我的问题是,如何正确地向虚张声势的客户机添加授权头?你知道吗


Tags: 模块keyfromclientapihttpurl客户机
2条回答

请重试,修复set\u api\u密钥行的主机。你知道吗

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,
)

在这里您可以找到有关方法的文档:https://github.com/Yelp/bravado/blob/master/README.rst#example-with-header-authentication

作为参考,一种可能的解决方案是在每个请求中添加_request_options

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)

然而,一个更好的解决方案,我仍然无法得到工作,是让它自动验证每个请求。你知道吗

相关问题 更多 >