How to format headers to send with python-requests - python

I'm not sure how to get the headers in an alphabetical order as the in the example in python-requests. Do the brackets and the punctuation such as ' effect the request headers when they are sent?
This is my code:
headers = {'oauth_callback': "http://www.website-tm-access.co.nz%2Ftrademe-callback",
'oauth_consumer_key' : "5C82CC6BC7C6472154FBC9CAB24A29A2" ,
'oauth_version': "1.0",
'oauth_timestamp': time, #int(time.time()),
'oauth_nonce' : nonce,
'oauth_signature_method' : "HMAC-SHA1",
'oauth_signature' : signature
}
authorization = ', '.join([key + '="' + urllib.parse.quote_plus(str(value)) + '"' for key, value in headers.items()])
http_headers = {'Authorization': authorization}
The Output is:
{'Authorization': 'oauth_nonce="62942100", oauth_callback="http%3A%2F%2Fwww.website-tm-access.co.nz%252Ftrademe-callback", oauth_consumer_key="5C82CC6BC7C6472154FBC9CAB24A29A2", oauth_version="1.0", oauth_timestamp="1457345962", oauth_signature="b%27o0rNPtba78EQ3ALsg2mX1Y4vIQw%3D%27", oauth_signature_method="HMAC-SHA1"'}
The output as defined in the example:
To make the Authorization header, you simply append all the values
starting with “OAuth”. Each value must be URL encoded.
Authorization: OAuth oauth_callback="http%3A%2F%2Fwww.website-tm-access.co.nz%2Ftrademe-callback", oauth_consumer_key="C74CD73FDBE37D29BDD21BAB54BC70E422", oauth_version="1.0", oauth_timestamp="1285532322", oauth_nonce="7O3kEe", oauth_signature_method="HMAC-SHA1", oauth_signature="5s3%2Bel078a5AXGi43FBDyfg5yWY%3D"

The order shouldn't matter when passing the headers to the requests module.
You can just do:
headers = {'oauth_callback': "http://www.website-tm-access.co.nz%2Ftrademe-callback",
'oauth_consumer_key' : "5C82CC6BC7C6472154FBC9CAB24A29A2" ,
'oauth_version': "1.0",
'oauth_timestamp': int(time.time()),
'oauth_nonce' : nonce,
'oauth_signature_method' : "HMAC-SHA1",
'oauth_signature' : signature
}
r = requests.get(url, headers=headers)

Related

Pinterst api: not able to get access token - Stuck in Oauth flow

Using v5 of the pinterest api and stuck on the authentication flow: https://developers.pinterest.com/docs/getting-started/authentication/
Completed the first step and got the access code.
However, I get the below error when I try to use this code to get the access token.
{"code":1,"message":"Missing request body"}
Here is my code:
client_id= 'my_client_id'
client_secret = 'my_client_secret'
data_string = f'{client_id}:{client_secret}'
token = base64.b64encode(data_string.encode())
headers = {
'Authorization': 'Basic ' + token.decode('utf-8'),
'Content-Type': 'application/x-www-form-urlencoded',
}
url = "https://api.pinterest.com/v5/oauth/token"
code = "my_code_that_i_got_in_the_first_step"
params = {
'grant_type':'authorization_code',
'code': code,
'redirect_url':'https://my_redirect_uri'
}
r = requests.post(url, headers=headers, params=params)
print(r.json())
Below is the correct way to get the access token:
client_id= 'my_client_id'
client_secret = 'my_client_secret'
data_string = f'{client_id}:{client_secret}'
token = base64.b64encode(data_string.encode())
headers = {
'Authorization': 'Basic ' + token.decode('utf-8'),
'Content-Type': 'application/x-www-form-urlencoded',
}
url = "https://api.pinterest.com/v5/oauth/token"
code = "my_code_that_i_got_in_the_first_step"
data= {
'grant_type':'authorization_code',
'code': code,
'redirect_uri':'https://my_redirect_uri'
}
r = requests.post(url, headers=headers, data=data)
print(r.json())
In my question, I had mistyped redirect_uri as redirect_url. Also, when sending a POST, you should use data instead of params. See the comment by Amos Baker.

"unsupported_grant_type" when using Google's urlfetch to get an oauth token from PayPal. Using "requests" works

I've been trying (and failing miserably) to use google's urlfetch module (python within app engine's local server) to retrieve a token from paypal. It works as follows using the "requests" module outside of app engine:
url = base + "/v1/oauth2/token"
payload = {
'grant_type': 'client_credentials',
}
auth_encoded = APP_CLIENT_ID + ":" + APP_SECRET
auth_encoded = base64.b64encode(auth_encoded)
##headers = {'Content-Type': 'application/json', 'Authorization': 'Basic ' + auth_encoded}
headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic ' + auth_encoded}
r = requests.post(url,headers=headers,params=payload)
print r.text
... but I get this message when trying the same thing with urlfetch:
{"error":"unsupported_grant_type","error_description":"Grant Type is NULL"}
... here's the code that I'm using:
url = base + "/v1/oauth2/token"
payload = {"grant_type": "client_credentials"}
auth_encoded = APP_CLIENT_ID + ":" + APP_SECRET
auth_encoded = base64.b64encode(auth_encoded)
headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic ' + auth_encoded}
result = urlfetch.fetch(
url=url,
method=urlfetch.POST,
headers=headers,
payload = payload
)
... I've tried everything that I can think of. Should be a simple thing.
This API call is formatted as application/x-www-form-urlencoded , not JSON.
Therefore:
payload = "grant_type=client_credentials"
or
import urllib
payload = urllib.urlencode({"grant_type": "client_credentials"})

Spotify Web API python requests unable to access public playlist information

import requests
import json
CLIENT_ID = 'xxxx'
CLIENT_SECRET = 'xxxx'
AUTH_URL = 'https://accounts.spotify.com/api/token'
auth_response = requests.post(AUTH_URL, {
'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
})
# convert the response to JSON
auth_response_data = auth_response.json()
# save the access token
access_token = auth_response_data['access_token']
headers = {
'Authorization': 'Bearer {token}'.format(token=access_token),
'Content-Type': 'application/json'
}
# base URL of all Spotify API endpoints
BASE_URL = 'https://api.spotify.com/v1/'
# Playlist ID from the URI
playlist_id = '5GEf0fJs9xBPr5R4jEQjtw'
# actual GET request with proper header
playlist_response = requests.get(BASE_URL + 'playlist/'+playlist_id, headers=headers)
#Track ID from the URI
track_id = '6y0igZArWVi6Iz0rj35c1Y'
track_response = requests.get(BASE_URL + 'audio-features/' + track_id, headers=headers)
print(playlist_response.text)
print(track_response.text)
So with this code, the track_response returns:
{
"danceability" : 0.540,
"energy" : 0.590,
"key" : 0,
"loudness" : -4.359,
"mode" : 1,
"speechiness" : 0.0528,
"acousticness" : 0.446,
"instrumentalness" : 0,
"liveness" : 0.140,
"valence" : 0.267,
"tempo" : 119.878,
"type" : "audio_features",
"id" : "6y0igZArWVi6Iz0rj35c1Y",
"uri" : "spotify:track:6y0igZArWVi6Iz0rj35c1Y",
"track_href" : "https://api.spotify.com/v1/tracks/6y0igZArWVi6Iz0rj35c1Y",
"analysis_url" : "https://api.spotify.com/v1/audio-analysis/6y0igZArWVi6Iz0rj35c1Y",
"duration_ms" : 234910,
"time_signature" : 4
}
But when I try and repeat this to obtain information about the playlist, I receive a 404 error saying that the service is not found. I have found this is the same case for albums when I use BASE_URL + 'album/' + id. How can I get this to return some playlist information?
Any help is greatly appreciated.

How to config Bearer Token when making a GET request?

Here is the Bearer Token in Postman:
Here is what I do in code:
url_apollo = https://
params_apollo = {
'ID': 123,
}
Here is the requests that I made:
r_apollo = requests.get(url = url_apollo,
params = params_apollo,
headers={'Authorization': 'Bearer ' + 'Token'})
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1
(char 0)
You could do it like this:
url_apollo = https://
params_apollo = {'ID': 123}
headers = {'Authorization': 'Bearer YOURTOKENHERE'}
r_apollo = requests.get(url=url_apollo,
params=params_apollo,
headers=headers)
The reason why you get that error message is within the "params_apollo" variable. Since "ID" is the last line in the JSON, the comma after the value is incorrect and raises a JSONDecodeError.

Python Requests: Success/Error Not Called

Trying to use python requests. I'm getting a {"code":141,"error":"success/error was not called"} error when I try to save the response I receive from the url into a variable and then post it back to a different url. Any ideas how I can fix this?
payload = { "email" : "jade#gmail.com", "github" : "https://github.com/"}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/r", json = payload, headers = headers)
#Store the token into a variable
token = r.text
payload = { "token" : token}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/getstring", json = payload, headers = headers)
print r.text
You have to use the actual tokens you get back:
Based on the instructions from the main page:
================================
Stage I: Reverse a string
================================
Once you’re registered, it’s time to get started on the challenges.
The first one is straightforward. You’re going to reverse a string.
That is, if the API says “cupcake,” you’re going to send back “ekacpuc.”
POST a JSON dictionary with the key token and your previous token value to this endpoint:
http://challenge.code2040.org/api/getstring
The getstring endpoint will return a string that your code should then reverse, as in the example above.
Once that string is reversed, send it back to us. POST some JSON to:
http://challenge.code2040.org/api/validatestring
Use the key token for your token.
Use the key string for your reversed string.
Part 1 get out token:
payload = { "email" : "jade#gmail.com", "github" : "https://github.com/"}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/register", json = payload, headers = headers)
#Store the token into a variable
token = r.json() # {u'result': u'ZO8FFqVjWp'}
part 2 get the string:
payload = { "token" :token["result"]}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/getstring", json = payload, headers = headers)
jsn = r.json() # {"result":"Wv55g"} # we need to reverse that string
The final part is actually reversing the string you get from our last post:
payload = {"token" :token["result"], "string" :jsn["result"][::-1]} # jsn["result"][::-1]} reverse the string
r = requests.post("http://challenge.code2040.org/api/validatestring", json = payload, headers = headers)
print(r.json())
{u'result': u'PASS: stage1. Enrollment record updated!'} # all good!
You also had an extra r in your address "http://challenge.code2040.org/r" <- should not be there

Categories

Resources