尝试调用Apple Music API时,我一直遇到401错误。我正在使用Windows机器,下面是它的Python代码。
import datetime
import jwt
secret = """-----BEGIN PRIVATE KEY-----
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxx
-----END PRIVATE KEY-----"""
kid = 'ABCDEFGHI'
teamId = 'JKLMNOPQRS'
alg = 'ES256'
headers = {
'alg': alg,
'kid': kid
}
payload = {
'iss': teamId,
'iat': 1518033023,
'exp': 1518290267
}
if __name__ == '__main__':
'''Create an auth token'''
token = jwt.encode(payload, secret, algorithm=alg, headers=headers)
print '----CURL----'
print ("curl -v -H 'Authorization: Bearer %s' \"https://api.music.apple.com/v1/catalog/us/playlists/pl.14362d3dfe4b41f7878939782647e0ba\" " % (token))
最佳答案
字符串格式运算符存在相同的问题。因此使用此:
"""Create an auth token"""
token = jwt.encode(payload, secret, algorithm=alg, headers=headers)
token_str = token.decode('utf-8') # converts bytes to string
url = "https://api.music.apple.com/v1/catalog/us/playlists/pl.14362d3dfe4b41f7878939782647e0ba"
print("curl -v -H 'Authorization: Bearer" + token_str + "\"" + url + "\"")
此外:我假设您想直接访问数据。为此,您可以使用requests库:
import requests
request_obj = requests.get(url, headers={'Authorization': "Bearer " + token_str})
json_dict = request_obj.json()
干杯!