Skip to main content

API? Spotify? Verify!

API? Spotify? Verify!
The APIs we've been using so far are pretty unusual in that they provide their service for free.

Normally, you have to pay to use an APIs data services (at least if you're doing so commercially). This means that you will need to verify your status as an approved user before you can get your grubby hands on all of that sweet, sweet data!

Today, we're learning how to write a program that tells an API that we've got an account before accessing its info.

Don't worry, you won't have to bust out the credit card. We're using a Spotify API that won't charge provided we keep our usage under a certain level.

Get started
👉 Click here to go to the Spotify developer page and log in/create an account.

👉 Next, hit create app and give it a name and description.




👉 Copy the client ID and insert it as a secret in your REPL. Make sure to call it CLIENT_ID.





Client Secret
👉 Back to Spotify and click show client secret (use your own, not the one in these screenshots, I'll have changed it by the time this goes out).



Again, copy and create a REPL secret for it - CLIENT_SECRET.


Now we have, effectively, the username and password that our program needs so that it can talk to Spotify.



Authenticate
Now we have access to a whole bunch of music related data. You can find and test all of the different category data on the spotify API page in the categories tab.

Connect to Spotify
👉 First though, we need to connect our program to Spotify. Step 1 is to import a bunch of libraries. Line 2 is a new library that authenticates our Spotify credentials against their API.



import requests, json, os
from requests.auth import HTTPBasicAuth

👉 Then bring in our secrets and assign to variables.


import requests, json, os
from requests.auth import HTTPBasicAuth

clientID = os.environ['CLIENT_ID']
clientSecret = os.environ['CLIENT_SECRET']



Authenticate
👉 Now to authenticate with Spotify's system. This is tricky the first time, but after that you'll have the code that you can reuse.

Authenticating gives you a token (a series of seemingly random numbers & letters) that is the 'I'm allowed in here' pass for your program.

There's a lot going on here. So, here's the breakdown:

I've set up variables to store the data needed for authentication.
url stores the web address to connect to
data creates a dictionary that communicates with the API in the correct way. It basically says to Spotify 'Send me back the credentials based in my client ID and secret. Here's a dictionary format to put them in'.
auth uses the new HTTPBasicAuth function to send your client ID and secret to Spotify as pretty much the username and password to log you in.
response stores the API key that will be returned by the requests function that sends Spotify the login info needed.
After that, I've added some print functions to output the info we get back for testing purposes.



url = "https://accounts.spotify.com/api/token"
data = {"grant_type":"client_credentials"}
auth = HTTPBasicAuth(clientID, clientSecret)

response = requests.post(url, data=data, auth=auth)

print(response.ok)
print(response.json())
print(response.status_code)

Whole code so far
Once I've tested the prints and I know that it's all working, I can remove them and extract the access token. Here's the whole code so far:


import requests, json, os
from requests.auth import HTTPBasicAuth

clientID = os.environ['CLIENT_ID']
clientSecret = os.environ['CLIENT_SECRET']

url = "https://accounts.spotify.com/api/token"
data = {"grant_type":"client_credentials"}
auth = HTTPBasicAuth(clientID, clientSecret)

response = requests.post(url, data=data, auth=auth)
accessToken = response.json()["access_token"]



Set up a search


👉 Now let's set up a search form Spotify. I've gone to the API page, selected console > search and grabbed the endpoint details.














 I've inserted it into my repl in the url variable (I can reuse it because it's done it's job of logging me in earlier). Additionally, I've set up a headers variable that will enable communication with the Spotify API using my access token as a pass.


url = "https://api.spotify.com/v1/search"
headers = {'Authorization': f'Bearer {accessToken}'}



       

Access Token
👉 Back to Spotify now, and let's search for an artist. Copy your access token (you may need to print it out again) and paste it into the OAuthToken box in Spotify. Then click request.


Fill in the details
👉 Now fill in the rest of the details in the Spotify search menu. You can see lots of examples of what to search for on the API reference page. Then click Try It and scroll down to see the JSON on the right of the screen.





Grab part of the query
👉 Next I'm going to grab part of the query from the Spotify page and bring it into a variable in my Repl. The part that I've grabbed specifies that I'm searching for tracks by 'Queen', and I only want to display 5 results.







search = "?q=artist%3Aqueen&type=track&limit=5"



The full query
Next, create the full query by concatenating the url and search variables. I've included the full code here. The new line is the last one.


import requests, json, os
from requests.auth import HTTPBasicAuth

clientID = os.environ['CLIENT_ID']
clientSecret = os.environ['CLIENT_SECRET']

url = "https://accounts.spotify.com/api/token"
data = {"grant_type":"client_credentials"}
auth = HTTPBasicAuth(clientID, clientSecret)

response = requests.post(url, data=data, auth=auth)

accessToken = response.json()["access_token"]

url = "https://api.spotify.com/v1/search"
headers = {'Authorization': f'Bearer {accessToken}'}
search = "?q=artist%3Aqueen&type=track&limit=5"

fullURL = f"{url}{search}"


 At last! Time to send that url off and get some results from it. I also need to send the headers to get authorization.

I've also used a loop to strip out just the track names and output them.

Preview the song
Spotify also includes a cool preview URL - a 30 second sample of the song, so I've added a link to that sample as part of the output.

response = requests.get(fullURL, headers=headers)

for track in data["tracks"]["items"]:
  print(track["name"])

Making this customizable
👉So how about making our search user customizable? In the code below, I have:

Asked the user to input an artist (line 14)
Tidied up their input (line 15)
formatted the search URL as an fString that includes the artist (line 19)
Here's the code:

import requests, json, os
from requests.auth import HTTPBasicAuth

clientID = os.environ['CLIENT_ID']
clientSecret = os.environ['CLIENT_SECRET']

url = "https://accounts.spotify.com/api/token"
data = {"grant_type":"client_credentials"}
auth = HTTPBasicAuth(clientID, clientSecret)

response = requests.post(url, data=data, auth=auth)
accessToken = response.json()["access_token"]

artist = input("Artist: ").lower()
artist = artist.replace(" ", "%20")

url = "https://api.spotify.com/v1/search"
headers = {'Authorization': f'Bearer {accessToken}'}
search = f"?q=artist%3A{artist}&type=track&limit=5"

fullURL = f"{url}{search}"

response = requests.get(fullURL, headers=headers)
print(json.dumps(data, indent=2))  

for track in data["tracks"]["items"]:
  print(track["name"])
  print(track["preview_url"])

Comments

Popular posts from this blog

ALL ABOUT WHILE LOOP

 WHILE LOOP  A  while  loop allows your code to repeat itself based on a condition you set.   EXAMPLE : counter = 0 while counter < 10:   print(counter)   counter +=1 Infinite Loop  You have to be  really  careful that you don't accidentally invoke an infinite loop! This is where the computer will loop code until the end of time. Without a break. Forever.  This is just saying "count to 10 by 1 each time." to make the loop end. Don't forget, if your  condition  is a  >  then you might need to  -= . This will subtract from the variable instead of adding to it.   EXAMPLE : counter = 0 while counter < 10:   print(counter)    counter += 1

WHAT IS ELIF

  What the elif is this? The  elif  command (which stands for 'elseif') allows you to ask 2, 3, 4 or 142 questions using the same input! This command must be in a certain place. You can have as many  elif  statements as you want, but they  must  go in between  if  and  else  and have the same indentation. The  print  statements in your  elif  command need to line up with the indent of the other  print  statements. EXAMPLE :  print("SECURE LOGIN") username = input("Username > ") password = input("Password> ") if username == "mark" and password == "password":  print("Welcome Mark!") elif username == "suzanne":  print("Hey there Suzanne!") else:  print("Go away!") E

Automate! Automate!

 Making this customizable 👉So how about making our search user customizable? In the code below, I have: Asked the user to input an artist (line 14) Tidied up their input (line 15) formatted the search URL as an fString that includes the artist (line 19) Here's tAutomate! Automate! We are so close. I can taste it, folks! Massive kudos on getting this far! Today's lesson, however, will work best if you have one of Replit's paid for features (hacker plan or cycles). Free plan Repls 'fall asleep' after a while. Automation kinda relies on the Repl being always on. If you have hacker plan or you've bought some cycles, then you can enable always on in the drop down menu that appears when you click your Repl name (top left).he code: This is important because when our repl is always running, it can keep track of time and schedule events. 👉 I've set up a simple schedule that prints out a clock emoji every couple of seconds. It works like this: Import schedule librar