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

WHAT IS Nesting

 WHAT IS Nesting  Nesting is where we put an  if  statement within an  if  statement using the power of indenting. The second  if  statement within the first  if  statement must be indented and its  print  statement needs to be indented one more time.  EXAMPLE:

IF AND ELSE STATEMENT

  If Statements    These statements are a bit like asking a question. You are telling the computer:  if  something is true,  then  do this specific block of code. Double equals ( == ) is asking the computer to compare if these two things are  exactly  the same.  EXAMPLE :  myName = input("What's your name?: ") if myName == "David":  What is else? IF  the condition is  not  met with the  if  statement, then we want the computer to do the  else  part instead. Likewise, if the condition  is  met in the  if  statement, then the  else  bit is ignored by the computer. The  else  statement must be the first thing  unindented  after the  if  statement and in line with it    EXAMPLE :  myName = input("What's your name?: ") if myName == "David":  print("Welcome Dude!")  print("You're just the baldest dude I've ever seen...

FOR LOOP , RANGE

  FOR LOOP  A  while  loop is perfect to use when we  don't  know how many times we want the loop to repeat.  If we have an idea of how many times we want the loop to repeat, we can use a  for  loop to loop code in exactly the same way the  while  loop did.  EXAMPLE :  for counter in range(10):   print(counter) RANGE  The  range  function creates a list of numbers in the range you create. If you only give it one number, it will start at  0  and move to a state where the final number is  one less  than the number in the brackets. In this case, the final number would be  9 .  EXAMPLE :  total = 0 for number in range(100) :   total += number   print(total)