Skip to content

Commit 9c1f83f

Browse files
odysseusmaxjtroussard
authored andcommitted
add Spotify OAuth 2 Tutorial
1 parent 2944df6 commit 9c1f83f

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

docs/examples/spotify.rst

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
Spotify OAuth 2 Tutorial
2+
==========================
3+
4+
Setup a new app in the `Spotify Developer Console`_.
5+
When you have obtained a ``client_id``, ``client_secret`` and registered
6+
a Redirect URI, then you can try out the command line interactive example below.
7+
8+
.. _`Spotify Developer Console`: https://developer.spotify.com/dashboard/applications
9+
10+
.. code-block:: pycon
11+
12+
>>> # Credentials you get from registering a new application
13+
>>> client_id = '<the id you get from spotify developer console>'
14+
>>> client_secret = '<the secret you get from spotify developer console>'
15+
>>> redirect_uri = 'https://your.registered/callback'
16+
17+
>>> # OAuth endpoints given in the Spotify API documentation
18+
>>> # https://developer.spotify.com/documentation/general/guides/authorization/code-flow/
19+
>>> authorization_base_url = "https://accounts.spotify.com/authorize"
20+
>>> token_url = "https://accounts.spotify.com/api/token"
21+
>>> # https://developer.spotify.com/documentation/general/guides/authorization/scopes/
22+
>>> scope = [
23+
... "user-read-email",
24+
... "playlist-read-collaborative"
25+
... ]
26+
27+
>>> from requests_oauthlib import OAuth2Session
28+
>>> spotify = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri)
29+
30+
>>> # Redirect user to Spotify for authorization
31+
>>> authorization_url, state = spotify.authorization_url(authorization_base_url)
32+
>>> print('Please go here and authorize: ', authorization_url)
33+
34+
>>> # Get the authorization verifier code from the callback url
35+
>>> redirect_response = input('\n\nPaste the full redirect URL here: ')
36+
37+
>>> from requests.auth import HTTPBasicAuth
38+
39+
>>> auth = HTTPBasicAuth(client_id, client_secret)
40+
41+
>>> # Fetch the access token
42+
>>> token = spotify.fetch_token(token_url, auth=auth,
43+
... authorization_response=redirect_response)
44+
45+
>>> print(token)
46+
47+
>>> # Fetch a protected resource, i.e. user profile
48+
>>> r = spotify.get('https://api.spotify.com/v1/me')
49+
>>> print(r.content)

0 commit comments

Comments
 (0)