如何为Authenticated API GET请求设置请求标头

时间:2018-10-25 23:34:03

标签: python python-3.x python-requests python-2.x

我正在尝试向API发出经过身份验证的GET请求。这是我第一次使用Python的request库。我看过与此类似的帖子,但是看来它们太笼统了,无法回答我的问题。他们的答案几乎适用于我处理过的所有其他情况,因此感觉有些卡住。

请求标头相当长:

':authority': 'api-WEBSITE.com',
':method': 'GET',
':path': 'ENDPOINT',
':scheme': 'https',
'accept': 'application/json',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9',
'authorization': 'AUTH_TOKEN', 
'content-type': 'application/json',
'cookie': 'VERY_LONG_COOKIE',
'origin': 'https://WEBSITE.com',
'referer': 'https://WEBSITE.com/app',
'user-agent': 'LIST_OF_BROWSERS'

发出此请求的代码:

import requests

requestURL = "https://api-WEBSITE.com/ENDPOINT"

parameters = {
    ':authority': 'api-WEBSITE.com',
    ':method': 'GET',
    ':path': 'ENDPOINT',
    ':scheme': 'https',
    'accept': 'application/json',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9',
    'authorization': 'AUTH_TOKEN', 
    'content-type': 'application/json',
    'cookie': 'VERY_LONG_COOKIE',
    'origin': 'https://WEBSITE.com',
    'referer': 'https://WEBSITE.com/app',
    'user-agent': 'LIST_OF_BROWSERS'
}

response = requests.get(requestURL, parameters)

print(response.status_code)

运行此命令时,我收到401状态码,要求进行身份验证;但是,我似乎无法找出引发此401错误的原因。

1 个答案:

答案 0 :(得分:1)

要为python请求提供标头:您必须执行此操作 r = request.get(URL,标头= headersDict)

headersDict是要添加到请求中的标头的有效字典