Spotify Web API Introduction

Agenda

  • About Spotify Web API
  • Steps to build an application
    • Explore the functionality of Spotify Web APIs
    • Create and register your application
    • Learn about authorization
    • Understanding the object model
  • ​Let's code!
  • Summary

About

Spotify Web API

With Spotify Web API, you could:

Spotify Web API is:

  • RESTful
  • JSON formatted
  • OAuth 2.0
{
  "album_type": "album",
  "artists": [ {
    "name": "Linkin Park",
    ...
  } ],
  "name" : "Meteora Live Around The World",
  "release_date" : "2012-06-05",
  "tracks" : {...},
  "uri" : "spotify:album:4flcwtqnLoKZJ2wrCp1aJq",
  ...
}
GET https://api.spotify.com/v1/albums/4flcwtqnLoKZJ2wrCp1aJq/tracks
POST https://api.spotify.com/v1/users/johnliu55tw/playlists

Steps to

Build an application Using

Spotify Web API

Steps

  • Explore the functionality
  • Create and register your application
  • Learn about authorization
  • Understand object model

Spotify Developer

Explore the functionality

  • User guides and tutorials
  • API reference documents
  • Interactive API console
  • Examples
  • ...

Create your application

  • Client ID
  • Client Secret
  • Redirect URIs

Authorization

  • All endpoints
  • 3 authorization flows:

OAuth 2.0 (RFC-6749)

Authorization

  • Scope
  • None (public data only)
  • user-library-read
  • user-modify-playback-state
  • ...
  • List of scopes

OAuth 2.0 (RFC-6749)

Object Model

  • JSON
  • Pagination (paging object)
  • Full/simplified object
    • tracks in an album

Object Model

  • Common data objects
  • Container objects
  • Error objects

Object Model

Common data object model

  • album
  • artist
  • track
  • ...

Object Model

Example: track

  • href key pointing to either self or the full object
  • Properties of the object itself (name, id, ...)
  • Related objects in simplified version
    • artists of a track
    • album of a track
{
  "album" : {...},
  "artists" : [...],
  "href" : "https://api.spotify.com/v1/tracks/60a0Rd6pjrkxjPbaKzXjfq",
  "id" : "60a0Rd6pjrkxjPbaKzXjfq",
  "name" : "In The End",
  "popularity" : 86,
  "type" : "track",
  "uri" : "spotify:track:60a0Rd6pjrkxjPbaKzXjfq",
  ...
}

Object Model

Container object model

Object Model

Paging object

  • Offset-based pagination
  • items
  • Useful keys:
    • next
    • previous
    • total
{
  "href": ".../v1/albums/{id}/tracks?offset=0&limit=2",
  "items": [ {
    ...
  } ],
  "limit": 2,
  "next": ".../v1/albums/{id}/tracks?offset=2&limit=2",
  "offset": 0,
  "previous": null,
  "total": 11
}

Object Model

Error object model

Object Model

Authentication error object

  • Error occurred during the authentication/authorization
  • Follows RFC-6749
{
    "error": "invalid_client",
    "error_description": "Invalid client secret"
}

Object Model

Regular error object

HTTP/1.1 400 Bad Request
{
    "error": {
        "status": 400,
        "message": "invalid id"
    }
}

Let's Code!

Let's code!

Client libraries

RESTful

Let's code!

  1. Get new released albums
  2. Get user information
    • ​​Authorization Code
    • Python + Flask
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

# My application credentials
CLIENT_ID = 'MY_ID'
CLIENT_SECRET = 'MY SECRET'
# Create a credential manager
cred_manager = SpotifyClientCredentials(client_id=CLIENT_ID,
                                        client_secret=CLIENT_SECRET)
# Ask for new releases
sp = spotipy.Spotify(client_credentials_manager=cred_manager)
paged_albums = sp.new_releases(limit=20, offset=0)['albums']
# Display
for idx, album in enumerate(paged_albums['items'], 1):
    artists_name = ', '.join([artist['name'] for artist in album['artists']])
    print("{:2d}: {} - {}".format(idx, album['name'], artists_name))

Client Credentials

authorization

Access API

Display

Spotipy

Get new released albums

Spotipy

 1: Tell Me You Love Me (Deluxe) - Demi Lovato
 2: The Bigger Artist - A Boogie Wit da Hoodie
 3: Now (Deluxe) - Shania Twain
 4: Younger Now - Miley Cyrus
 5: SAVAGE - Tank
 6: Seven Days - PARTYNEXTDOOR
 7: Vuelve - Daddy Yankee
 8: Waterfall - Petit Biscuit, Panama
 9: Mean Demeanor - Run The Jewels
10: Deadstar - Smokepurpp
11: In Too Deep - Trippie Redd
12: Buzzin - Alina Baraz
13: Beautiful Trauma - P!nk
14: My Utmost For His Highest - Various Artists
15: Dirtybird Campout West Coast Compilation - Various Artists
16: Take Back Home Girl (Feat. Tori Kelly) - Chris Lane
17: New Energy - Four Tet
18: Our Point Of View - Blue Note All-Stars
19: Dreams and Daggers - Cécile McLorin Salvant
20: Life Is Confusing EP - Langhorne Slim

Get new released albums

import requests
from base64 import b64encode

CLIENT_ID = b'MY_ID'.encode('ascii')
CLIENT_SECRET = b'MY_SECRET'.encode('ascii')

# Request for access token
reqs_body = {'grant_type': 'client_credentials'}
encoded_cred = b64encode(CLIENT_ID + b':' + CLIENT_SECRET).decode('ascii')
header = {'Authorization': "Basic " + encoded_cred}
resp = requests.post("https://accounts.spotify.com/api/token",
                     data=reqs_body,
                     headers=header)
resp_json = resp.json()
token = resp_json['access_token']
token_type = resp_json['token_type']
expires_in = resp_json['expires_in']

Authorization header

and body

Reqeust for token

Retrieve token from response

Get new released albums

Requests: 1. Retrieve token

# Get new released albums
header = {'Authorization': "Bearer " + token}
params = {'limit': 20, 'offset': 0}
resp = requests.get("https://api.spotify.com/v1/browse/new-releases",
                    headers=header,
                    params=params)

obj = resp.json()
for idx, album in enumerate(obj['albums']['items'], 1):
    artists_name = ', '.join([artist['name'] for artist in album['artists']])
    print("{:2d}: {} - {}".format(idx, album['name'], artists_name))

Auth. header with token

Requests parameters

Make the request

Display

Requests: 2. Access API

Get new released albums

Get user information

  • Interact with resource owner
  • Redirect URI

Get user information

  • /
  • /login
  • /callback
  • /refresh_token

Application endpoints

Get user information

/
/login

Authorization

endpoint

Log in,

authorize access

client ID,

client secret,

scopes,

redirect_uri

Authorization Code: 1. Get the code

Click log in

/callback

code

Get user information

/callback

Token

endpoint

access token,

refresh token

Authorization Code: 2. Get tokens

client ID,

client secret,

code,

redirect_uri

code

/callback

Get user information

Authorization Code: 3. Access API

/callback

access token,

refresh token

Authorization

endpoint

access token

JSON response

token expired

Get user information

Authorization Code: 4. Refresh token

/refresh_token

Authorization

endpoint

client ID,

client secret,

refresh_token

access token

request for refresh

return JSON

Summary

Spotify Web API

By Hsin-Wu Liu (John)

Spotify Web API

  • 1,156