Stytch Python Client

14.4.0 · active · verified Wed Apr 15

The Stytch Python library provides an interface to the Stytch user infrastructure API, simplifying the integration of authentication and authorization flows into Python applications. It supports various authentication methods like Email Magic Links, OAuth, SMS/WhatsApp passcodes, and more for both B2C and B2B use cases. The library is actively maintained with frequent releases, often multiple times a month for minor versions, indicating an agile development cycle.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Stytch client using environment variables and send a magic link for user login or signup. It includes basic error handling for `StytchError` exceptions.

import os
import stytch

# Initialize the Stytch client using environment variables
# Replace with your actual project_id and secret, or set as environment variables
# For B2C authentication:
client = stytch.Client(
    project_id=os.environ.get("STYTCH_PROJECT_ID", "project-test-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"),
    secret=os.environ.get("STYTCH_SECRET", "secret-test-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"),
    # Optionally specify a custom base URL for all API calls
    # custom_base_url="https://api.custom-domain.com/",
)

# For B2B authentication, use stytch.B2BClient instead:
# b2b_client = stytch.B2BClient(
#     project_id=os.environ.get("STYTCH_PROJECT_ID", "project-test-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"),
#     secret=os.environ.get("STYTCH_SECRET", "secret-test-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"),
# )

try:
    # Example: Send a magic link for login or signup
    email_to_authenticate = "test@example.com"
    response = client.magic_links.email.login_or_create(
        email=email_to_authenticate,
        login_magic_link_url="http://localhost:3000/authenticate",
        signup_magic_link_url="http://localhost:3000/authenticate",
    )
    print(f"Magic link sent to {email_to_authenticate}. Status code: {response.status_code}")
    print(f"Request ID: {response.request_id}")
except stytch.StytchError as e:
    print(f"Stytch API error occurred: {e.details}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →