Introducing a new way to review your PRs.

Read the announcement

reflex-dev / reflex

🕸️ Web apps in pure Python 🐍

View on GitHub

30 documents · Updated Nov 23, 2026

docs / build-service-sdk

Build service SDK

The build service SDK is the Python client for the Reflex Cloud control plane. It gives local tools and automation one typed interface for identity, projects, apps, deployments, hosting providers, and related platform services. It supports both blocking and coroutine-based use while keeping authentication, transport, retries, upload work, and response handling consistent. See build platform integration for the wider platform and deployment and hosting for the user-facing deployment flow.

Client boundary

The SDK turns Python method calls into authenticated requests to the build service. A top-level client owns the service connection and exposes resource groups that map to the main platform areas.

Client modes

ReflexBuild is the synchronous client and AsyncReflexBuild is its asynchronous counterpart. Both clients expose the same resource shape and service behavior, so a caller can choose blocking or coroutine-based control flow without changing the platform model. The asynchronous client is intended for event-loop based programs and the synchronous client is suited to scripts and command-line work.

Each client can manage its own network resource or use a caller-owned transport. Context-manager use closes resources created by the client, while a supplied transport remains under the caller's control. In this repository, the SDK is resolved as a workspace package and development installs include its aiohttp, httpx2, and httpx transport options.

References: packages/…/_client.py• L32-123 packages/…/_client.py• L31-122 pyproject.toml• L124-125 pyproject.toml• L548-570

Resource surface

The client groups related operations behind stable resource APIs. This grouping lets a caller move from an identity or project lookup to app management and then to deployment without building service URLs or request bodies by hand.

Resource groupPlatform purpose
authIdentify the caller, run browser login, and manage access tokens.
projectsManage project boundaries, apps in projects, roles, members, teams, and audit records.
appsCreate and manage apps, runtime state, secrets, domains, environments, databases, and app sign-in.
deploymentsValidate, upload, start, observe, and describe app deployments.
providersInspect and manage connected cloud provider accounts, especially Google Cloud.
security_reviewsSubmit source archives for security and logic review.
usageRead plan allowance balance and charge or credit history.

The asynchronous client mirrors this surface with coroutine methods and asynchronous iterators where a resource returns a stream of pages.

References: packages/…/_client.py• L38-51 packages/…/_client.py• L37-50 packages/…/apps.py• L282-307

Access and request model

The SDK centralizes access selection and request handling so every resource follows the same service contract. Resources declare the operation and expected result, while the shared client layer applies the service URL, headers, authentication, retry rules, and response conversion.

Credential sources

The client resolves credentials in a fixed order: an explicit token argument and then the REFLEX_ACCESS_TOKEN environment value. The SDK does not read a token saved by the local Reflex login flow. An authenticated call without a usable token fails before it is sent.

Browser login remains a separate resource operation. It creates an approval URL and waits for a one-time token, which the caller must pass to the client or otherwise manage for later use. CI and other unattended jobs should use an explicit or environment token.

References: packages/…/_base.py• L131-163 packages/…/_base.py• L223-235 packages/…/auth.py• L143-248

Request lifecycle

An API call is built under the service's versioned API path with a fresh request ID. The shared layer adds the access token when the endpoint needs it, encodes query and body values, and sends the request through the selected transport. Safe retries cover rejected requests and transient failures only when repeating the operation cannot apply it twice.

Successful JSON responses are decoded into the type requested by the resource. Error responses become typed API errors with the status, server detail, and request ID available for diagnosis. A successful response with an unexpected body becomes a response-validation error instead of silently producing an invalid model.

References: packages/…/_base.py• L192-308 packages/…/_client.py• L125-224 packages/…/_errors.py• L80-209

Transport selection

The synchronous client selects an httpx2 transport when it is installed and falls back to httpx. The asynchronous client selects the first installed transport in this order: aiohttp, httpx2, then httpx. These HTTP libraries are optional, and the SDK loads their transport modules only when a caller selects one. A caller can pass a custom transport that follows the SDK's Transport or AsyncTransport protocol. The public default_transport() helper lets a transport wrapper preserve this default choice instead of hard-coding an HTTP library.

The transport boundary keeps HTTP-library choices separate from resource APIs. It also carries streamed request bodies for build archives, reports whether a connection failure may have reached the service, and applies operation-level timeout limits. A custom synchronous transport must be safe for concurrent archive uploads.

References: packages/…/__init__.py• L1-71 packages/…/_base.py• L18-145 packages/…/_defaults.py• L1-66 packages/…/_httpx.py• L56-129 packages/…/_aiohttp.py• L73-197 packages/…/CHANGELOG.md• L5-10

Resource APIs

The resource APIs express the main build-platform actions as typed operations. They preserve the relationships between projects, apps, environments, deployments, and provider targets instead of treating each request as an unrelated HTTP call.

Project and app management

Projects provide the access and usage boundary for apps. The project API supports project discovery and lifecycle work plus role, member, team, and audit controls. The app API then manages an app within that boundary, including its name, description, provider, running state, scale, rollout behavior, history, and runtime logs.

App sub-resources cover concerns that affect how an app runs or who can use it. Secrets apply as environment values, custom domains expose an app at a controlled name, environments form a promotion pipeline, managed databases provide shared Postgres storage, and sign-in controls access for the app's users.

References: packages/…/projects.py• L68-88 packages/…/projects.py• L402-526 packages/…/apps.py• L282-307 packages/…/apps.py• L344-390 packages/…/apps.py• L549-863

Environment pipelines

An environment pipeline separates the place where a new build first runs from later environments such as production. New deployments enter the first environment, and promotion reuses the tested build in the next environment with that environment's URL and secrets. This gives the service a path for approval and staged release without rebuilding the same source for every stage.

The pipeline keeps environment state distinct. Each environment can have its own secrets and running deployment, while production retains the app identity and history that existed before the pipeline was enabled.

References: packages/…/environments.py• L48-54 packages/…/environments.py• L64-97 packages/…/environments.py• L189-265

Provider accounts

Provider APIs connect the build service to a hosting target. The SDK can read whether an organization may use Google Cloud, manage verified Google Cloud connections, set a default connection, and obtain material for a self-managed Cloud Run deployment. App-level provider operations select where an app runs and whether its frontend also runs in the app's own container.

Provider changes affect the hosted app lifecycle rather than only a saved setting. The service may release resources on the old provider or stop an app before a new hosting mode takes effect, so callers should inspect the returned change state and deployment status.

References: packages/…/providers.py• L89-97 packages/…/providers.py• L300-455 packages/…/apps.py• L651-744

Platform support services

The SDK also exposes platform services that support the app lifecycle. Usage reports plan allowance shared by builder work and hosting. Security reviews accept a source archive and return typed findings. These services use the same client boundary and polling style as deployments, but their results describe allowance or source findings rather than a running app.

References: packages/…/usage.py• L42-101 packages/…/security_reviews.py• L43-142

Deployment helpers

Deployment helpers connect local build output to the hosted build service. They reserve the target URLs and upload locations, send the frontend and backend archives, submit deployment settings, and follow the service-owned build until it is live, awaiting approval, or failed.

Build handoff

The deployment flow starts by reserving the frontend and backend URLs that the local export must use. The caller then supplies the resulting archives to deployments.create. The SDK reserves signed storage targets, streams both archives to storage, and submits a deployment form that carries app identity, placement, machine size, secrets, package needs, rollout strategy, and version metadata.

The signed upload URLs are the credentials for the archive transfer. The upload does not send the API access token to storage. The uploader keeps memory use bounded, reports combined progress, and can reserve fresh targets when an upload URL expires.

This diagram shows the handoff from local export to the service-owned deployment.

flowchart LR
    A[Reserve hostname] --> B[Export frontend and backend]
    B --> C[Reserve signed upload targets]
    C --> D[Stream backend and frontend archives]
    D --> E[Submit deployment settings]
    E --> F[Build service runs deployment]

References: packages/…/apps.py• L746-773 packages/…/deployments.py• L75-162 packages/…/_deploy.py• L21-40 packages/…/_deploy.py• L161-307

Deployment state

Deployment observation separates short status messages from the recorded deployment report. wait polls for a final outcome and checks the report at intervals so a stale status source does not hide a failure. It returns when the deployment is running or awaiting approval and raises a deployment error when the service rejects or fails the build.

The deployment API also exposes validation before export, full build logs, available regions and machine sizes, deployment history, rollback, and descriptions. A caller can therefore validate target settings early and use the report or log excerpt to explain a failed build.

References: packages/…/deployments.py• L222-368 packages/…/deployments.py• L390-411 packages/…/types.py• L143-188

Typed response model

The SDK presents service results as immutable typed data models rather than raw JSON dictionaries. These models give callers stable names for identities, app and deployment state, environment transitions, provider results, usage records, and review findings.

Response decoding

The decoder maps JSON values into dataclasses, lists, dictionaries, tuples, unions, enums, dates, and UUIDs. It supports response field names that differ from Python field names and reports the path of a mismatched value. Unknown object fields are ignored, which lets a model continue to read responses that gain new server fields.

Resource methods choose the expected model for each successful response. This keeps wire-format knowledge at the SDK boundary and gives callers a clear failure when the service response no longer matches the expected contract.

References: packages/…/_decode.py• L56-104 packages/…/_decode.py• L352-395 packages/…/_base.py• L311-334

Type definitions

types.py defines the public data vocabulary for the service. It covers the main resource results and the state values needed to reason about app hosting, deployment progress, environment promotion, access scope, provider readiness, usage, and security review output.

The definitions are aligned with the checked-in OpenAPI snapshot where the service publishes a schema. The schema check verifies that model fields and nested types can decode the values allowed by that snapshot, while models for responses that the schema leaves untyped are tracked separately. This gives API changes a visible compatibility check without making the public client depend on raw schema objects.

References: packages/…/types.py• L13-21 packages/…/types.py• L110-188 packages/…/types.py• L301-363 tests/…/schema_check.py• L1-187 tests/…/test_types.py• L21-135

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the async resource API and the generated sync resource API aligned. The _async tree is the source for the synchronous tree, so a resource contract change must flow through the generation step.
  • Keep deployment URL reservation, local export settings, archive upload names, and deployment submission fields aligned. A mismatch can produce an archive that builds but cannot serve the expected frontend or backend.
  • Keep signed upload reservation results and archive upload behavior compatible. The storage target carries its own credential and exact content length.
  • Keep retry safety metadata aligned with endpoint behavior. A request marked repeatable must converge when the service has already applied the first attempt.
  • Update types.py, JSON field-name metadata, and the OpenAPI snapshot checks together when a service response changes. A renamed or newly required field can fail only when that response is decoded.
  • Keep token precedence and full-access restrictions clear when adding privileged resource actions. The SDK accepts an explicit token or REFLEX_ACCESS_TOKEN; a token obtained by browser login is not read from a local SDK credential file.
  • Preserve provider and environment state transitions when changing app settings. Provider switches, frontend hosting mode changes, and promotions can stop or move a running app.
  • Keep the workspace dependency and enabled transport extras aligned with the client modes used by repository tools. A dependency change can make a supported sync or async client unavailable in development.
  • Keep the documented default transport order aligned with optional transport imports and default_transport(). A change to the installed-library preference or wrapper helper changes which HTTP behavior a caller receives without changing resource code.

Important failure modes

TriggerConsequenceGuard
No token is available for an authenticated operationThe request fails before it reaches the build service.Pass token= or set REFLEX_ACCESS_TOKEN.
No supported HTTP library is installed and no transport is suppliedClient creation fails before it can send a request.Install the extra for aiohttp, httpx2, or httpx, or provide a compatible transport.
A restricted login token calls token, provider-management, database, or sign-in write APIsThe service refuses the action even though the token can read some resources.Use a full-access token or a suitably scoped service token.
Archives are exported before the hostname reservation or with mismatched frontend and backend filesThe deployment can use the wrong public URLs or fail during upload or submission.Reserve URLs first and pass the paired export archives to deployments.create.
A signed upload URL expires or storage rejects an archiveThe deployment cannot be submitted with that upload reservation.Let the SDK retry the upload with a fresh reservation and keep the archives available.
A deployment remains pending past the caller's wait limitwait raises DeploymentTimeoutError even though the service may continue the deployment.Treat timeout as an observation limit, then inspect status or report again.
A deployment is rejected, fails, or is replacedwait raises DeploymentFailedError with a report and possible build-log excerpt.Read the report, fault, guidance, and build logs before retrying.
A response field or type no longer matches the SDK modelThe call raises APIResponseValidationError instead of returning a partial result.Refresh the schema snapshot and update the model and field mapping as one contract change.
A caller closes a client around a caller-owned transportThe client leaves that transport open, so its connections remain active.Close externally supplied transports through their owning application lifecycle.
A provider switch or full-deploy change stops the app before the new state is readyThe app can remain stopped or need operator recovery.Check the returned change state and hosted deployment status after the operation.

Key files

FileWhy to read it
packages/…/README.mdShows the public client use cases, resource groups, deployment flow, authentication choices, and transport options.
packages/…/CHANGELOG.mdRecords public SDK contract changes, including optional transport extras and the default_transport() helper.
pyproject.tomlShows how repository development resolves the SDK workspace package and enables its transport extras.
packages/…/_client.pyDefines the asynchronous client boundary and the resource surface used as the source for sync client generation.
packages/…/_client.pyShows the synchronous client lifecycle, transport ownership, request execution, retries, and response handling.
packages/…/_base.pyDefines shared URL, token, request, retry, and successful-response behavior.
packages/…/__init__.pyDefines the public transport surface and lazy loading for optional HTTP libraries.
packages/…/_defaults.pyDefines the fallback order for synchronous and asynchronous default transports.
packages/…/auth.pyDefines browser login and access-token operations exposed through the resource surface.
packages/…/apps.pyShows the central app API and its nested secrets, domains, environments, database, and sign-in resources.
packages/…/deployments.pyShows deployment validation, archive submission, polling, reports, logs, and target discovery.
packages/…/_deploy.pyDefines the shared signed-upload and deployment-outcome rules.
packages/…/projects.pyShows project ownership, access roles, members, teams, and audit records.
packages/…/providers.pyShows connected Google Cloud account management and self-managed Cloud Run support.
packages/…/_decode.pyDefines conversion from service JSON to typed SDK values and validation errors.
packages/…/types.pyDefines the typed service results returned by resource APIs.
packages/…/unasync.pyExplains how synchronous clients and resource modules stay aligned with asynchronous source modules.
packages/…/openapi.jsonProvides the checked-in service schema snapshot used for model compatibility checks.
tests/…/schema_check.pyShows how model fields and types are compared with the service schema.