Descope Python SDK

1.12.1 · active · verified Sun Apr 12

The Descope Python SDK provides convenient access to Descope's user management and authentication APIs for backend applications. It facilitates secure user authentication, session management, and various identity-related operations. The library is actively maintained with frequent updates, ensuring compatibility with the latest Descope platform features.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `DescopeClient` using a project ID and an optional management key (preferably from environment variables). It then shows a basic example of attempting to validate a session token. Remember to replace placeholder tokens with actual values in a live application.

import os
from descope import DescopeClient, AuthException

# Ensure DESCOPE_PROJECT_ID and optionally DESCOPE_AUTH_MANAGEMENT_KEY are set as environment variables
project_id = os.environ.get('DESCOPE_PROJECT_ID', '')
management_key = os.environ.get('DESCOPE_AUTH_MANAGEMENT_KEY', '')
# Optional: If using a custom domain
base_url = os.environ.get('DESCOPE_BASE_URI', '')

if not project_id:
    print("Error: DESCOPE_PROJECT_ID environment variable is not set.")
    exit(1)

try:
    # Initialize the DescopeClient
    # If base_url is an empty string, it will default to Descope's API endpoint
    descope_client = DescopeClient(project_id=project_id, auth_management_key=management_key, base_url=base_url)
    print("DescopeClient initialized successfully.")

    # Example: Validate a session token (replace 'your_session_token' with an actual token)
    # In a real application, this token would come from an incoming request's Authorization header or cookie
    test_session_token = "your_session_token"
    if test_session_token == "your_session_token":
        print("Warning: Please replace 'your_session_token' with a real session token for validation.")
    
    try:
        session_jwt = descope_client.validate_session(session_token=test_session_token)
        print(f"Session validated successfully. User ID: {session_jwt['sub']}")
    except AuthException as e:
        print(f"Session validation failed: {e}")
    except Exception as e:
        print(f"An unexpected error occurred during session validation: {e}")

except AuthException as e:
    print(f"Failed to initialize DescopeClient due to authentication error: {e}")
except Exception as e:
    print(f"An unexpected error occurred during DescopeClient initialization: {e}")

view raw JSON →