When building an application that needs to access user data from an API that uses OAuth2 authentication, Python's Requests library provides an easy way to handle the OAuth2 flow. In this guide, I'll walk through a simple example of using Requests to access a protected resource from an OAuth2 API.
Understanding the OAuth2 Flow
At a high level, the OAuth2 authentication flow has three main steps:
- Get an access token from the OAuth2 server by authenticating your application
- Include the access token in requests to the API
- Refresh the access token before it expires
The Requests library handles step 2 automatically. We just need to get the initial access token and refresh it when needed.
Getting an Initial Access Token
To retrieve an initial access token, we make a
import requests
url = "https://oauth2.example.com/token"
data = {
"grant_type": "client_credentials",
"client_id": "my_client_id",
"client_secret": "my_client_secret"
}
response = requests.post(url, data=data)
access_token = response.json()["access_token"]
This gives us an access token we can use to access protected resources.
Making Authenticated API Requests
To call an API endpoint using our access token, we simply pass the token in the
headers = {
"Authorization": f"Bearer {access_token}"
}
response = requests.get("https://api.example.com/user", headers=headers)
The API will validate our access token and return the protected resource if valid.
Refreshing Expired Tokens
Access tokens eventually expire. To get a fresh access token using a refresh token, make another
Handling the token refresh logic allows us to keep accessing the API without interruptions.
This covers the basics of using Requests to access OAuth2 APIs. The key is obtaining and refreshing access tokens programmatically. Requests then handles including the token in API requests under the hood.