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...
To send a GET request with a Bearer Token authorization header using Python, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.
Obtain Access TokenUse your client ID and client secret to obtain an auth token. You will add the auth token to the header of each API request. The following Python example shows how to obtain an auth token and create the Authorization header using the token.
import requests import json myToken = 'ABCD' #(Dummy token, have copied actual token from session storage in chrome) myUrl ='http://10.197.194.137/' head = {'Authorization': 'token {}'. format(myToken) +myToken} headers = {'content-type': 'application/json'} response = requests.
To send a POST JSON request with a Bearer Token authorization header, you need to make an HTTP POST request, provide your Bearer Token with an Authorization: Bearer {token} HTTP header and give the JSON data in the body of the POST message.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With