Python Forum

Full Version: passing token to requests
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to use the requests library to hit some endpoints, but I am having problems passing the auth token. This curl works just fine:

Output:
curl -X POST "https://my/api/" -H "accept: application/json" -H "Authorization: eeJ0eXAiOiJKV1.eyzdWIiOiIyNDAxN2QxMDdjODA0ZmI4.jArOH9fvXGiblidZ1ZhxvjLvc1Bg_AGDd" -H "Content-Type: application/json" -d "{ \"language\": \"en\", \"name\": \"dude\", \"password\": \"mypw\"}"
but when I try with requests:
token = 'eeJ0eXAiOiJKV1.eyzdWIiOiIyNDAxN2QxMDdjODA0ZmI4.jArOH9fvXGiblidZ1ZhxvjLvc1Bg_AGDd'
payload = {'language': 'en', 'name': 'dude', 'password': 'mypw'}

r = requests.post("https://my/api/",
                          headers={'Authorization':token}, data=payload)
I get a 500 from the server or if I change 'Authorization' to 'auth_token' or something else, I get unrecognized token.

I have tried so many things from stackoverflow but nothing has worked. I am at the point of just using curl but wanted to see if anybody here has had any similar experience.

Thanks for your time,
Try.
import requests

headers = {
    'accept': 'application/json',
    'Authorization': 'eeJ0eXAiOiJKV1.eyzdWIiOiIyNDAxN2QxMDdjODA0ZmI4.jArOH9fvXGiblidZ1ZhxvjLvc1Bg_AGDd',
    'Content-Type': 'application/json',
}

data = '{"language": "en", "name": "dude", "password": "mypw"}'
response = requests.post('https://my/api/', headers=headers, data=data)
Thanks guys, I still got a 500. Here is the response. I am also printing the header values

Output:
{"id": 500, "description": "Internal Server Error", "request_id": "e040171b3c0349e39b684879546f4997"} ValuesView({'Connection': 'keep-alive', 'Content-Length': '101', 'Content-Type': 'application/json', 'Server': 'nginx', 'X-MY-REQUEST-ID': 'e040171b3c0349e39b684879546f4997', 'Accept-Ranges': 'bytes', 'Date': 'Thu, 11 Mar 2021 22:18:55 GMT', 'Via': '1.1 varnish', 'X-Served-By': 'cache-pao17470-PAO', 'X-Cache': 'MISS', 'X-Cache-Hits': '0', 'X-Timer': 'S1615501135.095095,VS0,VE257', 'Access-Control-Allow-Origin': '*'})
Try send payload as json. In requests.post I replace data with json

payload = {'language': 'en', 'name': 'dude', 'password': 'mypw'} 
r = requests.post("https://my/api/", headers={'Authorization':token}, json=payload)
Thank you kashcode. That was it! I can't believe it. Off to using requests!

Alex