I have this code, it sends a request to my server which is run by web.py:
url = "https://sample.com/api"
auth_string = 'Basic ' + base64.encodestring('%s:%s' % ("usernamexxxx", "codexxxx"))[:-1]
headers = {"Content-Type": "application/json", "authorization": auth_string}
data = {"message":"WELCOME!..."}
req = urlfetch.fetch(url, method=urlfetch.POST, payload= simplejson.dumps(data), headers= headers)
response = req.content
So when I receive this kind of request in my web server I want to check if the username and code input to the request is valid or not? And how can I access the given data of the code above?
Probably you can access those headers via the os.environ dictionary.
Related
I'm trying to get a token using Spotify's Client Credentials Flow and Python, however I just get the following:
{"error":"invalid_client","error_description":"Invalid client"}
I'm following this guide - https://developer.spotify.com/documentation/general/guides/authorization/client-credentials/
Using this example script as a starting point - https://www.w3schools.com/python/showpython.asp?filename=demo_requests_post_headers
Here's my code (I've changed the Base 64 encoded string that contains the client ID and client secret key):
import requests
url = 'https://accounts.spotify.com/api/token'
myobj = {'grant_type': 'client_credentials'}
#use the 'headers' parameter to set the HTTP headers:
x = requests.post(url, data = myobj, headers = {"Authorization": "Basic Base64EncodedStringHere==","Content-Type": "application/x-www-form-urlencoded"})
print(x.text)
If I change the last line to print(x), I just get: <Response [400]>
Clearly I'm doing something wrong, but I can't figure out what?
I had the same problem while following a tutorial but I manage to find a solution on the Spotify community.
import requests
import base64
client_id = "your client id here"
client_secret = "your client secret here"
encoded = base64.b64encode((client_id + ":" + client_secret).encode("ascii")).decode("ascii")
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + encoded
}
payload = {
"grant_type": "client_credentials"
}
response = requests.post("https://accounts.spotify.com/api/token", data=payload, headers=headers)
print(response.text)
I am new to using this type of trying to get the user details in my org using python flask server by hitting the
URL : https://graph.microsoft.com/v1.0/me/
Request headers:
'Content-Type': "application/json", 'Authorization': accessToken
Response:
Access Denied
The page you requested has been blocked
any suggestions please?
From the graph URL , able to get the response from python code base we got the Access Denied.
method in python:
enter code here
def get_user_details_(access_token: str):
url = "https://graph.microsoft.com/v1.0/me"
headers = {'Content-Type': "application/json",
'Authorization': access_token
}
response = requests.get(url, headers=headers, verify=False)
print("response **** ", response.text)
response = response.json() if response else {}
return response
enter image description here
To resolve the above issue, We can follow the below workaround;
Make sure that you have following permissions given for your application so that, while calling the API it can able to read and give the desired result.
OUTPUT RESULT FOR REFERENCE:-
For complete setup please refr this BLOG|Querying Microsoft Graph API with Python by #Ephraim Mwai.
I found the answer.
It is related to Proxy. We need to add proxy details to request object.
proxyDict = {
"http": "http proxy address",
"https": "https proxy address"
}
response = requests.request('GET', url, headers=headers, proxies=proxyDict, verify=False)
Sending Post request error
Hi talented developers. I am going to send request to specified url with authorization header.
I am trying to send POST request to
POST https://server/api HTTP 1.1
Authorization: Bearer a12b34567c89012def34g56789hi0j12
{
"data" : "test"
}
url = "https://server/api"
headers = {'Authorization' : 'Bearer %s' % API_KEY}
data = {
"data" : "test"
}
req = requests.post (url, headers = headers, data =
json.dumps(data))
Could you tell me what I am doing wrong in this code snippet?
I appreciate your help.
Thanks
i'm working on settin up a rest api with python, however i'm having some problem getting it to work.
I'm working with the TV DB rest api: https://api.thetvdb.com/swagger
and using python with Requests library to pull out the information.
My code is currently:
import json
import requests
URL = "https://api.thetvdb.com/"
API_KEY = "Api_key"
USER_KEY = "Key"
USERNAME = "Name"
headers = {"Accept": "application/json"}
params = {
"apikey": API_KEY,
"userkey": USER_KEY,
"username": USERNAME
}
resp = requests.post(URL + "login/", headers = headers ,params=params)
if resp.status_code != 200:
print('error: ' + str(resp.status_code))
else:
print('Success')
So far i'm only getting error code 401, not sure why.
Solved:
2 Things needed to be changed
1. The resp was changed into:
resp = requests.post(URL + "login/", headers = headers, data=json.dumps(params))
The header had to have
"Content-Type": "application/json"
added to it :) It's now working, thanks everyone
The login parameters probably need to be a JSON-encoded string POSTed as the body of the message.
Try resp = requests.post(URL + "login/", headers = headers, data=json.dumps(params))
I'm at the first stage of integrating our web app with PayPal's express checkout api. For me to place a purchase, I have to get a Bearer token of course using our client id and our client secret.
I use the following curl command to successfully get that token:
curl https://api.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-u "ourID:ourSecret" \
-d "grant_type=client_credentials"
Now I am trying to achieve the same results in python using urllib2. I've arrived at the following code, which produces a 401 HTTP Unauthorized exception.
import urllib
import urllib2
url = "https://api.sandbox.paypal.com/v1/oauth2/token"
PAYPAL_CLIENT_ID = "ourID"
PAYPAL_CLIENT_SECRET = "ourSecret"
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
req = urllib2.Request( url=url,
headers={
"Accept": "application/json",
"Accept-Language": "en_US",
},
data =urllib.urlencode({
"grant_type":"client_credentials",
}),)
result = urllib2.urlopen(req).read()
print result
Does anyone have any idea what I'm doing wrong above? Many thanks for any insights
Experiencing the same problem here. Based on Get access token from Paypal in Python - Using urllib2 or requests library working python code is:
import urllib
import urllib2
import base64
token_url = 'https://api.sandbox.paypal.com/v1/oauth2/token'
client_id = '.....'
client_secret = '....'
credentials = "%s:%s" % (client_id, client_secret)
encode_credential = base64.b64encode(credentials.encode('utf-8')).decode('utf-8').replace("\n", "")
header_params = {
"Authorization": ("Basic %s" % encode_credential),
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
}
param = {
'grant_type': 'client_credentials',
}
data = urllib.urlencode(param)
request = urllib2.Request(token_url, data, header_params)
response = urllib2.urlopen(request).open()
print response
The reason, I believe, is explained at Python urllib2 Basic Auth Problem
Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the servers don't do "totally standard authentication" then the libraries won't work.