🎧
【Spotify API】ローカル環境でRefresh Tokenを取得する方法(Flask)
はじめに
Spotify for Developers でアプリを作成後、Redirect URI の設定がうまくいかずに Refresh Token が取得できないという人向けの記事です。
筆者も同じく、ローカル環境で localhost を使ってサーバーを立てようとしたところ、Spotify のダッシュボードに http://localhost:5000/callback のような HTTP の URL が登録できず詰まったので、その解消手順をまとめます。
環境
- Python 3.10+
- Flask
- requests
事前準備(Spotify Developer Dashboard)
- Spotify for Developers にアクセス
- 新しいアプリを作成
- 「Redirect URI」に
http://[::1]:5000/callbackを Add - Client ID / Client Secret を控える
コード例(Flask)
以下は、Spotify 認証コードフローを使って Refresh Token を取得するための最小構成のコードです。
"""auth-server.py"""
"""auth-server.py"""
from base64 import b64encode
import requests
from flask import Flask, redirect, request
CLIENT_ID = "自分のアプリの Client ID に置き換え"
CLIENT_SECRET = "自分のアプリの Client Sercret に置き換え"
REDIRECT_URI = "http://[::1]:5000/callback"
app = Flask(__name__)
@app.route("/login")
def login():
"""ログイン用のルート"""
scope = "user-read-recently-played"
url = (
"https://accounts.spotify.com/authorize"
f"?client_id={CLIENT_ID}"
f"&response_type=code"
f"&redirect_uri={REDIRECT_URI}"
f"&scope={scope}"
)
return redirect(url)
@app.route("/callback")
def callback():
"""Spotifyのリダイレクトを受け取る"""
code = request.args.get("code")
if not code:
return "No code returned", 400
auth_str = f"{CLIENT_ID}:{CLIENT_SECRET}"
headers = {
"Authorization": "Basic " + b64encode(auth_str.encode()).decode(),
"Content-Type": "application/x-www-form-urlencoded",
}
data = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": REDIRECT_URI,
}
res = requests.post(
"https://accounts.spotify.com/api/token",
headers=headers,
data=data,
timeout=None
)
res.raise_for_status()
tokens = res.json()
return f"Refresh Token: {tokens.get('refresh_token')}"
if __name__ == "__main__":
app.run(host="::1", port=5000, debug=True)
実行手順
- Client ID と Client Sercret を書き換え、サーバーを起動
python auth-server.py
-
http://[::1]:5000/loginにアクセス -
画面の指示に従う
-
表示される Refresh Token を控える
まとめ
- Spotify の認証フローでは Redirect URI に HTTPS が必須(HTTP は上記のもの以外NG)
- Flask で簡単に Refresh Token を取得できる
参考
- Spotify Web API Authorization Guide
- Spotify Redirect URI 要件(公式)
Discussion