Skip to main content

Phase Two Python SDK

build PyPI license docs

📚 Documentation • 🚀 Hosted Keycloak • 🤖 Keycloak Skills • 💬 Support

Python client for the Phase Two Admin API: organizations, members, roles, domains, identity providers, invitations, SCIM, webhooks and events, realm attributes and magic links. For the core Keycloak Admin API (users, clients, realms), use the official admin client for your language; for Python, python-keycloak.

Installation

pip install phasetwo-sdk
# or
uv add phasetwo-sdk

Requires Python 3.11 or later (tested on 3.11 to 3.14). The package is phasetwo-sdk; the import name is phasetwo.

Quick start

Create an organization, add a member, create an IdP Wizard link for the organization's admin, and record an audit event. This is examples/quickstart.py, which CI runs against Phase Two Keycloak.

import time

import urllib3

from phasetwo import (
    ApiClient,
    Configuration,
    EventRepresentation,
    EventsApi,
    OrganizationMembershipsApi,
    OrganizationRepresentation,
    OrganizationsApi,
)

# Get a token for a service account with the client credentials grant.
token = urllib3.PoolManager().request(
    "POST",
    f"{base_url}/realms/{realm}/protocol/openid-connect/token",
    fields={"grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret},
    encode_multipart=False,
).json()["access_token"]

config = Configuration(host=f"{base_url}/realms", access_token=token)

with ApiClient(config) as client:
    orgs = OrganizationsApi(client)

    # Create an organization. The response is empty; the new id is in the Location header.
    created = orgs.create_organization_with_http_info(
        realm, OrganizationRepresentation(name="acme", domains=["acme.example.com"])
    )
    org_id = created.headers["Location"].rsplit("/", 1)[-1]

    # Add an existing user as a member.
    OrganizationMembershipsApi(client).add_organization_member(realm, org_id, user_id)

    # Create a link to the IdP Wizard, for the organization's admin to set up SSO.
    link = orgs.create_portal_link(realm, org_id)
    print("IdP Wizard:", link.link)

    # Record an audit event.
    EventsApi(client).create_event(
        realm, EventRepresentation(type="acme.onboarded", time=int(time.time() * 1000))
    )

base_url is your Keycloak URL including /auth (for example https://auth.example.com/auth); the SDK's host is that plus /realms.

Authentication

Every request needs an access token in Configuration(access_token=...). We recommend a service account: a confidential client with Service accounts enabled and the realm-management roles it needs (for example manage-organizations), using the client credentials grant as in the quick start. Any HTTP or OIDC library can get the token:

  • python-keycloak: KeycloakOpenID(server_url=..., realm_name=..., client_id=..., client_secret_key=...).token(grant_type="client_credentials")["access_token"]
  • httpx or requests: POST {base_url}/realms/{realm}/protocol/openid-connect/token with form fields grant_type=client_credentials, client_id, client_secret.

Tokens expire (5 minutes by default). For long-running processes, get a new token before it expires and set config.access_token again.

Usage

  • There is one API class per area (OrganizationsApi, OrganizationMembershipsApi, EventsApi, ...), created from a shared ApiClient. Use with ApiClient(config) as client: so the connection pool is closed.
  • Methods are named after the API operation (createOrganization → create_organization) and take the realm name first, then path parameters, then the request body. Optional query parameters are keyword arguments.
  • Request and response bodies are pydantic models (OrganizationRepresentation, ...).
  • Each method has a *_with_http_info variant that also returns the status code and headers. Creates return 201 with an empty body and the new resource's URL in Location; read the id from there, as the quick start does.

Errors

Any non-2xx response raises an ApiException, with status, reason, headers and body. Common statuses have their own subclass: BadRequestException (400), UnauthorizedException (401), ForbiddenException (403), NotFoundException (404), ConflictException (409), UnprocessableEntityException (422) and ServiceException (5xx). All are importable from phasetwo.

from phasetwo import ApiException, NotFoundException

orgs.delete_organization(realm, org_id)
try:
    orgs.get_organization_by_id(realm, org_id)
except NotFoundException:
    print("Deleted:", org_id)
except ApiException as e:  # any other non-2xx response
    print(e.status, e.reason, e.body)

Compatibility

SDK Phase Two API Tested against
0.2.x 0.2 quay.io/phasetwo/phasetwo-keycloak:26.5.6

The API version and the exact spec commit the code was generated from are in sdk-generator.json.

API reference

  • Phase Two Admin REST API reference: every operation, with request and response schemas.
  • The API classes and models have docstrings generated from the same spec; use your editor's help or help(phasetwo.OrganizationsApi).

Generated code

The API classes and models in phasetwo/openapi/ are generated from the Phase Two OpenAPI spec by phasetwo-sdk-generator and re-exported from phasetwo. Don't edit them by hand: changes come from the spec or the generator, and CI fails if the generated code doesn't match. The README code blocks are copied from examples/ by the same tool.

License

Apache License 2.0, see COPYING.

Metadata

Release files for phasetwo-sdk 0.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for phasetwo-sdk 0.2.2
File Size Uploaded Provenance Actions
phasetwo_sdk-0.2.2.tar.gz 120.4 kB With provenance Details for phasetwo_sdk-0.2.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for phasetwo-sdk 0.2.2
File Interpreter ABI Platform Actions
phasetwo_sdk-0.2.2-py3-none-any.whl Python 3 none any Details for phasetwo_sdk-0.2.2-py3-none-any.whl

Total release size: 308.0 kB

Release files / phasetwo_sdk-0.2.2.tar.gz

Download URL phasetwo_sdk-0.2.2.tar.gz
Size 120.4 kB
Tags Source
SHA-256 checksum
How to use checksums
e86d11a7f2c32b0799040ac068d2732a0fb1469a190f1e79d3fcd757e8299fd6
BLAKE2b-256 checksum
How to use checksums
71ca1e1fb0400165a7a465f196ee29cb97bd624c32d76fb3e6bd54ba8e9d7c91
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Release files / phasetwo_sdk-0.2.2-py3-none-any.whl

Download URL phasetwo_sdk-0.2.2-py3-none-any.whl
Size 187.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
31384de2568dae3e549fcfd60c30aec9e7e69015584e1d7b2ab1f586f21e4376
BLAKE2b-256 checksum
How to use checksums
9ba327f2628e1e7a85918f067a36c8eb25733d33145e5a2be2c3c92e9045a6fd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Security for phasetwo-sdk 0.2.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for phasetwo_sdk-0.2.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page