WorkOS Python Client
WorkOS Python Client provides a comprehensive SDK to interact with the WorkOS API for enterprise-ready features like Single Sign-On (SSO), Directory Sync (SCIM), Multi-Factor Authentication (MFA), Admin Portal, and Audit Logs. It simplifies integration with various identity providers and directory services. The library is actively maintained with frequent updates, often on a weekly or bi-weekly cadence. The current version is 5.46.0.
Warnings
- breaking Major breaking changes were introduced in version `2.0.0`. This included significant renames (e.g., `WorkOS` class methods moved to top-level `workos` module), changes in error handling (e.g., `workos.exceptions` moved to `workos.errors`), and parameter name updates across various API methods. Upgrading from `1.x.x` to `2.x.x` requires code modifications.
- gotcha Webhook events must always be cryptographically verified using `workos.webhooks.verify_event()`. Failure to do so exposes your webhook endpoints to spoofing and unauthorized access, posing a significant security risk.
- gotcha Many WorkOS list endpoints (e.g., `list_organizations`, `list_users`) are paginated. If you don't explicitly handle pagination by iterating through `organizations.list_organizations(limit=N, after='cursor')` or similar patterns, you will only receive the first page of results, leading to incomplete data.
- gotcha The global configuration pattern (`import workos; workos.api_key = ...`) can lead to issues in complex applications (e.g., multi-tenant services, tests) where different WorkOS configurations are needed simultaneously. All requests will use the globally set credentials.
Install
-
pip install workos
Imports
- workos
import workos
- WorkOSClient
from workos import WorkOSClient
- WebhookSignatureError
from workos.errors import WebhookSignatureError
Quickstart
import os
import workos
from pprint import pprint
# Configure WorkOS using environment variables
# For local testing, replace with actual test keys if env vars are not set
workos.api_key = os.environ.get("WORKOS_API_KEY", "sk_test_YOUR_API_KEY")
workos.client_id = os.environ.get("WORKOS_CLIENT_ID", "client_test_YOUR_CLIENT_ID")
# Optional: Set the API base URL for custom environments (e.g., local development)
# workos.base_api_url = "http://localhost:8000/"
# Example 1: List organizations
try:
print("\n--- Listing Organizations ---")
organizations = workos.organizations.list_organizations(limit=5)
if organizations.data:
for org in organizations.data:
pprint(org.to_dict())
else:
print("No organizations found.")
except Exception as e:
print(f"Error listing organizations: {e}")
# Example 2: Generate an SSO authorization URL
try:
print("\n--- Generating SSO Authorization URL ---")
authorization_url = workos.sso.get_authorization_url(
domain="example.com", # Replace with a domain configured in WorkOS
redirect_uri="http://localhost:8000/callback", # Must be a valid redirect URI configured in WorkOS
state="some-secure-random-state"
)
print(f"SSO Authorization URL for example.com: {authorization_url}")
except Exception as e:
print(f"Error generating SSO URL: {e}")
# Example 3: Verify a webhook event (simulated payload)
try:
print("\n--- Simulating Webhook Verification ---")
# In a real scenario, payload and signature_header come from the HTTP request
webhook_payload = '{"id": "wh_01G827B6V8F1PZ1D7E40P5940X", "event": "directory_sync.user.created", "data": {}}'
webhook_signature = "t=1678886400,v1=signature_hash"
webhook_secret = os.environ.get("WORKOS_WEBHOOK_SECRET", "webhook_secret_YOUR_WEBHOOK_SECRET")
# This will likely fail with a dummy signature, but demonstrates the call
print("Attempting to verify webhook (will likely fail with dummy data)...")
event = workos.webhooks.verify_event(
payload=webhook_payload,
signature_header=webhook_signature,
secret=webhook_secret
)
print(f"Webhook event verified: {event['event']}")
except workos.errors.WebhookSignatureError as e:
print(f"Webhook signature verification failed: {e}")
except Exception as e:
print(f"Error during webhook verification simulation: {e}")