-
Notifications
You must be signed in to change notification settings - Fork 0
/
spotify.py
199 lines (150 loc) · 6.49 KB
/
spotify.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import base64
import json
import requests
import sys
import urllib.parse as urllibparse
import config
'''
--------------------- HOW THIS FILE IS ORGANIZED --------------------
0. SPOTIFY BASE URL
1. USER AUTHORIZATION
2. ARTISTS
3. SEARCH
4. USER RELATED REQUESTS (NEEDS OAUTH)
'''
# ----------------- 0. SPOTIFY BASE URL ----------------
SPOTIFY_API_BASE_URL = 'https://api.spotify.com'
API_VERSION = "v1"
SPOTIFY_API_URL = "{}/{}".format(SPOTIFY_API_BASE_URL, API_VERSION)
# ----------------- 1. USER AUTHORIZATION ----------------
# Spotify endpoints
SPOTIFY_AUTH_BASE_URL = "https://accounts.spotify.com/{}"
SPOTIFY_AUTH_URL = SPOTIFY_AUTH_BASE_URL.format('authorize')
SPOTIFY_TOKEN_URL = SPOTIFY_AUTH_BASE_URL.format('api/token')
# Client keys
CLIENT = config.config()
CLIENT_ID = CLIENT.spotify_client_id
CLIENT_SECRET = CLIENT.spotify_client_secret
# Server-side
CLIENT_SIDE_URL = "http://127.0.0.1:5000"
REDIRECT_URI = "{}/callback/".format(CLIENT_SIDE_URL)
SCOPE = "playlist-read-private playlist-modify-public playlist-modify-private user-read-recently-played user-top-read"
STATE = ""
SHOW_DIALOG_bool = True
SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower()
# https://developer.spotify.com/web-api/authorization-guide/
auth_query_parameters = {
"response_type": "code",
"redirect_uri": REDIRECT_URI,
"scope": SCOPE,
# "state": STATE,
# "show_dialog": SHOW_DIALOG_str,
"client_id": CLIENT_ID
}
URL_ARGS = "&".join(["{}={}".format(key, urllibparse.quote(val))
for key, val in list(auth_query_parameters.items())])
AUTH_URL = "{}/?{}".format(SPOTIFY_AUTH_URL, URL_ARGS)
def authorize(auth_token):
code_payload = {
"grant_type": "authorization_code",
"code": str(auth_token),
"redirect_uri": REDIRECT_URI
}
#python 3 or above
if sys.version_info[0] >= 3:
base64encoded = base64.b64encode(("{}:{}".format(CLIENT_ID, CLIENT_SECRET)).encode())
headers = {"Authorization": "Basic {}".format(base64encoded.decode())}
else:
base64encoded = base64.b64encode("{}:{}".format(CLIENT_ID, CLIENT_SECRET))
headers = {"Authorization": "Basic {}".format(base64encoded)}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload,
headers=headers)
# tokens are returned to the app
response_data = json.loads(post_request.text)
access_token = response_data["access_token"]
# use the access token to access Spotify API
auth_header = {"Authorization": "Bearer {}".format(access_token)}
return auth_header
# ---------------- 2. ARTISTS ------------------------
# https://developer.spotify.com/web-api/artist-endpoints/
GET_ARTIST_ENDPOINT = "{}/{}".format(SPOTIFY_API_URL, 'artists') # /<id>
# https://developer.spotify.com/web-api/get-artist/
def get_artist(artist_id):
url = "{}/{id}".format(GET_ARTIST_ENDPOINT, id=artist_id)
resp = requests.get(url)
return resp.json()
# https://developer.spotify.com/web-api/get-several-artists/
def get_several_artists(list_of_ids):
url = "{}/?ids={ids}".format(GET_ARTIST_ENDPOINT, ids=','.join(list_of_ids))
resp = requests.get(url)
return resp.json()
# https://developer.spotify.com/web-api/get-artists-albums/
def get_artists_albums(artist_id):
url = "{}/{id}/albums".format(GET_ARTIST_ENDPOINT, id=artist_id)
resp = requests.get(url)
return resp.json()
# https://developer.spotify.com/web-api/get-artists-top-tracks/
def get_artists_top_tracks(artist_id, country='US'):
url = "{}/{id}/top-tracks".format(GET_ARTIST_ENDPOINT, id=artist_id)
myparams = {'country': country}
resp = requests.get(url, params=myparams)
return resp.json()
# https://developer.spotify.com/web-api/get-related-artists/
def get_related_artists(artist_id):
url = "{}/{id}/related-artists".format(GET_ARTIST_ENDPOINT, id=artist_id)
resp = requests.get(url)
return resp.json()
# ----------------- 3. SEARCH ------------------------
# https://developer.spotify.com/web-api/search-item/
SEARCH_ENDPOINT = "{}/{}".format(SPOTIFY_API_URL, 'search')
# https://developer.spotify.com/web-api/search-item/
def search(search_type, name):
if search_type not in ['artist', 'track', 'album', 'playlist']:
print('invalid type')
return None
myparams = {'type': search_type}
myparams['q'] = name
resp = requests.get(SEARCH_ENDPOINT, params=myparams)
return resp.json()
# ------------------ 4. USER RELATED REQUESTS ---------- #
# spotify endpoints
USER_PROFILE_ENDPOINT = "{}/{}".format(SPOTIFY_API_URL, 'me')
USER_PLAYLISTS_ENDPOINT = "{}/{}".format(USER_PROFILE_ENDPOINT, 'playlists')
USER_TOP_ARTISTS_AND_TRACKS_ENDPOINT = "{}/{}".format(
USER_PROFILE_ENDPOINT, 'top') # /<type>
USER_RECENTLY_PLAYED_ENDPOINT = "{}/{}/{}".format(USER_PROFILE_ENDPOINT,
'player', 'recently-played')
BROWSE_FEATURED_PLAYLISTS = "{}/{}/{}".format(SPOTIFY_API_URL, 'browse',
'featured-playlists')
# https://developer.spotify.com/web-api/get-users-profile/
def get_users_profile(auth_header):
url = USER_PROFILE_ENDPOINT
resp = requests.get(url, headers=auth_header)
return resp.json()
# https://developer.spotify.com/web-api/get-a-list-of-current-users-playlists/
def get_users_playlists(auth_header):
url = USER_PLAYLISTS_ENDPOINT+'?offset=0&limit=50'
resp = requests.get(url, headers=auth_header)
return resp.json()
# https://developer.spotify.com/web-api/get-users-top-artists-and-tracks/
def get_users_top(auth_header, t):
if t not in ['artists', 'tracks']:
print('invalid type')
return None
url = "{}/{type}".format(USER_TOP_ARTISTS_AND_TRACKS_ENDPOINT, type=t)
resp = requests.get(url, headers=auth_header)
print(resp)
# https://developer.spotify.com/web-api/web-api-personalization-endpoints/get-recently-played/
def get_users_recently_played(auth_header):
url = USER_RECENTLY_PLAYED_ENDPOINT
resp = requests.get(url, headers=auth_header)
return resp.json()
# https://developer.spotify.com/web-api/get-list-featured-playlists/
def get_featured_playlists(auth_header):
url = BROWSE_FEATURED_PLAYLISTS
resp = requests.get(url, headers=auth_header)
return resp.json()
def get_playlist_tracks(user_id, playlist_id, auth_header):
url = "{}/users/{userid}/playlists/{id}/tracks?offset=0&limit=50".format(SPOTIFY_API_URL, userid = user_id, id=playlist_id)
resp = requests.get(url, headers=auth_header)
return resp.json()