Skip to content

About

Sunday HTTP runtime for generated Python clients and servers

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Sunday Python

Sunday Python is the shared HTTP runtime for Python clients and servers generated by Sunday Generator. It provides declarative operations, typed RFC problem responses, media codecs, parameter serialization, reusable streaming bodies, and server-sent event support.

The package is currently in beta. No PyPI release has been published yet.

Installation

Until the first PyPI release, install Sunday Python from its GitHub beta tag. A requirements.txt entry for the transport-neutral core is:

sunday-python @ git+https://github.com/outfoxx/sunday-python.git@2.0.0-beta.1

Select adapters and optional codecs with extras:

sunday-python[httpx] @ git+https://github.com/outfoxx/sunday-python.git@2.0.0-beta.1
sunday-python[litestar] @ git+https://github.com/outfoxx/sunday-python.git@2.0.0-beta.1
sunday-python[httpx,litestar,cbor,xml,yaml] @ git+https://github.com/outfoxx/sunday-python.git@2.0.0-beta.1

Install the requirements with pip:

python -m pip install -r requirements.txt

Git must be available for this temporary VCS-based installation. The distribution is named sunday-python; public APIs are imported from sunday. These instructions will switch to ordinary PyPI version requirements after publication.

The core and adapters are separate import modules within that distribution. Generated clients depend only on sunday; applications opt into an adapter with its matching extra and import it from sunday.<adapter>. Installing the core alone does not install HTTPX or AnyIO. Importing sunday.httpx without its extra reports the required install command.

Generated clients accept a sunday.Transport implementation. The simplest HTTPX setup lets the transport create and own its client:

from sunday.httpx import HttpxTransport

from example_api.projects import ProjectsClient

async with HttpxTransport(base_url="https://api.example.test") as transport:
    client = ProjectsClient(transport)
    project = await client.get_project("project-1").execute()

Pass an existing client when the application needs custom HTTPX configuration or shares a pool. A supplied client is borrowed and remains the application's lifecycle responsibility:

import httpx

async with httpx.AsyncClient(base_url="https://api.example.test", timeout=30) as http_client:
    async with HttpxTransport(http_client) as transport:
        client = ProjectsClient(transport)
        project = await client.get_project("project-1").execute()

transport.client exposes the active client in both modes. Supplying both a client and base_url is an error.

Litestar binary requests

Generated Litestar handlers can call await sunday.litestar.request_bytes(request, media_types) for a whole binary body. The helper reads the original bytes without JSON/base64 decoding and uses the shared MediaType matcher to check every declared range, including image/* and */*. Unsupported media produces HTTP 415; malformed Content-Type produces HTTP 400. An absent header is treated as application/octet-stream, and an empty range list accepts any concrete media type. Matching ignores case and media parameters while explicit header arguments preserve the original value. Litestar's request body size limit continues to apply.

Keep JSON/base64 values and binary fields within models on the structured decoding path. The binary helper is for the whole request body. It is new after 2.0.0-beta.1; use this checkout until a tag containing the helper is released.

Future transport adapters will follow the same module and extra convention without changing generated clients. Because the package is still in beta, the former sunday.httpx_compat and sunday.httpx_sse modules are not retained.

Requests and native exchange

Sunday transports expose the same high-level workflow as the Kotlin, Swift, and TypeScript runtimes:

Sunday concept Python API
Build native request transport_request()
Return native response transport_response()
Decode result with metadata response()
Decode result only result()

BaseTransport implements this orchestration for custom adapters. Implementations provide protected _prepare_request(), _send(), and _decode_response() hooks. HTTPX preparation only builds the request; managed execution adapts immediately before each send. Request export adapts once and hands execution to the consumer (for example, await client.send(exported)). Calling transport_response() explicitly starts a new managed execution and applies its adapters.

Generated clients expose their transport, default_content_types, and default_accept_types. Operation-specific media declarations take precedence when they cannot use the client defaults, and an explicit Content-Type header remains authoritative.

Profiled credentials

Generated operations carry selected SecurityBinding metadata in RequestSpec.security. Applications compose providers explicitly with HttpxTransport(..., **authentication_adapters(providers)). Providers and token storage stay in the application; generated code contains no credentials.

import httpx
from sunday import TokenManager
from sunday.httpx import HttpxOAuthTokenProvider, HttpxTransport, authentication_adapters


def create_transport(client: httpx.AsyncClient, client_secret: str) -> HttpxTransport:
    # The caller owns and closes the borrowed client.
    provider = HttpxOAuthTokenProvider(
        client,
        identity="service-credential-v1",
        client_id="service-client",
        client_secret=client_secret,
        authentication="client_secret_basic",
    )
    return HttpxTransport(
        client,
        **authentication_adapters({"service-identity": TokenManager(provider)}),
    )

For an interactive public client, use authentication="none", a fresh grant_identity, and an async authorization(request) callback returning AuthorizationGrant(code, redirect_uri, code_verifier). The application performs the browser flow using S256 PKCE and verifies state, issuer, and redirect URI before supplying the result. A code is consumed once, even if exchange fails or is canceled. An expired session without refresh capability, or an invalid interactive refresh grant, raises AuthorizationRequiredError; supply fresh application authorization with a new grant identity. Discovery requires the separately configured issuer. Acquisition endpoints overrides do not change it. Token exchanges support client_secret_basic, client_secret_post, and public-client none authentication; other methods use an application TokenProvider. HTTPS is required except for loopback development URLs.

Custom TokenProvider implementations supply external or static credentials through configure and acquire; implementing refresh adds optional refresh capability. TokenSet.expires_at is Unix seconds. Return a new refresh_token when it rotates; omitting it retains the previous token. Provider exceptions become safe TokenProviderError diagnostics. Cancellation still propagates normally.

Cache keys include provider/client identity, grant identity, profile, flow, resolved endpoints, scopes, audience, and resource. Change provider identity when credential configuration changes, and grant identity when session or grant inputs change. Share one manager on one asyncio event loop across generated clients; its optional TokenStore supports application-owned storage. The manager coalesces renewal and defaults to 30 seconds of expiry skew. Canceling one waiter preserves other waiters; canceling the last cancels acquisition. Once persistence starts, saving a rotated token finishes even if callers cancel. A provider result arriving after cancellation cannot start persistence; if the identity server already consumed the refresh token despite cancellation, the interactive session requires fresh authorization.

HTTPX attaches every credential in the selected AND alternative at send time, once per attempt. Native request construction does not acquire credentials. Borrowed-client default Authorization headers are removed from managed requests; explicit conflicting credentials fail rather than being combined. Missing providers or conflicting credentials fail before network access. It checks credentials on every execution, including reused native requests. A bodyless GET/HEAD/OPTIONS receiving 401 with a bearer invalid_token challenge may renew and replay once; POST, streamed bodies, and 403 never trigger automatic replay. Managed credential requests do not follow redirects or apply HTTPX client-level auth. Managed query/header/cookie credentials are redacted from Sunday observers and response/error request diagnostics. Plain request adapters retain their existing behavior when no managed binding is selected.

Credentials are isolated by logical security scheme as well as provider and acquisition inputs. Discovery metadata is fetched and verified on each acquisition or renewal. Temporary provider outages allow event connections to reconnect; a rejected refresh grant triggers fresh client credentials only for the client-credentials flow. Interactive sessions require fresh application authorization. Built-in OAuth providers retain at most 1,024 consumed authorization-code hashes per provider instance. After this limit, create a provider for a newly authorized application session; old hashes are never evicted to allow code reuse. Refresh exchanges do not consume this history. Token managers similarly retain at most 1,024 hashed interactive grant-attempt identities, including failed attempts, and fail closed for further first-time authorizations. Start a fresh manager/provider lifecycle with fresh application authorization when that bound is reached; never recycle a consumed grant identity.

Errors

Sunday-originated failures are grouped as RequestEncodingError, ResponseDecodingError, ResponseValidationError, and TransportError. UnexpectedResponse is a response-validation error retaining status, content type, body, and native response diagnostics. Typed RFC problems remain Problem exceptions, while native transport, adapter, and cancellation exceptions are not indiscriminately wrapped.

RequestSpec accepts ordinary OpenAPI path placeholders or a URITemplate for RFC 6570 expansion. RFC template values are supplied separately through template_parameters, remain unencoded until expansion, and are not serialized again as ordinary operation parameters.

Media codecs

Default codec registries use JSON, form-urlencoded, text, and binary codecs and automatically add installed CBOR, XML, and YAML extras. Their deterministic preference order is JSON, CBOR, XML, YAML, form-urlencoded, text, then binary. Passing a custom encoder or decoder registry is authoritative and disables this automatic composition. Request content negotiation honors an explicit Content-Type; otherwise it selects the first declared installed encoder. Generated Accept values include only installed decoders.

Model validation

Generated models use Pydantic's native validation API. Select the payload mode with Item.model_validate(item, strict=True, context={"mode": ModelMode.REQUEST}), or an equivalent TypeAdapter call. Response mode permits declared tolerant fallbacks; request mode rejects them unless the schema explicitly allows them. Constructors use response semantics.

SundayModel rechecks current instance values, including mutations, without changing the application model, its extras, or its field-presence set. An ambiguous extra key that would overwrite a field or be promoted into an omitted field during revalidation produces model_key_conflict at its original path. Normal alias/name input selection remains Pydantic behavior. Litestar's SundayPlugin selects request mode before invoking application handlers; Sunday transports check every execution before encoding.

Litestar composite request bodies

SundayPlugin validates list, map, and optional Sunday models in request mode through Litestar’s native decoders. Litestar’s msgspec decoder cannot accept unions containing multiple custom model classes. For such bodies, use await request_model(TypeAdapter(First | Second), request, "application/json") before invoking application logic. The helper delegates to Pydantic with request context and translates malformed JSON, unknown enum values, and rejected union fallbacks to HTTP 400.

TolerantStrEnum explicitly designates UNKNOWN (or __unknown_member_name__) as its fallback. Request mode rejects that member even when directly constructed. A normal schema that merely declares an UNKNOWN value uses StrEnum, for which the declared value remains valid.

Server-sent events

Typed EventStream[T] values retain the async-iterator lifecycle. Raw EventSource values use synchronous management on a running AsyncIO loop: assign on_open, on_error, or on_message, register event-specific listeners, call connect(), and call close() when finished. connect() returns immediately in the connecting state. The source exposes ready_state and its current retry_time; closing is idempotent and immediately changes the state to closed while response cleanup completes on the loop. Calling connect() immediately after close() starts a new run with its own stream; transport shutdown also waits for any retiring runs.

HTTPX applications can construct a raw source from a declarative request with HttpxTransport.event_source() or from a synchronous or asynchronous native request factory with event_source_from(). Reconnect requests receive the SSE headers and Last-Event-ID before transport adapters run once.

Reconnects begin at 500 ms and use capped exponential backoff. The first retry is exact; consecutive failed connections apply 0.9–1.0 downward jitter to later attempts. The default maximum is 30 times the current base retry, while a configured maximum or positive server retry-max: control fixes the cap. Opening a valid stream resets escalation, so a stream that later ends reconnects at its current base interval. Positive retry: and retry-max: values are expressed in milliseconds on the wire.

Quiet streams have no timeout by default. A server opts into stuck-stream detection by sending a positive keepalive:<milliseconds> control, which sets the timeout to three keepalive intervals with a one-second floor. Receiving any bytes, including SSE comments, resets that deadline. The keepalive promise applies only to the current connection; each reconnect starts without a silence timeout until the server sends another positive keepalive. HTTPX read timeouts are disabled for SSE requests so borrowed-client settings cannot accidentally enable stuck-stream detection.

Development

Python 3.12 and uv are required for local development.

uv sync --all-extras
mise run check

See CONTRIBUTING.md for the validation and release rules. The parity matrix records the generator IR boundary and intentional exclusions for the first beta. The beta migration guide covers the breaking transport, client, ownership, and error changes.

Model revalidation requires Pydantic 2.13 or newer, including native dictionary-subclass alias lookup and field-presence handling.

Typed request parameters

RequestSpec.parameter_validation checks captured typed parameters before each native request is built, including requests without a body. Generated callbacks use Pydantic request-mode validation; failures become RequestEncodingError. Custom transports must call validate_parameters() before encoding parameters on every execution. Litestar query_model also validates in request mode and returns HTTP 400 before invoking application code when validation fails.

Typed PATCH models

Generated partial-update models extend SundayPatchModel. Each field supports UNSET for unchanged, a value to set, and None only when the schema permits deleting the member. JSON Merge Patch null means deletion, never assignment of a literal null. Omitted constructor arguments are UNSET; schema defaults never become implicit updates.

from pydantic import Field
from sunday import UNSET, SundayPatchModel, UnsetType, is_unset

class ItemPatch(SundayPatchModel):
    name: str | UnsetType = Field(default_factory=lambda: UNSET, exclude_if=is_unset, min_length=2)
    description: str | UnsetType | None = Field(default_factory=lambda: UNSET, exclude_if=is_unset)

patch = ItemPatch(name="New name", description=None)
patch.name = UNSET  # Cancel the name update.
assert patch.model_dump(mode="json") == {"description": None}

Pydantic selects aliases and field names before the runtime handles UNSET. Supplied values retain normal field validation, including validation during request-mode instance revalidation. UNSET is a typed, copyable, picklable singleton; it is omitted from JSON Schema and serialization by the field configuration above. A literal string "UNSET" remains an ordinary string value. Keep the default_factory and exclude_if configuration when defining patch models manually.

Explicit standard authentication

Choose standard authentication once in the transport factory supplied to generated clients. StandardAuthenticationAdapter composes credential attachment, missing-provider checks, rejection feedback, and terminal bearer-rejection cancellation. It delegates to the existing adapters, including their body ownership rules, and ignores public/detached operation responses. Feedback runs before cancellation. There is no hidden replay; a later explicit request can obtain renewed credentials.

The standard settings helper selects this policy on both sides. Lower-level AuthenticationAdapter remains available when an application wants feedback without the standard stop policy. Ordinary transport constructors perform no authentication and do not install this composition.

from sunday.httpx import HttpxTransport, transport_from_settings

# Keep the HTTPX client open for the lifetime of the generated clients.
async with httpx.AsyncClient(base_url=base_url) as client:
    def standard_factory(settings):
        return transport_from_settings(settings, client)

    # Pass standard_factory to the generated configuration-based factory,
    # or construct a generated service with this caller-owned transport:
    custom_transport = HttpxTransport(
        client, request_adapter=auth0_link, response_adapter=auth0_link,
    )

Caching is a separate explicit choice: construct TokenManager around a Sunday OAuth provider and supply that manager through provider credentials to the generated factory. This retains expiry renewal, refresh rotation, and application-selected storage. A provider returned by an OAuth credential factory can likewise be an explicitly constructed manager. Supplied external providers are used unchanged; standard composition never wraps them, creates a second cache, closes them, or clears their storage. Keep managers at application/session scope, share them across clients using the same credential lifecycle, and settle outstanding requests before closing managers or clearing credentials.

Static bearer, basic, and API-key credentials use their declared placement without an OAuth cache. Only an explicit Bearer invalid_token challenge for a sent bearer credential invokes the bearer stop policy; 403s and unrelated challenges retain ordinary response handling. Authentication selection and credential validation in generated settings remain active for the standard path. The direct-transport path lets a custom adapter own those choices using operation metadata.

Application-owned token lifecycle

Transport constructors perform no authentication or authorization by default. They accept request and response adapters, with no token-provider option or authentication retry loop. External authentication frameworks can implement these adapters directly, without using Sunday's token or security classes.

The optional AuthenticationAdapter acquires credentials for declared bindings, reports missing providers, and sends matching rejection feedback to the credential owner. Install it explicitly in each desired slot; installing a request adapter alone does not install response behavior. It adds no cache.

BearerTokenRejectionAdapter is a separate, opt-in response policy. It throws the cancellation marker when an initiating request sent a bearer credential and its response is 401 with an explicit Bearer invalid_token challenge. It leaves all other responses and all bodies untouched. Compose it after AuthenticationAdapter when provider feedback should run before cancellation. It has no counter, renewal, or replay behavior. The removed AuthenticationRecoveryBudget has no implicit replacement: applications choose their own recovery policy, and a cancellation-marked error always stops the exchange, retries, and SSE reconnections. An external framework (for example Auth0) remains responsible for storage, renewal and logout. Return only its access token and optional expiry; keep its refresh token inside that framework.

The provider-settings convenience transport_from_settings(...) explicitly installs the standard authentication composition. Use the ordinary transport constructor with your own adapters when you want to own the exchange entirely.

For Sunday's caching and refresh lifecycle, explicitly supply a TokenManager as the provider:

tokens = TokenManager(oauth_provider, store=application_store, expiry_skew=30, now=application_clock)
settings = ClientSettings.resolve(
    base_url, alternatives, {"identity": ProviderCredentials(tokens)},
)
# Supply an external framework's provider directly instead to keep its lifecycle authoritative.
from sunday.httpx import transport_from_settings
transport = transport_from_settings(settings, client)

Managers retain expiry skew, coalesced renewal, refresh rotation and application-selected persistence. Use a manager on one asyncio loop; cancel and await requests before discarding it. Transport closure does not erase the store or close a shared provider. Separate managers do not coordinate refreshes merely because they share a store. Reuse the same manager across clients that share a credential lifecycle, and distinguish users/environments with provider and grant identities.

Providers can implement reject to handle an invalid bearer token. It receives the original request context and rejected access token, and returns whether recovery can proceed. Compare the rejected credential with the current session before renewing: a late rejection must not invalidate a newer token or a new login. Providers without this capability raise TokenRejectedError, a RequestCancellationError, on explicit invalid-token rejection. Acquisition and rejection must not start interactive login automatically; return an authorization-required failure to the caller. For an Auth0 adapter, retrieve through its credentials manager and force renewal through that same manager on rejection, serializing concurrent rejection handling without maintaining a second token cache.

Request export materializes an optionally authorized native request once and hands its lifecycle to the consumer. Exported requests retain no Sunday-managed recovery state. Executing an operation through Sunday invokes the request adapter once per attempt. Authentication responses do not trigger an implicit retry; an application may make another request after its credential owner handles the rejection.

Migration: replace transport tokenManager/token_manager and tokenProviders/token_providers arguments with explicit request/response adapters. Replace TokenManagerFactory hooks with explicitly constructed managers supplied through provider credentials. Direct built-in OAuth providers are not implicitly cached; wrap them explicitly when Sunday should retain and refresh their tokens. For logout, stop outstanding requests and settle refresh commits before clearing the owning framework's or application's storage.

Custom transports implementing the Transport protocol must provide execute_request(spec) for operation execution. BaseTransport implements it through _prepare_request and _send. Keep transport_request(spec) as the caller-owned export path; do not route operation execution through an export override.

Request and response adapters

RequestAdapter and ResponseAdapter are independent ABCs in sunday.httpx. Implement async adapt(request) -> httpx.Request or async adapt(response, request) -> httpx.Response. Each provides chain_to(next_adapter). RequestAdapters and ResponseAdapters also accept async functions and flatten nested chains once at construction:

from sunday.httpx import HttpxTransport, RequestAdapters, ResponseAdapters, copy_request

async def add_header(request):
    return copy_request(request, headers=[*request.headers.multi_items(), ("X-Client", "example")])

async def inspect_response(response, request):
    # Headers are available before Sunday reads the body.
    return response

transport = HttpxTransport(
    client,
    request_adapter=RequestAdapters(add_header),
    response_adapter=ResponseAdapters(inspect_response),
)

Managed attempts prepare, adapt the request, send, and adapt the response before normal handling. No response capability is inferred from a request adapter. Optional AuthenticationAdapter owns provider rejection feedback; transport execution does not classify or retry token rejection. Cancellation markers stop the exchange. Native request export detaches operation bindings and leaves execution to the consumer.

Adapters surround each native HTTPX call. Borrowed-client event hooks, authentication flows, and transport-level connection recovery retain their native behavior; intermediate native responses are not guaranteed to reach Sunday adapters. Credentialed calls suppress native auth. Sunday handles allowed redirects after response adaptation, rerunning request adapters on each follow-up without accumulating header mutations. Buffered bodies and StreamingBody factories can be replayed for redirects; arbitrary one-shot request streams are not replayed. Credentialed redirects remain disabled. Allowed follow-ups use the native cookie jar, including its domain, path, and secure-cookie rules. Returned responses retain redirect and native authentication history; intermediate redirect bodies are buffered as in HTTPX, including during streaming execution. Native clients and connection pools are reused without reconfiguration.

An adapter that consumes or replaces a resource must close it and provide a replacement. HTTPX responses and headers are mutable; await response.aread() retains buffered content for subsequent readers. Return a new httpx.Response to replace the body. copy_request() preserves native extensions and shares an unread stream without consuming it; pass content=b"" to remove a body. Changing the URL authority updates Host unless the supplied headers explicitly override it. Replacing headers preserves an unchanged body's framing unless Content-Length or Transfer-Encoding is explicitly supplied. Buffering a chunked upload before copying it retains chunked framing without adding Content-Length; streams without known framing use chunked encoding. Use asynchronous streams; synchronous factories must not block the event loop.

Subclass sunday.RequestCancellationError to veto retries and SSE reconnects. Sunday propagates the original exception, including when it also subclasses an HTTPX error or Problem; encoding fallbacks and nullable operations never suppress it. This is distinct from asyncio.CancelledError: task cancellation follows Python semantics and is never swallowed. Cleanup waits for the response to close even when asyncio cancellation is pending or repeated, then propagates the original error. A cleanup failure does not replace an existing failure. Explicit closure and HTTPX's automatic EOF closure share one protected stream-close operation; concurrent closers join it until it finishes. Native sends and reads run behind a cancellation boundary that allows HTTPX/httpcore to finish internal cleanup before the original cancellation is rethrown. This also covers OAuth discovery and token exchanges. Transport shutdown shares one completion task across callers and waits for retiring EventSource runs before closing an owned client. A cancelled shutdown waiter does not cancel that shared cleanup. When an owned EventSource's adapter, native hook, or response-cleanup callback calls transport.aclose(), it requests shutdown without joining its own run; external callers still wait for cleanup to finish. This also applies to retiring runs after an immediate reconnect. Buffered collection uses HTTPX's bulk aread() with one owner task for the entire body; SSE uses its asynchronous byte iterator with cancellation bounded to each read. Use async with stream or explicitly await stream.aclose() when ending iteration early. Closing a stream interrupts and joins its active I/O, including header reception and response adaptation before the stream receives the response. It then joins response cleanup without waiting for application work between yielded events. Context cleanup preserves the consumer's original exception if cleanup fails. A close called inside that stream's own adapter, native hook, or response-cleanup callback requests closure without waiting on itself; external close callers wait for completion, including when callbacks delegate work to child tasks.

The existing adapters= argument remains supported for legacy (transport, request) adapters; it runs before the new request-adapter chain. Prefer the independent request_adapter= and response_adapter= arguments for new code. Generated code continues to use managed execute_request()/response() operations; generator migration is a separate step.

The adapter lifecycle audit records the recurring failure patterns, native-framework boundaries, and regression coverage used for this refactor.

Application-owned authentication adapters

Transports delegate requests directly to request_adapter and responses to response_adapter. request_security_bindings(request) from sunday.httpx exposes the generated operation's immutable audience, scopes, and credential-placement metadata. Copies and adapter composition preserve this metadata without adding wire headers or token receipts. Adapters run for all operations and responses; applications select the exchanges they own and must preserve usable request/response streams.

Raise RequestCancellationError to stop an exchange, or return the response for ordinary handling. Transports have no token-recovery retries. AuthenticationAdapter, authentication_adapters, and transport_from_settings provide optional provider composition outside transport execution.

About

Sunday HTTP runtime for generated Python clients and servers

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages