Skip to content

Repository files navigation

WorkOS Python Library

PyPIBuild Status

The WorkOS library for Python provides convenient access to the WorkOS API from applications written in Python, hosted on PyPI.

Documentation

See the API Reference for Python usage examples.

Installation

Requires Python 3.10+.

pip install workos

Quick Start

fromworkosimportWorkOSClientclient=WorkOSClient(api_key="sk_1234", client_id="client_1234")
# List organizationspage=client.organizations.list_organizations()
fororginpage.auto_paging_iter():
print(org.name)
# Create an organizationorg=client.organizations.create_organization(name="Acme Corp")
print(org.id)

Async Client

Every HTTP API method has an identical async counterpart on AsyncWorkOSClient. (Pure-local utilities such as webhook signature verification, Actions helpers, and PKCE are synchronous on both clients.)

fromworkosimportAsyncWorkOSClientasync_client=AsyncWorkOSClient(api_key="sk_1234", client_id="client_1234")
page=awaitasync_client.organizations.list_organizations()
asyncfororginpage.auto_paging_iter():
print(org.name)

Environment Variables

The client reads credentials from the environment when not passed explicitly:

VariableDescription
WORKOS_API_KEYWorkOS API key
WORKOS_CLIENT_IDWorkOS client ID
WORKOS_BASE_URLOverride the API base URL (defaults to https://api.workos.com/)
WORKOS_REQUEST_TIMEOUTHTTP timeout in seconds (defaults to 60)

Available Resources

The client exposes the WorkOS API through typed namespace properties:

PropertyDescription
client.ssoSingle Sign-On connections and authorization
client.organizationsOrganization management
client.organization_domainsOrganization domain verification
client.organization_membershipOrganization membership management
client.user_managementUsers, identities, auth methods, invitations
client.directory_syncDirectory connections and directory users/groups
client.groupsOrganization group management
client.admin_portalAdmin Portal link generation
client.audit_logsAudit log events, exports, and schemas
client.authorizationFine-Grained Authorization (FGA) resources, roles, permissions, and checks
client.eventsEvents API
client.webhooksWebhook endpoint management and event verification
client.feature_flagsFeature flag management (list, enable/disable, targeting)
client.api_keysOrganization API key management
client.client_apiClient API token generation
client.connectOAuth application management
client.widgetsWidget session tokens
client.multi_factor_authMFA enrollment and verification (also available as client.mfa)
client.pipesData Integrations
client.pipes_providerOrganization data integration configuration
client.radarRadar risk scoring
client.passwordlessPasswordless authentication sessions
client.vaultEncrypted data vault
client.actionsAuthKit Actions signature verification and response signing
client.pkcePKCE code verifier/challenge helpers

Pagination

Paginated endpoints return SyncPage[T] (or AsyncPage[T]) with built-in auto-pagination:

# Iterate through all pages automaticallyforuserinclient.user_management.list_users().auto_paging_iter():
print(user.email)
# Or work with a single pagepage=client.user_management.list_users(limit=10)
print(page.data) # List of items on this pageprint(page.has_more()) # Whether more pages existprint(page.after) # Cursor for the next page

Error Handling

All API errors map to typed exception classes with rich context:

fromworkosimportNotFoundError, RateLimitExceededErrortry:
client.organizations.get_organization("org_nonexistent")
exceptNotFoundErrorase:
print(f"Not found: {e.message}")
print(f"Request ID: {e.request_id}")
exceptRateLimitExceededErrorase:
print(f"Retry after: {e.retry_after} seconds")
ExceptionStatus Code
BadRequestError400
AuthenticationError401
AuthorizationError403
NotFoundError404
ConflictError409
UnprocessableEntityError422
RateLimitExceededError429
ServerError5xx

Retries

The client automatically retries requests up to 3 times (configurable via the max_retries request option) on 429 and 5xx responses, timeouts, and connection errors, using exponential backoff with jitter and honoring Retry-After. The SDK attaches an auto-generated Idempotency-Key (UUID v4) to every POST request and reuses the same key across its internal retries.

Per-Request Options

Every API method accepts request_options for per-call overrides (local helpers such as webhook/Actions signature verification and PKCE utilities do not make HTTP calls and don't take request_options):

result=client.organizations.list_organizations(
request_options={
"timeout": 10,
"max_retries": 5,
"extra_headers": {"X-Custom": "value"},
"idempotency_key": "my-key",
"base_url": "https://staging.workos.com/",
}
)

Note

The WorkOS API currently honors Idempotency-Key only on the Create Audit Log Event endpoint (audit_logs.create_event). Other endpoints accept the header but do not deduplicate requests, so a retried mutation elsewhere can still create a duplicate.

Type Safety

This SDK ships with full type annotations (py.typed / PEP 561) and works with mypy, pyright, and IDE autocompletion out of the box. All API resource models are @dataclass(slots=True) classes with from_dict() / to_dict() for serialization.

SDK Versioning

WorkOS follows Semantic Versioning. Breaking changes are only released in major versions. We strongly recommend reading changelogs before making major version upgrades.

Beta Releases

WorkOS has features in Beta that can be accessed via Beta releases. We would love for you to try these and share feedback with us before these features reach general availability (GA). To install a Beta version, please follow the installation steps above using the Beta release version.

Note: there can be breaking changes between Beta versions. We recommend pinning the package version to a specific version.

More Information

Releases

Packages

Used by

Contributors

Languages