Spotify refresh token in Python 3 - python

I am attempting to get a refresh token and use it to request a new access token when the temporary access token expires.
Spotify's documentation states the response body should contain the following json data:
{
"access_token": "NgCXRK...MzYjw",
"token_type": "Bearer",
"scope": "user-read-private user-read-email",
"expires_in": 3600,
"refresh_token": "NgAagA...Um_SHo"
}
However, using my code below only provides the following:
{
"access_token": "xxxx....",
"token_type": "Bearer",
"expires_in": 3600
}
I am using the following function to request an access token:
def get_access_token(client_id, client_secret): # getting access token from spotify using client ID
# Encoding Client ID and Client Secret in Base64
token_url = "https://accounts.spotify.com/api/token"
client_creds = f"{client_id}:{client_secret}"
client_creds_b64 = base64.b64encode(client_creds.encode())
token_data = {
"grant_type": "client_credentials"
}
token_headers = {
'Authorization': f"Basic {client_creds_b64.decode()}"
}
r = requests.post(token_url, data=token_data, headers=token_headers)
valid_request = r.status_code in range(200, 299)
token_response_data = r.json()
# pretty print response body
print(json.dumps(token_response_data, indent=2)) # response 200 -> successful attempt
if valid_request:
access_token = token_response_data['access_token']
return access_token
I am unsure why the scope and refresh token are missing from the response body. How can I alter this function to include these?
Thanks in advance for your time!
Spotify documentation: https://developer.spotify.com/documentation/general/guides/authorization/code-flow/

Altering the token data fixes this:
token_data = {
"grant_type": "authorization_code",
"code": "xxxx....",
"redirect_uri": "your redirect uri from Spotify for devs"
}
You need to set up a redirect uri on Spotify for devs, then encode it to use it as a parameter.
To get the 'code' parameter fill-out this URL with your data and you will be redirected to your redirect uri.
https://accounts.spotify.com/authorize?client_id=YOUR CLIENT ID&response_type=code&redirect_uri=YOUR ENCODED REDIRECT URI&scope=playlist-modify-public%20playlist-modify-private
The code will then be in the search bar to copy/paste. It should look something like this:
https://your redirectURI?code=xxx.....
Here is a good video guide for reference:
https://www.youtube.com/watch?v=-FsFT6OwE1A&ab_channel=EuanMorgan

Related

send post request to itunes Reporter

I am trying to send a POST request to Itunes reporter API to download a sales report: https://help.apple.com/itc/appsreporterguide/#/apd68da36164
In the queryInput, I pass in "1234" which is the vendorId.
import requests
headers = { "access_token": "123"}
json_data = {
"version": "1.0",
"mode": "Test",
"queryInput": "[p=Reporter.properties, Sales.getReport, 1234, Sales, Summary, Daily, 20230101]"
}
response = requests.post('https://reportingitc-reporter.apple.com/reportservice/sales/v1',
headers=headers, json=json_data)
#content = response.json()
print(response.content, response.status_code)
However, looks like the way I am passing parameters is incorrect because I only get this as the response:
b'' 400
I am certain that the access token is correct but not sure if i am passing it correctly.

How to exchange code for access token with Reddit API

I'm sure this is a broader question that applies to more than just Reddit, but currently I am attempting to exchange a code for a user access token however I am not understanding how to implement the following steps:
https://github.com/reddit-archive/reddit/wiki/OAuth2#retrieving-the-access-token
If you didn't get an error and the state value checks out,
you may then make a POST request with code to the following URL to retrieve your access token:
https://www.reddit.com/api/v1/access_token
Include the following information in your POST data (NOT as part of the URL)
grant_type=authorization_code&code=CODE&redirect_uri=URI
Okay, so what I did was this:
headers = {
CLIENT_ID: CLIENT_SECRET,
}
r = requests.post(
url="https://www.reddit.com/api/v1/access_token",
data={
"grant_type": "authorization_code",
"code": code,
"redirect_uri": "http://127.0.0.1:5000/callback"
},
headers=headers
)
I think I am failing with the headers, I receive a 429 error, and I don't think I've understood how to arrange the headers correctly as it doesn't clearly explain in the above link.
The "user" is the client_id. The "password" for confidential clients is the client_secret. The "password" for non-confidential clients (installed apps) is an empty string.
CLIENT_ID and CLIENT_SECRET are obviously variables, and they are my Reddit App dev credentials.
EDIT:
I came up with this, it's gross but it seems to work
headers = {
"User-Agent": "MyApp v1.0",
"Authorization": "Basic " + str(base64.b64encode(str.encode(f"{CLIENT_ID}:{CLIENT_SECRET}")))[2:-1],
}
Is there a cleaner way to write that?
Final answer, using an inbuilt method in Python's request:
client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
r = requests.post(
url="https://www.example.com/api/v1/access_token",
auth=client_auth,
data={
"grant_type": "authorization_code",
"code": code,
"redirect_uri": "http://127.0.0.1:5000/callback"
},
headers={
"User-Agent": "MyApp v1.0",
}
)

Error 404 api azure translator basic program python

I started a translator project on azure.
I copy the simple test code.
import os, requests, uuid, json
subscription_key = 'KEY_IN_PORTAL_AZURE'
endpoint = 'URL_IN_PORTAL_AZURE'
path = '/translate?api-version=3.0'
params = '&from=fr&to=en'
constructed_url = endpoint + path + params
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
body = [{
'text' : 'Bonjour'
}]
request = requests.post(constructed_url, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, indent=4,
ensure_ascii=False, separators=(',', ': ')))
I change the key and the endpoint but the program return
{
"error": {
"code": "404",
"message": "Resource not found"
}
}
I delete the service and i retry same thing
There're 2 errors in the sample code.
Error 1: for the endpoint, use this one instead of copying the one from azure portal:
endpoint = 'https://api.cognitive.microsofttranslator.com/'
Error 2: in headers, please add Ocp-Apim-Subscription-Region, and it's value is the region of the Cognitive Services resource. Like below:
'Ocp-Apim-Subscription-Region':'EastUS'
You can get the region from azure portal, the screenshot is as below:
And I tested it at my side, it worked. The result as below:

FCM api 'Bad request 400' error

I'm trying to implement sending notifications via new FCM api protocols. I went through authenticating requests, I enabled api in google console as well. Now when I send request I'm receiving Bad request 400 error. Response doesn't contain any other information than error code and error message. Even reason field says 'Bad Request'. I'm implementing it with FCM api docs.
def fcm_test():
FCM_URL = "https://fcm.googleapis.com/v1/projects/MY_PROJECT_NAME/messages:send"
my_token = "device-token"
payload = {
"massage": {
"token": my_token,
"notification": {
"body": "body",
"title": "title"
}
}
}
payload = json.dumps(payload)
headers = {
"Authorization": "Bearer {auth_token}".format(auth_token=_get_authentication_token()),
"Content-Type": "application/json; UTF-8",
}
try:
request = moves.urllib.request.Request(FCM_URL, payload.encode('utf-8'), headers)
response = moves.urllib.request.urlopen(request, timeout=10)
except Exception as e:
pass
return
There's a typo in your payload key, can you try it again with "message" instead of "massage"?

Can not parse JSON share document.\nRequest body:\n\nError:\nnull

I am trying to send a request to Linkedin's rest share api. I have been receiving this error message:
{
"errorCode": 0,
"message": "Can not parse JSON share document.\nRequest body:\n\nError:\nnull",
"requestId": "ETX9XFEI7N",
"status": 400,
"timestamp": 1437910620120
}
The request is send through the following python code:
import requests,json
auth_token = "some auth token"
url = "https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token="+auth_token
headers = {'content-type': 'application/x-www-form-urlencoded','x-li-format':'json'}
data = {
"comment":"Check out developer.linkedin.com!",
"content":{
"title": "LinkedIn Developers Resources",
"description": "Leverage LinkedIn's APIs to maximize engagement",
"submitted-url": "https://developer.linkedin.com",
"submitted-image-url": "https://example.com/logo.png"
},
"visibility":{
"code": "anyone"
}
}
response = requests.post( url , json= data , headers=headers )
return HttpResponse( response )
I made sure that I followed all the instructions in their documentation and can't find the mistake I am making.
Note: i have tried json=data and data=data both are not working
Remove content-type from the headers dictionary.
requests sets the correct Content-Type when using the json keyword argument.
You have three basic problems:
Please read the documentation on oauth2; because you are not passing in the token correctly.
The share URL does not take a oauth2_token argument.
You have the wrong content-type header.

Categories

Resources