Python post request with Bearer token

Question:

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…

Asked By: Jakadinho

||

Answers:

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())
Answered By: Dharmesh Fumakiya

You can get the token from response

request.headers['authorization']
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.