Authenticating with OAuth in Python can be tedious and error-prone. httpx-oauth is a Python library that aims to simplify this process when using the popular httpx HTTP client.
What is OAuth Authentication?
OAuth is an open standard authorization protocol that allows you to access resources from a service without exposing user credentials. Instead of directly sending a username and password, OAuth uses access tokens that grant limited access to the user's data without exposing their password.
Common examples of sites that use OAuth include Facebook, GitHub, Google, and Twitter. To access their APIs in an application, you need to implement OAuth authentication to obtain access tokens for that user.
Challenges with OAuth in Python
Implementing OAuth authentication involves:
This can get complicated very quickly. Each provider also has slightly different OAuth APIs and terminology too.
All this ceremony just to make some API requests with httpx!
How httpx-oauth Simplifies OAuth
The httpx-oauth library abstracts away much of the OAuth complexity:
import httpx
from httpx_oauth.clients.google import GoogleOAuth2
google = GoogleOAuth2()
token = google.fetch_token(scopes=["https://www.googleapis.com/auth/drive.readonly"])
headers = {"Authorization": f"Bearer {token}"}
httpx_client = httpx.Client(headers=headers)
response = httpx_client.get("https://www.googleapis.com/drive/v3/files")
print(response.json())
With just a few lines of code, you can authenticate and make authorized requests!
The key features of httpx-oauth include:
Let's walk through how to use httpx-oauth for OAuth with GitHub as an example.
Authenticating with GitHub using httpx-oauth
First install httpx and httpx-oauth:
pip install httpx httpx-oauth
Then we can authenticate and make requests:
from httpx_oauth.clients.github import GithubOAuth2
github = GithubOAuth2()
# Fetch token for user
token, refresh = github.fetch_token(
scopes=["user", "repo"],
# optional CLI prompt
)
# Create httpx client with auth header
headers = {"Authorization": f"token {token}"}
httpx_client = httpx.Client(headers=headers)
# Make API request
response = httpx_client.get("https://api.github.com/user")
print(response.json())
The
If the access token expires,
Wrap Up
httpx-oauth takes care of the OAuth ceremony like token management, refreshing, and storage. This lets you focus on making API requests with httpx rather than authentication logic.
It provides a consistent and simple API for authenticating with OAuth providers like Google, GitHub, Facebook. No more dealing with complex auth flows for every different platform!
To learn more, check out the httpx-oauth documentation and GitHub repo.