Typing stubs for oauthlib

3.3.0.20260408 · active · verified Sat Apr 11

types-oauthlib provides typing stubs for the `oauthlib` library, a generic, spec-compliant OAuth framework for Python. It enables static type checkers like MyPy and Pyright to validate code that uses `oauthlib`, enhancing code quality and helping prevent runtime errors. This package is part of the `typeshed` project, which automatically releases stub updates (up to once a day) to keep pace with `oauthlib` and other third-party packages.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `oauthlib` with `types-oauthlib` for static type checking. It illustrates the initial steps of an OAuth 2.0 Authorization Code flow: initializing a `WebApplicationClient` and preparing/parsing an authorization request URI. The type hints provided by `types-oauthlib` ensure that methods and their arguments are used correctly.

import os
from typing import Dict, Any
from oauthlib.oauth2 import WebApplicationClient

# --- Configuration (replace with your actual values) ---
CLIENT_ID: str = os.environ.get('OAUTH_CLIENT_ID', 'your_client_id')
AUTHORIZATION_BASE_URL: str = os.environ.get('OAUTH_AUTH_URL', 'https://example.com/oauth/authorize')
REDIRECT_URI: str = os.environ.get('OAUTH_REDIRECT_URI', 'https://example.com/callback')

# 1. Create a client instance
client: WebApplicationClient = WebApplicationClient(CLIENT_ID)

# 2. Prepare the authorization request URL
scope: str = "read write profile"
request_uri: str = client.prepare_request_uri(
    AUTHORIZATION_BASE_URL,
    redirect_uri=REDIRECT_URI,
    scope=scope
)

print(f"Visit this URL to authorize: {request_uri}")

# Simulate receiving an authorization response from the OAuth provider
# In a real web application, this URL would be received by your REDIRECT_URI endpoint
simulated_auth_response_url: str = f"{REDIRECT_URI}?code=AUTHORIZATION_CODE_EXAMPLE&state=STATE_EXAMPLE"

# 3. Parse the authorization response for the code
# The state parameter is crucial for CSRF protection and should be validated against a stored value.
response_params: Dict[str, Any] = client.parse_request_uri(
    uri=simulated_auth_response_url,
    state='STATE_EXAMPLE' # This should match the state generated in prepare_request_uri and stored in session/database
)

auth_code: str = response_params['code']
print(f"Successfully received authorization code: {auth_code}")

# Further steps would involve exchanging the code for an access token
# using client.prepare_token_request and sending it to the token endpoint.

view raw JSON →