I am working with the Spotify API. I am trying to generate an access token. I followed along https://www.youtube.com/watch?v=xdq6Gz33khQ this video to generate the token.
I am getting an error
{'error': 'invalid_client'}
The code I have written is:
import base64
from wsgiref import headers
import requests
import json
client_id = "09e0b9beeba74aee986546f496823d60"
client_secret = "be1c93f2a446477e8416235b2a3f442c"
# searching for token which will help in authorization
client_creds = f"{client_id} : {client_secret}"
client_creds_b64 = base64.b64encode(client_creds.encode())
token_url = "https://accounts.spotify.com/api/token"
method = "POST"
token_data = {
"grant_type": "client_credentials"
}
token_header = {
"Authorization" : f"Basic {client_creds}" # <base64 encoded client_id:client_secret>
}
r = requests.post(token_url, data=token_data, headers=token_header)
print(r.json())
Not sure why I get this error. It could be the link I am using for the token url but can't find what to replace it with.
change
client_creds = f"{client_id} : {client_secret}"
to
client_creds = f"{client_id}:{client_secret}"
change
"Authorization" : f"Basic {client_creds}" # <base64 encoded client_id:client_secret>
to
"Authorization": f"Basic {client_creds_b64.decode()}"
Related
The documentation of the API is here, and I try to implement this line in python
//retrieve entries created on a specific day (use the date_created field)
//this example returns entries created on September 10, 2019
https://localhost/wp-json/gf/v2/entries?search={"field_filters": [{"key":"date_created","value":"09/10/2019","operator":"is"}]}
But when I try to do with python in the following code, I got an error:
import json
import oauthlib
from requests_oauthlib import OAuth1Session
consumer_key = ""
client_secret = ""
session = OAuth1Session(consumer_key,
client_secret=client_secret,signature_type=oauthlib.oauth1.SIGNATURE_TYPE_QUERY)
url = 'https://localhost/wp-json/gf/v2/entries?search={"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}'
r = session.get(url)
print(r.content)
The error message is :
ValueError: Error trying to decode a non urlencoded string. Found invalid characters: {']', '['} in the string: 'search=%7B%22field_filters%22:%20[%7B%22key%22:%22date_created%22,%22value%22:%2209/01/2023%22,%22operator%22:%22is%22%7D]%7D'. Please ensure the request/response body is x-www-form-urlencoded.
One solution is to parameterize the url:
import requests
import json
url = 'https://localhost/wp-json/gf/v2/entries'
params = {
"search": {"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}
}
headers = {'Content-type': 'application/json'}
response = session.get(url, params=params, headers=headers)
print(response.json())
But in the retrieved entries, the data is not filtered with the specified date.
In the official documentation, they gave a date in this format "09/01/2023", but in my dataset, the format is: "2023-01-10 19:16:59"
Do I have to transform the format ? I tried a different format for the date
date_created = "09/01/2023"
date_created = datetime.strptime(date_created, "%d/%m/%Y").strftime("%Y-%m-%d %H:%M:%S")
What alternative solutions can I test ?
What if you use urllib.parse.urlencode function, so your code would looks like:
import json
import oauthlib
from requests_oauthlib import OAuth1Session
import urllib.parse
consumer_key = ""
client_secret = ""
session = OAuth1Session(consumer_key,
client_secret=client_secret,signature_type=oauthlib.oauth1.SIGNATURE_TYPE_QUERY)
params = {
"search": {"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}
}
encoded_params = urllib.parse.urlencode(params)
url = f'https://localhost/wp-json/gf/v2/entries?{encoded_params}'
r = session.get(url)
print(r.content)
hope that helps
I had the same problem and found a solution with this code:
params = {
'search': json.dumps({
'field_filters': [
{ 'key': 'date_created', 'value': '2023-01-01', 'operator': 'is' }
],
'mode': 'all'
})
}
encoded_params = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
url = 'http://localhost/depot_git/wp-json/gf/v2/forms/1/entries?' + encoded_params + '&paging[page_size]=999999999' # nombre de réponses par page forcé manuellement
I'm not really sure what permitted it to work as I'm an absolute beginner with Python, but I found that you need double quotes in the URL ( " ) instead of simple quotes ( ' ), so the solution by William Castrillon wasn't enough.
As for the date format, Gravity Forms seems to understand DD/MM/YYYY. It doesn't need a time either.
I'm writing code to access the MS365 API and the Python code example uses urllib. I want to instead use requests but I'm not sure how urllib translates into requests as my attempts of doing so have failed.
The code example can be found here:
https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/run-advanced-query-sample-python?view=o365-worldwide#get-token
import json
import urllib.request
import urllib.parse
tenantId = '00000000-0000-0000-0000-000000000000' # Paste your own tenant ID here
appId = '11111111-1111-1111-1111-111111111111' # Paste your own app ID here
appSecret = '22222222-2222-2222-2222-222222222222' # Paste your own app secret here
url = "https://login.microsoftonline.com/%s/oauth2/token" % (tenantId)
resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
body = {
'resource' : resourceAppIdUri,
'client_id' : appId,
'client_secret' : appSecret,
'grant_type' : 'client_credentials'
}
data = urllib.parse.urlencode(body).encode("utf-8")
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
jsonResponse = json.loads(response.read())
aadToken = jsonResponse["access_token"]
IIUC, this should work the same:
import requests
tenantId = '00000000-0000-0000-0000-000000000000' # Paste your own tenant ID here
appId = '11111111-1111-1111-1111-111111111111' # Paste your own app ID here
appSecret = '22222222-2222-2222-2222-222222222222' # Paste your own app secret here
url = "https://login.microsoftonline.com/%s/oauth2/token" % (tenantId)
resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
params = {
'resource' : resourceAppIdUri,
'client_id' : appId,
'client_secret' : appSecret,
'grant_type' : 'client_credentials'
}
response = requests.get(url, params)
jsonResponse = response.json()
aadToken = jsonResponse["access_token"]
Modifying #BeRT2me's answer has made this work.
import requests
tenantId = '00000000-0000-0000-0000-000000000000' # Paste your own tenant ID here
appId = '11111111-1111-1111-1111-111111111111' # Paste your own app ID here
appSecret = '22222222-2222-2222-2222-222222222222' # Paste your own app secret here
url = "https://login.microsoftonline.com/%s/oauth2/token" % (tenantId)
resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
data = {
'resource' : resourceAppIdUri,
'client_id' : appId,
'client_secret' : appSecret,
'grant_type' : 'client_credentials'
}
response = requests.post(url=url, data=data)
jsonResponse = response.json()
aadToken = jsonResponse["access_token"]
I am trying to call an API using an access token.
Currently I am getting the token like so:
import requests
auth_url = "https://oauth.thegivenurl.com/connect/token"
client_id = "SomeClient_ID"
client_secret = "SomeClient_Secret"
scope = "SomeScope"
grant_type = "client_credentials"
data = {
"grant_type": grant_type,
"client_id": client_id,
"client_secret": client_secret,
"scope": scope
}
auth_response = requests.post(auth_url, data=data)
print(auth_response.content)
This produces something like the following:
{"access_token":"eyJhbGdiOihSUzh1NhIsImtpZCI6IjlVUHVwYnBkTXN2RDZ0Ry1ZcDVRUlEiLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE2MzM4OTcxNDIsImV4cCI6hTYzMhkwMDc0MiwiaXNzIjoiaHR0cHM6Ly9vYXV0aC56YW1iaW9uLmNvbSIsImF1ZCI6ImFwaTEiLCJjbGllbnRfaWQiOiIwN0I3RkZEOC1GMDJCLTRERDAtODY2OS0zRURBNzUyRTMyNkQiLCJzY29wZSI6WyJhcGkxIl19.GU6lynvQYAAmycEPKbLgHE-Ck189x-a-rVz6QojkBIVpSLu_sSAX2I19-GlTjVWeLKoMVxqEfVq_qIaaQYa5KFmMLHRxP6J-RUgGK8f_APKjX2VNoMyGyAbZ0qXAJCvUTh4CPaRbZ6pexEishzr4-w3JN-hJLiv3-QH2y_JZ_V_KoAyu8ANupIog-Hdg8coI3wyh86OeOSAWJA1AdkK5kcuwC890n60YVOWqmUiAwPRQrTGh2mnflho2O3EZGkHiRPsiJgjowheD9_Wi6AZO0kplHiJHvbuq1PV6lwDddoSdAIKkDscB0AF53sYlgJlugVbtU0gdbXjdyBZvUjWBgw","expires_in":3600,"token_type":"Bearer","scope":"api1"}
Now I would like to call the API and pass the token in a header, but I am unsure how to do this and I have had a couple of goes at online resources
One of my attempts were:
url = "https://anotherurl.com/api/SecuredApi/StaffDetails"
head = {'Authorization': 'token {}'.format(auth_response)}
response = requests.get(url, headers=head)
print(response)
but this gives me a 403 error
Please assist me with pointing out my error
EDIT:
Thanks to #RaniSharim I have made some changes. I now have
import requests
import json
auth_url = "https://oauth.thegivenurl.com/connect/token"
client_id = "SomeClient_ID"
client_secret = "SomeClient_Secret"
scope = "SomeScope"
grant_type = "client_credentials"
data = {
"grant_type": grant_type,
"client_id": client_id,
"client_secret": client_secret,
"scope": scope
}
dateparams = {
"StartDateTime": "2021-01-01 00:00:00",
"EndDateTime" : "2021-10-11 23:59:00"
}
auth_response = requests.post(auth_url, data=data)
# print(auth_response.content)
authjson = auth_response.content
authdata = json.loads(authjson)
token = (authdata['access_token'])
# print(token)
head = {"Authorization": "Bearer " + token}
response = requests.get(url, headers=head, params=dateparams)
print(response.content)
This looks better but I am now getting a 400 error:
"message":"The date range you have specified is in an invalid format. The required format is yyyy-MM-dd HH:mm:ss","status":400}
As best I can see my date ranges are already in the requested format, as set here:
dateparams = {
"StartDateTime": "2021-01-01 00:00:00",
"EndDateTime" : "2021-10-11 23:59:00"
}
Normally, 400 means front-end error, but when you do GET request
dateparams = {
"StartDateTime": "2021-01-01 00:00:00",
}
r = requests.get(url, params=dateparams)
print(r.url)
GET url will turn into sth like this:
https://oauth.thegivenurl.com/connect/token?StartDateTime=2021-01-01+00%3A00%3A00
see the str
2021-01-01+00%3A00%3A00
So if back-end can't handle this right, you'll get this error too
but you can use GET in another way:
requests.get(url, json=dateparams)
This will send your json params perfectly
I am trying to send a message via Firebase to a certain client. This is my current (test) code:
import json
import requests
import urllib
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Content-Type': 'application/json', 'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
payload = json.dumps(payload)
res = requests.post(server, headers=headers, json=payload)
return res
which produces the following error, returned by Firebase:
JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0.
The following JSON sent to Firebase seems correct to me:
{
"data": {
"type":"dataUpdate"
},
"to":"xxx"
}
which is in the format described by the Firebase documentation. Any idea why Firebase doesn't accept the given data?
When you use json=payload as a parameter to requests.post() you don't need to specify 'Content-Type': 'application/json' in the header. In addition, you are passing a string when the parameter should be payload as a dict (ie. no need for json.dumps())
Try this:
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
res = requests.post(server, headers=headers, json=payload)
return res
I want to get refresh token from Dailymotion API by this code
def get_refresh_token(code):
platform = Platform.objects.get(name='Dailymotion')
secret_key = platform.secret_key
api_key = platform.api_key
redirect_uri = platform.callback_url
params = {
'code' : code,
'client_id' : api_key,
'client_secret' : secret_key,
'grant_type':'authorization_code',
'redirect_uri':redirect_uri
}
r = requests.post('https://api.dailymotion.com/oauth/token',data=params)
print (r.json())
print(code)
print(r.data)
refresh_token = r.json().get('refresh_token')
return refresh_token
but it's not working. the error is : {'error_description': 'Invalid authorization code.', 'error': 'invalid_grant'}
.I tried with the same code,grant_type... post from Chrome extensions and it works. What did i do wrong with python code?
def get_refresh_token(self, code):
args = {
'grant_type': 'refresh_token',
'refresh_token': code,
'client_id': DAILYMOTION_API_KEY,
'client_secret': DAILYMOTION_API_SECRET,
}
url = 'https://api.dailymotion.com/oauth/token'
data = urllib.urlencode(args)
request = urllib2.Request(url, data)
response = urllib2.urlopen(request)
html = response.read()
obj_Response = literal_eval(html)
return obj_Response
while getting AccessToken we get a parameter 'code' here we have to put that value in place of code.