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.
Related
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()}"
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 want to access Snov.io API but there is Error Unauthenticated. but I authenticated. and I can print Acces token too. am I missing anything here?
import requests
import json
def get_access_token():
params = {
'grant_type': 'client_credentials',
'client_id': '59e814b92ded8ed6b5537718495bf2a5',
'client_secret': '9cc7012893ff220c6935440b8e216ac1'
}
res = requests.post(
'https://api.snov.io/v1/oauth/access_token', data=params)
resText = res.text.encode('ascii', 'ignore')
return json.loads(resText)['access_token']
def user_lists(token):
params = {'access_token': token}
res = requests.get(
'https://api.snov.io/v1/get-user-campaigns', data=params)
return json.loads(res.text)
token = get_access_token()
resp = user_lists(token)
print(token)
print(resp)
get_access_token() is working fine . that's what I am assuming because it's return CODE 200 and access_toke also.
user_lists() return error
ERROR
<Response [401]>
I'm making a project which will add songs from your youtube playlist to spotify playlist. everything works fine except the add_item() method. I'm getting 404 : not found response from the requests object.
Yes, i checked if the song actually exists. It does and even printed the id of the song.So it exists.
I'm following the official documentation
here is my code -
import json
from requests_oauthlib import OAuth2Session
import requests
import base64
import urllib.parse as urlparse
from urllib.parse import parse_qs
client_id = #id
client_secret = #secret
redirect_uri = 'https://www.spotify.com'
scope = "playlist-modify-public user-read-email user-read-private playlist-modify-private"
req = f'{client_id}:{client_secret}'
encoded = base64.b64encode(req.encode())
class sp :
def __init__(self) :
self.get_token()
self.get_id()
self.uri_list = []
def get_token(self) :
url = 'https://accounts.spotify.com/authorize'
oauth = OAuth2Session(client_id, redirect_uri = redirect_uri, scope = scope)
authorization_url, state = oauth.authorization_url(url)
print(authorization_url)
authorization_response = input('paste here : ')
parsed = urlparse.urlparse(authorization_response)
authorization_code = parse_qs(parsed.query)['code'][0]
# to get auth token
headers = {
'Authorization' : f'Basic {encoded.decode()}'
}
data = {
'grant_type' : 'authorization_code',
'redirect_uri' : redirect_uri,
'code' : authorization_code
}
access = requests.post('https://accounts.spotify.com/api/token', data = data, headers = headers)
response = json.loads(access.text)
self.access_token = response['access_token']
def get_id(self) :
headers = {
'Authorization' : f'Bearer {self.access_token}'
}
user_info = requests.get('https://api.spotify.com/v1/me', headers = headers)
user_info.raise_for_status()
user_info = json.loads(user_info.text)
self.user_id = user_info['id']
def search(self) :
search_url = 'https://api.spotify.com/v1/search'
headers = {
'Authorization': f'Bearer {self.access_token}'
}
params = {
'q' : 'track:Memories artist:Maroon 5',
'type' : 'track',
'limit' : 1,
}
search_response = requests.get(search_url, headers = headers, params = params)
search_response.raise_for_status()
json_response = search_response.json()
song_uri = json_response['tracks']['items'][0]['uri']
self.uri_list.append(song_uri)
def create_playlist(self) :
create_playlist_url = f'https://api.spotify.com/v1/users/{self.user_id}/playlists'
headers = {
'Authorization' : f'Bearer {self.access_token}',
'Content-Type' : 'application/json'
}
data = json.dumps({
'name' : 'new playlist'
})
response = requests.post(create_playlist_url, headers = headers, data = data)
print(response)
self.playlist_id = response.json()['uri']
def add_items(self) :
add_items_url = f'https://api.spotify.com/v1/playlists/{self.playlist_id}/tracks'
headers = {
'Authorization' : f'Bearer {self.access_token}',
'Content-Type' : 'application/json'
}
print(self.uri_list)
data = {
'uris' : json.dumps(self.uri_list)
}
res = requests.post(add_items_url, headers = headers, data = data)
print(res)
user = sp()
user.create_playlist()
user.search()
user.add_items()
Any help is appreciated. Thanks
You have this line of code for playlist creation:
self.playlist_id = response.json()['uri']
and then in items addition logic you have:
add_items_url = f'https://api.spotify.com/v1/playlists/{self.playlist_id}/tracks'
are you sure that you want to use playlist uri as playlist id?
Could you update your question with more info:
response.json() value after playlist is created
print add_items_url after f-string was declared
UPDATE
https://developer.spotify.com/documentation/web-api/reference/playlists/create-playlist/ as I can see here - the response after creation of the playlist include id field
So you should just change this line
self.playlist_id = response.json()['uri']
to
self.playlist_id = response.json()['id']
I'm trying to create a python (3.7) code, that will create a new room at https://bingosync.com/.
Here is my code so far:
import requests
with open('bingosync.txt', 'r') as myfile:
jsonstring = myfile.read()
url = "https://bingosync.com/"
csrfToken = requests.Session().get(url).cookies['csrftoken']
params = {'csrfmiddlewaretoken': csrfToken, 'room_name' : 'test', 'passphrase' : 'test123', 'nickname' : 'testcode', 'game_type' : '18', 'custom_json' : jsonstring }
headers = {'x-csrftoken': csrfToken}
r = requests.Session().post(url, data = params, headers = headers)
print(r.content)
My problem is that, I'm getting 403 from the request, because of invalid/missing CSRF token
As far as I understand, I need to put the token into the headers, but it doesn't matter if I input
'x-csrftoken': csrfToken
or
'csrfmiddlewaretoken' : csrfToken
It wouldn't return me anything else than 403.