问题
I am trying to access the API v2 from thetvdb.com (https://api.thetvdb.com). Unfortunately I always get the 403 error.
Here is what I have:
#!/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)
According to the API documentation I have to authenticate in order to get a token. But I just get 403 Forbidden.
Now I tried it using 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'
And this worked perfectly. Can anyone explain me what I am missing? This is driving me insane.
I also tried it with
post = requests.post(url, data = json.dumps(payload), headers = headers)
Same error.
回答1:
You have to explicitly convert the payload to json string and pass asdata . It looks like you have done that also you may try setting the user-agent as 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)
The program will look like
#!/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)
回答2:
I think you need to pass Accept headers in the python requests. Something like this
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",
}
来源:https://stackoverflow.com/questions/41361444/python-requests-error-403