Simplify OAuth Authentication in Python with httpx-oauth

Feb 5, 2024 ยท 3 min read

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:

  • Registering your app and obtaining client credentials
  • Redirecting users to the authorization URL
  • Exchanging the authorization code for an access token
  • Refreshing expired access tokens
  • Safely storing tokens
  • 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:

  • Unified API - Consistent simple API for different OAuth providers.
  • Auto token refreshing - Access tokens are refreshed automatically if expired.
  • Safe token storage - Tokens stored encrypted in operating system keyrings.
  • Stateless - No need to run your own server to store tokens.
  • 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 fetch_token method opens a browser to let the user log in and authorize access. It then returns the access token that we can use to make requests.

    If the access token expires, httpx-oauth will automatically refresh it when making a request. This frees you from needing to implement token refreshing logic.

    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.

    Browse by tags:

    Browse by language:

    Tired of getting blocked while scraping the web?

    ProxiesAPI handles headless browsers and rotates proxies for you.
    Get access to 1,000 free API credits, no credit card required!