Requests-OAuthlib
Requests-OAuthlib provides OAuth1 and OAuth2 authentication support for the Requests library. The current version is 2.0.0, released on March 22, 2024. The library is actively maintained, with updates addressing compliance fixes and feature enhancements.
Warnings
- breaking Version 1.2.0 and above require OAuthlib 3.0.0 or newer, which may introduce breaking changes.
- deprecated Support for Python 2.6 and 3.3 has been removed as of version 1.0.0.
- gotcha OAuth2Session.fetch_token previously tried to guess how and where to provide 'client' and 'user' credentials incorrectly.
Install
-
pip install requests requests-oauthlib
Imports
- OAuth1Session
from requests_oauthlib import OAuth1Session
- OAuth2Session
from requests_oauthlib import OAuth2Session
Quickstart
from requests_oauthlib import OAuth2Session
client_id = 'your_client_id'
client_secret = 'your_client_secret'
redirect_uri = 'your_redirect_uri'
authorization_base_url = 'https://authorization_server.com/authorize'
token_url = 'https://authorization_server.com/token'
# Create an OAuth2 session
oauth = OAuth2Session(client_id, redirect_uri=redirect_uri)
# Redirect the user to the authorization URL
authorization_url, state = oauth.authorization_url(authorization_base_url)
print('Please go to this URL and authorize:', authorization_url)
# After the user authorizes, the callback URL will contain the authorization code
# Exchange the authorization code for an access token
token = oauth.fetch_token(token_url, client_secret=client_secret, authorization_response='callback_url')
# Use the access token to access protected resources
response = oauth.get('https://api.resource_server.com/protected_resource')
print(response.content)