Reputation: 33
I am trying to use Spotify's API to get song details. My programming language is python and the code I am trying to execute is this:
def spotifysearch(searchterm):
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer OAUTH TOKEN',
}
params = (
('q', searchterm),
('type', 'track'),
('limit', '10'),
)
response = requests.get('https://api.spotify.com/v1/search', headers=headers, params=params)
a=response.json()
return a
However, my OAUTH TOKEN expires after every hour and I can't just manually get a new token every hour. I couldn't understand how to get my refresh token automatically.
Please provide me answer in either python or on curl (Both are fine with me)
Upvotes: 1
Views: 1858
Reputation: 764
Your first step will be to record:
You can use dataclasses for this. Dataclasses have a post_init func, which is executed after initialization. You should compute the expiry as a datetime there.
import dataclasses
@dataclasses.dataclass
class TToken:
access_token: str
refresh_token: str
created: datetime.datetime
expires: datetime.datetime
def __init_post__(self, data):
if data: # Not required
self.access_token = data['access_token']
self.created = datetime.datetime.utcnow()
self.expires = self.created + datetime.timedelta(minutes=59)
self.refresh_token = data['refresh_token']
def is_expired(self):
return datetime.datetime.utcnow() > self.expires
def as_header(self):
return {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': f'Bearer self.access_token',
}
For your tokens.
BASE64_CID_CSEC = <base64 encoded clientid:clientsecret>
def token_get(authorization_code: str):
data = {'form':{'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': <your redirect uri>},
'header':{'Authorization': f'Basic {BASE64_CID_CSEC}'}}
resp = requests.get('https://accounts.spotify.com/api/token', data=data['form'], headers=data['header'])
return TToken(resp)
def token_refresh(refresh_token: str):
data = {'form': {'grant_type': 'refresh_token', 'refresh_token': refresh_token},
'header': {'Authorization': f'Basic {BASE64_CID_CSEC}'}}
resp = requests.get('https://accounts.spotify.com/api/token', data=data['form'], headers=data['header'])
return TToken(resp)
Finally
token = token_get(authorization_code)
def spotify_search(searchterm: str):
if token.is_expired():
token = token_refresh(token.refresh_token)
params = (('q', searchterm),('type', 'track'),('limit', '10'))
resp = requests.get('https://api.spotify.com/v1/search', headers=token.as_header(), params=params)
return resp.json()
Upvotes: 1