Auth0 Python SDK

repository·master·Indexed 20 days ago

https://github.com/auth0/auth0-python

The Auth0 Python SDK (v6.1.0) provides a high-level, idiomatic interface for interacting with Auth0's Authentication and Management APIs. It includes the ManagementClient for simplified API interaction with automatic token management, AsyncManagementClient for non-blocking calls, and the GetToken class for authentication flows. The SDK supports paginated results via SyncPager and AsyncPager, custom httpx clients, and automatic retries with exponential backoff. It requires Python ≥3.10.

Tokens
128K
Snippets
504
Records
556
Agent score
67%

What's inside auth0-python

  1. Iterate through paginated results

    master

    Paginated requests return a SyncPager or AsyncPager. You can iterate through the items directly as a generator, or use .iter_pages() to navigate page-by-page. When using .iter_pages(), you can access the typed response for each page via the .response attribute.

    from auth0.management import Auth0
    
    client = Auth0(
        base_url="https://YOUR_TENANT.auth0.com/api/v2",
        token="YOUR_TOKEN",
    )
    
    # Get a pager object
    response = client.actions.list(
        trigger_id="post-login",
        action_name="actionName",
        deployed=True,
        page=1,
        per_page=1,
        installed=True,
    )
    
    # Option 1: Iterate through all items directly
    for item in response:
        print(item)
    
    # Option 2: Paginate page-by-page
    for page in response.iter_pages():
        print(page)
    
    # Option 3: Access typed response per page
    pager = client.actions.list(...)
    for page in pager.iter_pages():
        print(page.response)  # access the typed response for each page
        for item in page:
            print(item)
  2. Handle API responses using Pydantic models

    master

    All Management API responses in v5 are Pydantic models. This enables IDE autocomplete, type checking, and validation.

    Accessing Data:

    • Use attribute access (e.g., user.email) instead of dictionary keys.
    • For nested data, check for existence before access (e.g., if user.app_metadata:).

    Converting to Dictionaries: If your existing code requires dictionary access, use the .model_dump() method to convert the response.

    # v5: Attribute access
    user = client.users.get("user_id")
    print(user.email)
    print(user.nickname)
    
    # Convert to dict for compatibility
    user_dict = user.model_dump()
    print(user_dict['email'])
  3. Use the ManagementClient for the Management API

    master

    The ManagementClient is the recommended way to interact with the Auth0 Management API. It simplifies interaction by using your Auth0 domain and supports automatic token management (acquisition and refresh) when provided with client credentials.

    from auth0.management import ManagementClient
    
    # Option 1: With an existing token
    client = ManagementClient(
        domain="your-tenant.auth0.com",
        token="YOUR_TOKEN",
    )
    
    # Option 2: With client credentials (automatic token acquisition and refresh)
    client = ManagementClient(
        domain="your-tenant.auth0.com",
        client_id="YOUR_CLIENT_ID",
        client_secret="YOUR_CLIENT_SECRET",
    )
  4. Migrate from v4 to v5 Management API

    master

    The migration from v4 to v5 involves several key changes to the Management API due to a new code generation engine.

    Key Changes:

    • Python Version: v5 requires Python 3.9 or higher.
    • Client Class: Auth0 is replaced by ManagementClient (or AsyncManagementClient).
    • Response Types: Responses are now Pydantic models instead of raw dictionaries. You must use attribute access (e.g., user.email) instead of dictionary key access (e.g., user['email']).
    • Pagination: Manual loop-based pagination is replaced by SyncPager and AsyncPager for automatic or page-by-page iteration.
    • Authentication: v5 adds built-in support for client credentials with automatic token caching and refreshing.

    Note: The Authentication API remains unchanged and is compatible across versions.

  5. Migrate from v5 to v6

    master
    The v6 release removes the deprecated Management API surface for federated connections tokensets and tightens several generated types to align with the current Auth0 Management API contract. The Authentication API is unaffected. Most applications will only be impacted if they use the specific types or endpoints listed in the breaking changes section.
  6. Paginate results with SyncPager and AsyncPager

    master

    v5 provides specialized pager objects to simplify iterating over paginated endpoints.

    Automatic Iteration: Iterates through all pages automatically. Page-by-page Iteration: Uses .iter_pages() to process one page at a time. Manual Pagination: Use .has_next and .next_page() for explicit control.

    For asynchronous code, use AsyncManagementClient with async for loops.

    # Automatic iteration
    for user in client.users.list():
        print(user.email)
    
    # Page-by-page iteration
    for page in client.users.list().iter_pages():
        print(f"Processing {len(page.items)} users")
        for user in page.items:
            print(user.email)
    
    # Async pagination
    from auth0.management import AsyncManagementClient
    
    async for user in client.users.list():
        print(user.email)
  7. Manage email templates with EmailTemplatesClient

    master

    The EmailTemplatesClient (synchronous) and AsyncEmailTemplatesClient (asynchronous) allow you to create, retrieve, set, and update Auth0 email templates. You can access these via the email_templates property on your main Auth0 or AsyncAuth0 client instance.

    Supported template names include:

    • verify_email
    • verify_email_by_code
    • auth_email_by_code
    • reset_email
    • reset_email_by_code
    • welcome_email
    • blocked_account
    • stolen_credentials
    • enrollment_email
    • mfa_oob_code
    • user_invitation
    • async_approval
    • change_password (legacy)
    • password_reset (legacy)
    from auth0 import Auth0
    
    client = Auth0(token="YOUR_TOKEN")
    # Access the email templates client
    client.email_templates.get(template_name="verify_email")
  8. Configure custom domains

    master

    If your Auth0 tenant uses custom domains, you can specify a global custom domain in the ManagementClient or override it for a specific request using CustomDomainHeader in request_options. Per-request overrides take precedence over global settings.

    from auth0.management import ManagementClient, CustomDomainHeader
    
    # Global custom domain
    client = ManagementClient(
        domain="your-tenant.auth0.com",
        token="YOUR_TOKEN",
        custom_domain="login.mycompany.com",
    )
    
    # Per-request override
    client.users.create(
        connection="Username-Password-Authentication",
        email="user@example.com",
        password="SecurePass123!",
        request_options=CustomDomainHeader("other.mycompany.com"),
    )
  9. Access Flow Executions and Vault

    master

    The FlowsClient provides properties to access related management capabilities:

    • executions: Accesses the ExecutionsClient to manage flow executions.
    • vault: Accesses the VaultClient to manage vault-related flow data.

    These are lazily loaded.

    # Synchronous
    executions = client.flows.executions
    vault = client.flows.vault
    
    # Asynchronous
    executions = await client.flows.executions
    vault = await client.flows.vault
  10. Async Email Provider Client

    master

    The AsyncProviderClient provides the same functionality as ProviderClient but uses async/await syntax for non-blocking I/O. Use AsyncAuth0 to access these methods.

    Methods:

    • get(...): Retrieve provider details.
    • create(...): Create a new provider.
    • update(...): Update an existing provider.
    • delete(...): Delete the provider.
    import asyncio
    from auth0 import AsyncAuth0, EmailProviderCredentialsSchemaZero
    
    client = AsyncAuth0(token="YOUR_TOKEN")
    
    async def main() -> None:
        # Example: Create a provider
        await client.emails.provider.create(
            name="mailgun",
            credentials=EmailProviderCredentialsSchemaZero(
                api_key="api_key",
            ),
        )
        
        # Example: Get provider details
        await client.emails.provider.get(fields="fields", include_fields=True)
    
    asyncio.run(main())