简体   繁体   中英

Python requests library header authorization issue

I'm trying to use the Spotify Web API to access my Spotify devices available. See this link for the specific API endpoint I'm trying to access. I'm using Python 2.7 in a virtualenv on macOS Sierra.

I already have an authorization token that I've used to make several other function calls so I know that works. However this is the first time I'm using the requests library as opposed to the Spotipy wrapper that abstracts the http requests to Spotipy function calls.

The documentation in the link above states I need to pass in my authorization token in the header. I understand in the requests module you should pass in headers as a dictionary where both the key and value are strings.

Here is the code I'm using to make the request:

token_string = token.encode('ascii','ignore')
    print type(token_string)
    headers = {"Authorization":token_string}
    r=requests.get("https://api.spotify.com/v1/me/player/devices", headers=headers)

I'm encoding the token as a string because I read the requests module prefers strings over unicode and the token was originally in unicode.

I keep getting a 400 error (see below for what it prints) which is an authorization issue. I think the issue may be that I'm not passing in the authorization token in correctly. Does anyone have any insight into this?

<Response [400]>

Judging by their example on the posted page, you should use Bearer prefix for your authorization (for 'why?' check the 5. The tokens are returned to your application section of the Spotify Web API Authorization Guide ), so:

headers = {"Authorization": "Bearer {}".format(token_string)}
r = requests.get("https://api.spotify.com/v1/me/player/devices", headers=headers)

Provided that your token is valid, that should work, you don't need to do any encoding or anything - just store it at face value in the token_string .

There are already Python Spotify client modules, tho, so instead of wrangling it yourself why not use one of them, like spotipy which is even referenced on the official Spotify API examples page?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM