Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python post request with Bearer token

Tags:

python

rest

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...

like image 625
Jakadinho Avatar asked Aug 24 '17 17:08

Jakadinho


People also ask

How do I send a Bearer Token in Python?

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.

How do you get auth tokens in Python?

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.

How do you pass a JWT token in Python?

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.

How do I send a POST request with Bearer Token?

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.


1 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()) 
like image 175
Dharmesh Fumakiya Avatar answered Sep 24 '22 23:09

Dharmesh Fumakiya