PAYATHON 2026

如何获取 Spotify API 授权码并完成授权流程?

数据小陈

authorization code 不是用 requests.get 或 urllib.request.urlopen 从 Spotify 主动拉取的。浏览器完成登录授权后,Spotify 会把浏览器重定向到你登记的 redirect_uri,例如 http://127.0.0.1:8888/callback?code=...&state=...。你需要在本地启动一个 HTTP 服务监听这个地址,从回调请求的查询参数里取出 code,再用它去换取 access_token。

为什么 requests.get 拿不到 code

requests.get 和 urllib.request.urlopen 用来发起 HTTP 请求,它们不会截获浏览器的跳转。授权码出现在浏览器发往 redirect_uri 的 GET 请求里,所以必须有一个本地服务接收这个请求并解析 code。用 Flask、http.server 或其他本地回调服务都可以。

redirect_uri 必须和 Spotify Dashboard 中登记的地址完全一致,包括协议、主机、端口和路径。用 localhost 还是 127.0.0.1 也要统一,否则回调会失败,或者参数对不上。

用标准库接收授权码的最小示例

下面只演示接收回调。先启动本地服务,再打开授权页。

import http.server
import socketserver
import urllib.parse
import webbrowser

CLIENT_ID = 'your_client_id'
REDIRECT_URI = 'http://127.0.0.1:8888/callback'
SCOPE = 'user-library-read'
STATE = 'some-random-state'

auth_url = 'https://accounts.spotify.com/authorize?' + urllib.parse.urlencode({
    'client_id': CLIENT_ID,
    'response_type': 'code',
    'redirect_uri': REDIRECT_URI,
    'scope': SCOPE,
    'state': STATE,
})

auth_code = None

class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        global auth_code
        parsed = urllib.parse.urlparse(self.path)
        params = urllib.parse.parse_qs(parsed.query)
        if parsed.path == '/callback':
            if params.get('state', [None])[0] != STATE:
                self.send_response(400)
                self.end_headers()
                self.wfile.write(b'State mismatch')
                return
            auth_code = params.get('code', [None])[0]
            self.send_response(200)
            self.send_header('Content-Type', 'text/html; charset=utf-8')
            self.end_headers()
            self.wfile.write('授权完成,可以关闭页面。'.encode('utf-8'))
        else:
            self.send_response(404)
            self.end_headers()

with socketserver.TCPServer(('127.0.0.1', 8888), Handler) as httpd:
    webbrowser.open(auth_url)
    httpd.handle_request()

print('code =', auth_code)

用授权码换 access token

拿到 code 后,向 https://accounts.spotify.com/api/token 发 POST 请求。redirect_uri 要和上一步完全一致。Spotify 通常使用 HTTP Basic 认证传 client_id 和 client_secret。

import requests

token_resp = requests.post(
    'https://accounts.spotify.com/api/token',
    data={
        'grant_type': 'authorization_code',
        'code': auth_code,
        'redirect_uri': REDIRECT_URI,
    },
    auth=(CLIENT_ID, 'your_client_secret'),
)
token_resp.raise_for_status()
tokens = token_resp.json()

access_token = tokens['access_token']
refresh_token = tokens.get('refresh_token')

调用受保护 API 时,每个请求都要带访问令牌:

headers = {'Authorization': f'Bearer {access_token}'}
r = requests.get('https://api.spotify.com/v1/me', headers=headers)
r.raise_for_status()
print(r.json())

有效期和是否每次都要 token

按 Spotify 文档和常见行为:authorization code 有效期很短,通常约 10 分钟,而且只能使用一次;access_token 通常 1 小时后过期。每次调用受保护 API 时都需要在 Authorization: Bearer <access_token> 头里带上 access token,但不需要每次都重新走浏览器授权。access_token 过期后,用 refresh_token 去 token 端点换新的 access token。

如果应用是公开客户端、不能安全保存 client_secret,应使用 Authorization Code with PKCE。学习项目在本地临时使用 client_secret 可以,但不要把它提交到代码仓库或发给别人。

备注:内容仅供参考。