Create an application using the Spotify API

Introduction

I think that the subscription model system tends to have abundant data (use it because it is unlimited). In my case, I listen to music so much lately that I thought it would be interesting to use the Spotify API.

So, this time, let's create some application using Spotify API.

Let's register the application

https://developer.spotify.com/dashboard/

You can register from here. If you already have an account, you can log in and use it immediately.

You will be asked if you want to use it for commercial purposes during registration, so answer correctly. After creating the application, you can enter the OAuth information from ʻEDIT SETTINGS`. There are various options, such as the Web and smartphones. Register the one that suits you.

As will be described later this time, since it is not strictly hit from the Web service, an appropriate URL is set.

Make around authentication

https://developer.spotify.com/documentation/general/guides/authorization-guide/

Details are described above. This time, we will create it as a web application, but in reality it will be executed from Google Cloud Functions, so a Refresh Token is required. According to Spotify's specifications, the Access Token will remain valid for 1 hour and the Refresh Token will remain valid until something is disabled. So, this time, before creating the application, create a Refresh Token by hand, convert it to an Access Token in the code-> hit the Spotify API.

1. Get code

First, generate the URL to get the code. I will omit the details, but the final URL will be as follows. Match client_id and redirect_uri to your environment.

Also, the Spotify API has very finely divided scopes. It is listed below, so you need to specify the required scope. https://developer.spotify.com/documentation/general/guides/scopes/

https://accounts.spotify.com/authorize?client_id=${CLIENT_ID}&response_type=code&redirect_uri=${REDIRECT_URL}&scope=user-read-private%20user-read-email&state=34fFs29kd09

When it is completed, paste it in a suitable browser and press Enter to return to the set redirect_uri. There is no problem if an error occurs here. Since the URL itself has changed, we'll use only the code part of that URL next.

2. Get Refresh Token

Next I have to throw POST. So I'll throw it with curl. Specifically, set the code that took the following command and the client_id and client_secret according to the environment and throw it. If there is no problem, the token will be returned, so keep the Refresh Token.

curl --data "code=${CODE}" --data "client_id=${CLIENT_ID}" --data "client_secret=${CLIENT_SECRET}" --data "redirect_uri=http://localhost/callback" --data "grant_type=authorization_code" https://accounts.spotify.com/api/token

from Refresh Token to Access Token Conversion from Refresh Token to Access Token is a one-shot by hitting the API. In that case, you have to include ʻAuthorization: Basic ` in the Header, and it's easy enough to find it cumbersome to create.

For the time being, I will paste the python code I made.

from dotenv import load_dotenv

import os
import requests
import base64
import json

load_dotenv(verbose=True)

client_id = os.environ.get("SPOTIFY_CLIENT_ID", default="")
client_secret = os.environ.get("SPOTIFY_CLIENT_SECRET", default="")
token = base64.b64encode((client_id + ":" + client_secret).encode("utf-8")).decode(
    "utf-8"
)

headers = {"Authorization": "Basic " + token}
data = {
    "refresh_token": os.environ.get("REFRESH_TOKEN"),
    "grant_type": "refresh_token",
}
response = requests.post(
    "https://accounts.spotify.com/api/token", data=data, headers=headers
)  # noqa: E501
print(json.loads(response.text)["access_token"])

Create the part to call the API

To make an API call, simply set the Access Token you got to Bearer and throw it. Below is a sample code for the ranking data generation that I am trying to create.

    header = {"Authorization": "Bearer " + access_token}
    data = {
        "limit": 50,
        "time_range": "short_term",
    }
    response = requests.get(
        "https://api.spotify.com/v1/me/top/tracks", params=data, headers=header
    )

At the end

So now you can safely create an application using the Spotify API. While Spotify is hard to understand where and what is, the API specifications are written in detail. There are surprisingly many things that can be done, so it is an impression that it can be used as a good sample as a starting point for API creation.

By the way, what I'm making now is to post the ranking I heard the previous month on Twitter once a month. I haven't made the post part yet, so I'll make it from now on.

The procedure for making it by hand is the same for other OAuth APIs, so it can be applied effectively. Please try to make various applications by hitting various APIs. However, if you publish it, the API limit will be exceeded immediately, so in that case, let's make the authentication part properly so that it can be done with the UI.

Recommended Posts

Create an application using the Spotify API
Create an application that just searches using the Google Custom Search API with Python 3.3.1 in Bottle
Try using the Twitter API
Create an easy-to-read pdf of laws and government ordinances using the law api
Try using the Twitter API
Create an app that works well with people's reports using the COTOHA API
Try using the PeeringDB 2.0 API
Create a real-time auto-reply bot using the Twitter Streaming API
Tweet Now Playing to Twitter using the Spotify API. [Python]
I made an original program guide using the NHK program guide API.
Create API using hug with mod_wsgi
Create a CRUD API using FastAPI
I tried using the checkio API
I built an application with Lambda that notifies LINE of "likes" using the Qiita API
Create an API that returns data from a model using turicreate
Create an alias for Route53 to CloudFront with the AWS API
Create an application by classifying with Pygame
Try using the Wunderlist API in Python
Try using the web application framework Flask
Try using the Kraken API in Python
Tweet using the Twitter API in Python
Create a graph using the Sympy module
[Python] Quickly create an API with Flask
Play with puns using the COTOHA API
Try hitting the Spotify API in Django.
Record custom events using the Shotgun API
I tried using the BigQuery Storage API
How to build an application from the cloud using the Django web framework
[Hyperledger Iroha] Create an account using Python library
I checked the library for using the Gracenote API
Hit the Web API using requests Example: Flickr
Try using the BitFlyer Ligntning API in Python
Create a REST API using the model learned in Lobe and TensorFlow Serving.
Easy to create API server using go-json-rest module
Let's create a REST API using SpringBoot + MongoDB
I tried using the Google Cloud Vision API
Creating an interactive application using a topic model
Get an access token for the Pocket API
Try to create an HTTP server using Node.js
To automatically send an email with an attachment using the Gmail API in Python
Create a filter to get an Access Token in the Graph API (Flask)
Create an API server quickly with Python + Falcon
Try using the DropBox Core API in Python
Create a GUI on the terminal using curses
Get all songs of Arashi's song information using Spotify API and verify the index
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
Initial settings when using the foursquare API in python
Send and receive Gmail via the Gmail API using Python
Create a tweet heatmap with the Google Maps API
Post to your account using the API on Twitter
Create a pseudo REST API server using GitHub Pages
I tried using the API of the salmon data project
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
Using the National Diet Library Search API in Python
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
Create a shape on the trajectory of an object
A little bit from Python using the Jenkins API
Create a dictionary by searching the table using sqlalchemy
[Python] Create an infrastructure diagram in 3 minutes using diagrams