我正在尝试从thetvdb.com(https://api.thetvdb.com)访问API v2。不幸的是我总是得到403错误。
这就是我所拥有的:
#!/usr/bin/python3
import requests
url = "https://api.thetvdb.com/login"
headers = {'content-type': 'application/json'}
payload = {"apikey":"123","username":"secretusername","userkey":"123"}
post = requests.post(url, data = payload, headers = headers)
print(post.status_code, post.reason)
根据API文档,我必须进行身份验证才能获得令牌。但我得到了403 Forbidden。
现在我尝试使用curl:
curl -X POST --header 'Content-Type: application/json' --header 'Accept:
application/json' -d
{"apikey":"123","username":"secretusername","userkey":"123"}'
'https://api.thetvdb.com/login'
这完美无缺。任何人都可以解释我错过了什么吗?这让我疯了。
我也尝试了
post = requests.post(url, data = json.dumps(payload), headers = headers)
同样的错误。
答案 0 :(得分:0)
您必须explicitly
将payload
转换为json字符串并传递为data
。看起来您已经这样做了,您也可以尝试将用户代理设置为curl/7.47.1
headers = {'content-type': 'application/json', 'User-Agent': 'curl/7.47.1'}
post = requests.post(url, data = json.dumps(payload), headers = headers)
程序看起来像
#!/usr/bin/python3
import requests
import json
url = "https://api.thetvdb.com/login"
headers = {'content-type': 'application/json', 'User-Agent': 'curl/7.47.1'}
payload = {"apikey":"123","username":"secretusername","userkey":"123"}
post = requests.post(url, data = json.dumps(payload), headers = headers)
print(post.status_code, post.reason)
答案 1 :(得分:0)
我认为您需要在python请求中传递Accept标头。像这样的东西
header = {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
"Accept-Encoding": "gzip, deflate, sdch, br",
"Accept-Language": "en-US,en;q=0.8",
"User-Agent": "some user-agent",
}