Python post request with Bearer token

Jakadinho picture Jakadinho · Aug 24, 2017 · Viewed 57k times · Source

Im trying to make a script that post data on REST service together with Bearer token.

Here is working PHP example:

$postData = array( 'app' => 'aaaa' );

$ch = curl_init($apiUrl);
curl_setopt_array($ch, array(
    CURLOPT_HTTPHEADER, ['Authorization: Bearer '.$accessToken],
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_POSTFIELDS => json_encode($postData)
));

$response = curl_exec($ch);

Im trying to do the same with python. Here is what i got so far...

import urllib2, urllib
import json

auth_token='kbkcmbkcmbkcbc9ic9vixc9vixc9v'
hed = {'Authorization': 'Bearer ' + auth_token}
data = urllib.urlencode({'app' : 'aaaaa'})

url = 'https://api.xy.com'
req = urllib2.Request(url=url, headers=hed, data=data)
content = urllib2.urlopen(req).read()
print content

I get HTTP Error 400: Bad Request. Any help appretiated...

Answer

Dharmesh picture Dharmesh · Aug 24, 2017
import requests

auth_token='kbkcmbkcmbkcbc9ic9vixc9vixc9v'
hed = {'Authorization': 'Bearer ' + auth_token}
data = {'app' : 'aaaaa'}

url = 'https://api.xy.com'
response = requests.post(url, json=data, headers=hed)
print(response)
print(response.json())