调用Spotify API获取Access Token报grant_type参数缺失错误,如何排查?
问题排查与解决方案
报错原因
返回{"error":"unsupported_grant_type","error_description":"grant_type parameter is missing"}的核心问题是请求参数的编码格式不符合Spotify授权接口的要求:
- 客户端凭证流的
/api/token接口要求请求体必须为application/x-www-form-urlencoded编码格式,grant_type参数需要放在表单格式的请求体中 - 绝大多数从JS实现转写Python代码的错误都是误用了
requests库的json参数传参:json参数会将内容序列化为JSON格式发送,接口无法正常解析到grant_type字段,就会返回参数缺失的报错
正确实现逻辑(参考spotipy库源码逻辑)
使用requests的data参数传递表单参数,requests会自动将参数编码为符合要求的x-www-form-urlencoded格式,示例代码如下:
import requests import base64 # 替换为自己的Spotify应用凭证 CLIENT_ID = "YOUR_CLIENT_ID" CLIENT_SECRET = "YOUR_CLIENT_SECRET" # 构造Basic认证头 auth_cred = f"{CLIENT_ID}:{CLIENT_SECRET}".encode() b64_cred = base64.b64encode(auth_cred).decode("utf-8") headers = { "Authorization": f"Basic {b64_cred}", "Content-Type": "application/x-www-form-urlencoded" } # 表单参数用data参数传递 payload = { "grant_type": "client_credentials" } resp = requests.post( "https://accounts.spotify.com/api/token", headers=headers, data=payload ) access_token = resp.json().get("access_token")
内容的提问来源于stack exchange,提问作者Павел Родин
相关产品推荐
相关产品推荐

