spotify_apis.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. import requests, spotipy
  2. from api_authentication import spotify_auth, get_aws_secret
  3. # set global authentication for spotify API
  4. # credentials are stored in AWS Secret Manager.
  5. cred = get_aws_secret("hpg-keys","us-west-2")["spotify"]
  6. token=spotify_auth(
  7. client_id=cred['clientid'],
  8. client_secret=cred['clientsecret'],
  9. user=cred['user'])
  10. AUTH={'Authorization': f'Bearer {token}'}
  11. # spotify APIs wrapped into functions
  12. def get_track_uri(artist, track):
  13. # given an artist and song title, return the top track uri
  14. kw = f"track:{track}%20artist:{artist}"
  15. url = f"https://api.spotify.com/v1/search?q={kw}&type=track&limit=1"
  16. r = requests.get(url=url, headers=AUTH)
  17. # parse for track uri
  18. try:
  19. uri = r.json()['tracks']['items'][0]['uri']
  20. return uri
  21. except Exception:
  22. print(f"Could not find a match for {artist} - {track}")
  23. return None
  24. def replace_tracks(playlist, tracks):
  25. # given a list of track uris, replace playlist with all those tracks
  26. url = f"https://api.spotify.com/v1/playlists/{playlist}/tracks"
  27. requests.put(url=url, headers=AUTH, json={"uris": tracks})
  28. return