Ir para o conteúdo

tempest_fastapi_sdk.ssr

Renderização no servidor: componentes Python tipados renderizados para HTML.

« Web, UI e utilitários


ssr

Server-side rendering: typed Python components rendered to HTML.

Build your FastAPI service full-stack and fully typed — no template language. Declare pages as :class:Page subclasses (typed tempest_core components), and return :func:html_response from a route to render them to HTML on the server. Serve HTMX locally with :func:make_htmx_router for progressive, server-driven interactivity.

Build the open attrs map of a widget from typed keyword arguments with :func:htmx, :func:aria and :func:data — they turn hx-* / aria-* / data-* call sites from stringly-typed dicts into autocompleted, statically-checked code, returning exactly the plain dict[str, str] you would have written.

To ship a compiled tempestweb build instead of rendering per request, point the SDK at a tempestweb build output directory: :func:make_web_app_router serves a static (wasm) SPA build with a single-page history fallback, and :func:build_web_app hosts a server-mode build (WebSocket/SSE) as a mountable sub-application. :func:detect_build_mode tells the two apart.

Guard a destructive action with :func:confirm (or form_for(..., confirm=...)): the attribute is read by a locally-served listener, never interpolated into script. Carry a one-shot notice across a redirect with :class:FlashMiddleware, :func:flash and :func:get_flashes; send the browser back where it came from with :func:redirect_back, which refuses an off-host or off-prefix Referer; and let :func:register_html_error_handlers answer HTML routes with an error page or a flash-and-redirect while the API keeps its JSON.

The rendering backend (tempestweb) is imported lazily, so importing this package never hard-requires the optional [ssr] extra; the dependency is touched only when a page is actually rendered.

CONFIRM_ATTRIBUTE module-attribute

CONFIRM_ATTRIBUTE: str = 'data-confirm'

The attribute the bundled confirm.js listener reads.

A <form>, a submit <button> or an <a> carrying it asks window.confirm with the attribute's text before the browser acts.

GENERIC_ERROR_MESSAGE module-attribute

GENERIC_ERROR_MESSAGE: Final[str] = 'Não foi possível concluir a operação.'

Message shown when the JSON error response carries no string detail.

FLASH_COOKIE_NAME: Final[str] = 'tempest_flash'

Default name of the cookie that carries the pending messages.

MAX_FLASH_COOKIE_BYTES: Final[int] = 3800

Upper bound of the encoded cookie value.

Browsers drop a cookie above roughly 4096 bytes (name, value and attributes together) without telling the server. When the queue would exceed this bound the oldest messages are dropped first, so the most recent notice always arrives.

MAX_FLASH_MESSAGE_LENGTH module-attribute

MAX_FLASH_MESSAGE_LENGTH: Final[int] = 500

Characters kept per message; longer text is cut and ends with ….

FlashMiddleware

FlashMiddleware(
    app: ASGIApp,
    *,
    secret: str,
    cookie_name: str = FLASH_COOKIE_NAME,
    max_age: int = 300,
    path: str = "/",
    secure: bool = True,
    samesite: Literal["lax", "strict", "none"] = "lax",
)

Pure ASGI middleware that carries flash messages in a signed cookie.

Install it once; then :func:flash and :func:get_flashes work in every route and exception handler behind it.

The cookie is HttpOnly (no script reads it), SameSite=Lax by default and scoped to path. Its value is <payload>.<signature>, where the signature is HMAC-SHA256 over the payload with secret and a fixed context string, so the same secret used elsewhere cannot produce a valid flash cookie. A cookie that fails the signature, fails to decode, or is older than max_age seconds is ignored and deleted.

Example
from fastapi import FastAPI

from tempest_fastapi_sdk.ssr import FlashMiddleware

app: FastAPI = FastAPI()
app.add_middleware(FlashMiddleware, secret="a-long-random-secret-from-settings")

Initialize the middleware.

Parameters:

Name Type Description Default
app ASGIApp

The wrapped application.

required
secret str

The signing key. Load it from settings; at least 16 characters.

required
cookie_name str

Name of the flash cookie.

FLASH_COOKIE_NAME
max_age int

Seconds a queued message stays valid. A message not read within it is dropped.

300
path str

Cookie path.

'/'
secure bool

Emit the Secure flag. Keep True in production; False only for a plain-HTTP dev server.

True
samesite Literal['lax', 'strict', 'none']

SameSite policy. "lax" keeps the cookie on the top-level 303 that follows a form post.

'lax'

Raises:

Type Description
ValueError

When secret is shorter than 16 characters or max_age is not positive.

encode

encode(messages: list[FlashMessage]) -> str

Encode and sign messages into a cookie value.

Oldest messages are dropped until the value fits :data:MAX_FLASH_COOKIE_BYTES.

Parameters:

Name Type Description Default
messages list[FlashMessage]

The messages to carry.

required

Returns:

Name Type Description
str str

<payload>.<signature>; empty when nothing fits.

decode

decode(value: str) -> list[FlashMessage]

Verify and decode a cookie value.

Parameters:

Name Type Description Default
value str

The raw cookie value.

required

Returns:

Type Description
list[FlashMessage]

list[FlashMessage]: The carried messages; empty when the

list[FlashMessage]

signature does not verify, the value is malformed or it is

list[FlashMessage]

older than max_age.

Page

Bases: Component

Typed page base.

Subclass it, declare fields, and implement :meth:body. Optionally override :meth:shell to wrap every page in a shared layout. Do not override :meth:render — it is the Component hook and already composes shell(body()) for you.

Attributes:

Name Type Description
title str

The page title. :func:tempest_fastapi_sdk.ssr.html_response derives the document <title> from it (through :meth:document_title) when no title= is passed.

stylesheets ClassVar[Sequence[str]]

Stylesheet URLs the document links, in order. Read by :func:~tempest_fastapi_sdk.ssr.html_response when its stylesheets= argument is not passed. A class attribute, not a field: set it once on a base page and every subclass inherits it.

head ClassVar[str]

Raw markup appended to the document head (favicon, meta tags). Read by :func:~tempest_fastapi_sdk.ssr.html_response when its head= argument is not passed. Inserted verbatim, so it is a class constant and never built from request data.

title_suffix ClassVar[str]

Appended to :attr:title by :meth:document_title — " · tempest-bucket" turns the page titled "Buckets" into "Buckets · tempest-bucket".

Example
from tempest_core import Text, Widget

from tempest_fastapi_sdk.ui.pages import Page


class HomePage(Page):
    user_name: str

    def body(self) -> Widget:
        return Text(content=f"Olá, {self.user_name}", tag="h1")

document_title

document_title() -> str

Return the text of the document <title>.

Override it when the document title needs more than a suffix (a counter, a prefix that depends on a field).

Returns:

Name Type Description
str str

:attr:title followed by :attr:title_suffix.

body

body() -> Widget

Return the page's main content widget tree.

Subclasses must implement this.

Returns:

Name Type Description
Widget Widget

The widget tree for the page body.

Raises:

Type Description
NotImplementedError

When a subclass does not implement it.

shell

shell(body: Widget) -> Widget

Wrap the page body in a shared layout.

The default returns body unchanged. Override in a base page to add chrome (header / nav / footer) inherited by every concrete page — :class:~tempest_fastapi_sdk.ui.layout.Shell is the ready-made frame.

Parameters:

Name Type Description Default
body Widget

The widget tree returned by :meth:body.

required

Returns:

Name Type Description
Widget Widget

The wrapped widget tree.

render

render() -> Widget

Compose the page into a single widget tree.

This is the Component render hook. Subclasses override :meth:body and :meth:shell instead of this method.

Returns:

Name Type Description
Widget Widget

shell(body()) — the fully composed page.

make_htmx_router

make_htmx_router(prefix: str = '/_ssr', docs_locale: str | None = None) -> APIRouter

Build a router that serves the bundled SSR scripts locally.

The files are read once, at call time, so a real htmx.min.js dropped into the package after import is still picked up when the router is constructed.

Parameters:

Name Type Description Default
prefix str

The router prefix. Defaults to "/_ssr", matching the <script> paths that :func:tempest_fastapi_sdk.ssr.html_response emits. Change both together if you customize it.

'/_ssr'
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
An APIRouter

class:~fastapi.APIRouter exposing GET {prefix}/htmx.js

APIRouter

(the bundled HTMX) and GET {prefix}/confirm.js (the

APIRouter

data-confirm listener), both with an

APIRouter

application/javascript media type.

aria

aria(
    *,
    label: str | None = None,
    labelledby: str | None = None,
    describedby: str | None = None,
    hidden: bool | None = None,
    expanded: bool | None = None,
    selected: bool | None = None,
    checked: bool | None = None,
    disabled: bool | None = None,
    pressed: bool | None = None,
    busy: bool | None = None,
    live: str | None = None,
    current: str | None = None,
    controls: str | None = None,
    haspopup: str | None = None,
    role: str | None = None,
) -> dict[str, str]

Build ARIA / role attributes for an accessible widget.

Only the arguments you pass appear in the result. role is emitted as the bare role attribute; every other argument becomes aria-<name>. Booleans render as "true" / "false".

Parameters:

Name Type Description Default
label str | None

aria-label.

None
labelledby str | None

aria-labelledby.

None
describedby str | None

aria-describedby.

None
hidden bool | None

aria-hidden.

None
expanded bool | None

aria-expanded.

None
selected bool | None

aria-selected.

None
checked bool | None

aria-checked.

None
disabled bool | None

aria-disabled.

None
pressed bool | None

aria-pressed.

None
busy bool | None

aria-busy.

None
live str | None

aria-live (polite / assertive / off).

None
current str | None

aria-current (page / step / true …).

None
controls str | None

aria-controls.

None
haspopup str | None

aria-haspopup.

None
role str | None

The role attribute (not aria- prefixed).

None

Returns:

Type Description
dict[str, str]

dict[str, str]: The ARIA/role attributes, ready to spread into

dict[str, str]

attrs=.

confirm

confirm(message: str) -> dict[str, str]

Build the data-confirm attribute that guards a destructive action.

Spread it into attrs= of a submit <button>, a <form> or an <a>. :func:~tempest_fastapi_sdk.ssr.html_response includes the locally-served /_ssr/confirm.js whenever the rendered document carries the attribute, and that script asks window.confirm with this text before the submit (or the navigation) goes ahead.

The message is an attribute value, escaped by the renderer and read back by the script with getAttribute — it is never interpolated into JavaScript, so a message quoting a user-supplied name (f"Remover {name}?") cannot inject script. Without JavaScript the element keeps working, just without the question.

For an element that fires an HTMX request, prefer htmx(confirm=...) (hx-confirm), which HTMX reads itself.

Parameters:

Name Type Description Default
message str

The question shown in the confirmation dialog.

required

Returns:

Type Description
dict[str, str]

dict[str, str]: {"data-confirm": message}.

Raises:

Type Description
ValueError

When message is blank — an empty dialog asks nothing, and the listener ignores an empty attribute.

data

data(**items: str | int | float | bool) -> dict[str, str]

Build data-* attributes from keyword arguments.

Underscores in a key become hyphens (user_id → data-user-id). Values are stringified; booleans render as "true" / "false".

Parameters:

Name Type Description Default
**items str | int | float | bool

The data attributes.

{}

Returns:

Type Description
dict[str, str]

dict[str, str]: The data-* attributes, ready to spread into

dict[str, str]

attrs=.

htmx

htmx(
    *,
    get: str | None = None,
    post: str | None = None,
    put: str | None = None,
    patch: str | None = None,
    delete: str | None = None,
    target: str | None = None,
    swap: str | None = None,
    trigger: str | None = None,
    select: str | None = None,
    include: str | None = None,
    indicator: str | None = None,
    confirm: str | None = None,
    prompt: str | None = None,
    push_url: bool | str | None = None,
    swap_oob: bool | str | None = None,
    boost: bool | None = None,
    disable: bool | None = None,
    encoding: str | None = None,
    ext: str | None = None,
    sync: str | None = None,
    params: str | None = None,
    vals: str | dict[str, Any] | None = None,
    headers: str | dict[str, Any] | None = None,
    on: dict[str, str] | None = None,
) -> dict[str, str]

Build the hx-* attribute map for an HTMX-driven widget.

Only the arguments you pass appear in the result. Exactly one of get/post/put/patch/delete is the usual choice (the request the element fires). vals / headers accept a mapping and are JSON-encoded for you; on maps an event spec to inline JS and becomes hx-on:<event> (e.g. on={":after-request": "this.reset()"} → hx-on::after-request).

Parameters:

Name Type Description Default
get str | None

URL for hx-get.

None
post str | None

URL for hx-post.

None
put str | None

URL for hx-put.

None
patch str | None

URL for hx-patch.

None
delete str | None

URL for hx-delete.

None
target str | None

CSS selector for hx-target.

None
swap str | None

Swap strategy (outerHTML, beforeend, …).

None
trigger str | None

Trigger spec for hx-trigger.

None
select str | None

Response subset selector for hx-select.

None
include str | None

Extra elements to include (hx-include).

None
indicator str | None

Loading-indicator selector (hx-indicator).

None
confirm str | None

confirm() message (hx-confirm).

None
prompt str | None

prompt() message (hx-prompt).

None
push_url bool | str | None

hx-push-url (True or a URL).

None
swap_oob bool | str | None

hx-swap-oob (True or a strategy).

None
boost bool | None

hx-boost.

None
disable bool | None

hx-disable.

None
encoding str | None

hx-encoding (e.g. multipart/form-data).

None
ext str | None

Extensions for hx-ext.

None
sync str | None

hx-sync spec.

None
params str | None

hx-params spec.

None
vals str | dict[str, Any] | None

hx-vals — a mapping is JSON-encoded.

None
headers str | dict[str, Any] | None

hx-headers — a mapping is JSON-encoded.

None
on dict[str, str] | None

Event spec → inline JS, each emitted as hx-on:<event>.

None

Returns:

Type Description
dict[str, str]

dict[str, str]: The hx-* attributes, ready to spread into

dict[str, str]

attrs=.

register_html_error_handlers

register_html_error_handlers(
    app: FastAPI,
    *,
    prefixes: Sequence[str] = (),
    tags: Sequence[str] = (),
    error_page: type[ErrorPage] = ErrorPage,
    fallback: str | None = None,
) -> None

Answer HTML routes with an error page or a flash-and-redirect.

Call it after :func:tempest_fastapi_sdk.register_exception_handlers (when the service uses it). It wraps the :class:AppException and HTTPException handlers registered on app: the wrapped handler always runs first — so logging, catalog localization and on_server_error behave exactly as for the API — and then, for a request to an HTML route:

  • GET / HEAD answers error_page rendered with the same status code and the (localized) detail;
  • any other method queues the detail as an "error" flash and answers 303 back to the Referer through :func:~tempest_fastapi_sdk.ssr.redirect_back, validated against the matched prefix. Without :class:~tempest_fastapi_sdk.ssr.FlashMiddleware the message would be lost, so the error page is rendered instead.

Every other request keeps the JSON response untouched.

Parameters:

Name Type Description Default
app FastAPI

The application.

required
prefixes Sequence[str]

Path prefixes of the HTML routes ("/admin" matches /admin and /admin/..., not /administrator).

()
tags Sequence[str]

Router tags that mark a route as HTML. Only a matched route has tags, so an unknown path is recognised by prefix alone.

()
error_page type[ErrorPage]

The page class rendered on reads, built through :meth:ErrorPage.from_error. Combine :class:~tempest_fastapi_sdk.ui.pages.ErrorPage with the service's base page to inherit its chrome and head; set its title_template to change the "Erro {status_code}" title.

ErrorPage
fallback str | None

Where the redirect goes when the Referer is refused. None uses the matched prefix, or "/" for a route matched by tag.

None

Raises:

Type Description
ValueError

When neither prefixes nor tags is given — there would be no HTML route to handle.

flash

flash(request: Request, message: str, variant: AlertVariant = 'info') -> None

Queue a message for the next screen this user sees.

Call it before returning the redirect; :class:FlashMiddleware writes the queue into the signed cookie on that response. Text longer than :data:MAX_FLASH_MESSAGE_LENGTH is cut.

Parameters:

Name Type Description Default
request Request

The current request.

required
message str

The notice text. Rendered escaped, but carried readable in the cookie — never put in it what the user may not see.

required
variant AlertVariant

The severity.

'info'

Raises:

Type Description
RuntimeError

When :class:FlashMiddleware is not installed — a message queued without it would be lost silently.

flash_enabled

flash_enabled(request: Request) -> bool

Tell whether :class:FlashMiddleware is handling this request.

Parameters:

Name Type Description Default
request Request

The current request.

required

Returns:

Name Type Description
bool bool

True when :func:flash and :func:get_flashes can be

bool

called for request.

get_flashes

get_flashes(request: Request) -> list[FlashMessage]

Return every pending message and mark them read.

Pending means the ones the request's cookie carried plus the ones queued by :func:flash during this request. After this call the middleware clears the cookie on the response, so a reload does not repeat them.

Parameters:

Name Type Description Default
request Request

The current request.

required

Returns:

Type Description
list[FlashMessage]

list[FlashMessage]: The messages, oldest first; empty when there

list[FlashMessage]

are none.

Raises:

Type Description
RuntimeError

When :class:FlashMiddleware is not installed.

back_url

back_url(request: Request, *, allowed_prefix: str = '/') -> str | None

Return the validated relative URL of the page the request came from.

Parameters:

Name Type Description Default
request Request

The current request.

required
allowed_prefix str

Only a Referer path under this prefix is accepted (segment boundary: "/admin" does not admit /administrator). "/" accepts any path on this host.

'/'

Returns:

Type Description
str | None

str | None: path (plus ?query when present) of the

str | None

Referer, or None when the header is missing, is not an

str | None

absolute http/https URL, names another host (or carries

str | None

user info), or its path is outside the prefix or unsafe.

redirect_back

redirect_back(
    request: Request,
    *,
    fallback: str,
    allowed_prefix: str = "/",
    status_code: int = 303,
) -> RedirectResponse

Redirect to the page the request came from, or to a fallback.

The Referer is followed only when it names this host (compared with the request's own Host) and a path under allowed_prefix; anything else — another host, no host, a //evil.example path, a javascript: URL, a path outside the prefix — goes to fallback. The Location sent is always the relative path, so even a header that passed cannot change the origin.

Parameters:

Name Type Description Default
request Request

The current request.

required
fallback str

Where to go when the Referer is refused. It is emitted as given, so it comes from code, never from the request.

required
allowed_prefix str

The path prefix the Referer must sit under. "/" (the default) accepts any path on this host.

'/'
status_code int

The redirect status. 303 (the default) makes the browser follow with a GET, which is what a form post wants.

303

Returns:

Name Type Description
RedirectResponse RedirectResponse

The redirect.

Example
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse

from tempest_fastapi_sdk.ssr import redirect_back

app: FastAPI = FastAPI()


@app.post("/admin/buckets/{name}/delete")
async def delete_bucket(request: Request, name: str) -> RedirectResponse:
    return redirect_back(request, fallback="/admin", allowed_prefix="/admin")

html_response

html_response(
    widget: Widget,
    *,
    title: str | None = None,
    status_code: int = 200,
    htmx: bool = False,
    document: bool = True,
    lang: str = "pt-BR",
    stylesheets: Sequence[str] | None = None,
    head: str | None = None,
    confirm: bool | None = None,
) -> HTMLResponse

Render a widget tree and return it as a FastAPI HTMLResponse.

Parameters:

Name Type Description Default
widget Widget

The component / widget tree to render. A :class:tempest_fastapi_sdk.ui.pages.Page (or any tempest_core widget) is accepted; Component subtrees are expanded via their render() hook by the renderer.

required
title str | None

The document <title>. When omitted and widget is a :class:~tempest_fastapi_sdk.ui.pages.Page, it is :meth:Page.document_title — the page's title plus its title_suffix. Required for any other widget when document is True; ignored when document is False.

None
status_code int

HTTP status code for the response. Defaults to 200.

200
htmx bool

When True and document is True, inject a <script> tag pointing at the SDK's locally-served HTMX asset (/_ssr/htmx.js) rather than a CDN. Has no effect on bare fragments (document=False).

False
document bool

When True (default), render a full HTML5 document via render_document. When False, render a bare HTML fragment via render_to_html — the shape HTMX expects for partial swaps.

True
lang str

The document language attribute. Defaults to "pt-BR". Only used when document is True.

'pt-BR'
stylesheets Sequence[str] | None

URLs added to the document head as <link rel="stylesheet">, in order. Point them at the path served by :func:tempest_fastapi_sdk.ui.css.make_css_router. None (the default) uses the page's :attr:Page.stylesheets when widget is a page, and no stylesheet otherwise. An explicit value replaces the page's list (() links nothing). Ignored for fragments.

None
head str | None

Raw markup appended to the document head, for what no argument covers (meta tags, preloads). It is inserted verbatim — never build it from user input. None (the default) uses the page's :attr:Page.head when widget is a page; an explicit value replaces it. Ignored for fragments.

None
confirm bool | None

Whether to include the locally-served data-confirm listener (/_ssr/confirm.js). None (the default) includes it when the rendered document carries a data-confirm attribute or when htmx is on, since an HTMX swap can bring a guarded form into a page that had none. True forces it, False leaves it out. Ignored for fragments — the listener is delegated on the document, so it already covers a swapped-in fragment.

None

Returns:

Name Type Description
An HTMLResponse

class:~fastapi.responses.HTMLResponse with the rendered

HTMLResponse

HTML and the given status code. The media type is text/html.

Raises:

Type Description
ValueError

When document is True, title is None and widget is not a page.

ImportError

When the optional [ssr] extra is not installed.

build_web_app

build_web_app(
    directory: str | Path,
    *,
    title: str | None = None,
    shell: ShellSource | None = None,
    theme: Theme | None = None,
) -> FastAPI

Build a FastAPI app hosting a tempestweb server build.

Loads the artifact's app.py (its make_state + view contract), wires the tempestweb server engine (WebSocket + SSE) via tempestweb.server.create_app, serves the shared client under /static and the shell at / — the same wiring the artifact's generated server.py performs, done in-process. Mount the result (app.mount("/", web)) or run it directly with uvicorn.

Parameters:

Name Type Description Default
directory str | Path

The build directory (dist/server).

required
title str | None

OpenAPI title; defaults to the directory name.

None
shell ShellSource | None

Replaces the artifact's index.html. The generated shell is what tempestweb build emitted, so anything the application owns — <html lang="pt-BR">, <meta name="description">, Open Graph tags, a favicon link, a CSP nonce — has to enter here. None (default) serves the generated file unchanged.

Whatever you supply must keep the script tag that boots the client; the practical way to write one is to read the generated index.html once and edit the head.

None
theme Theme | None

The palette handed to each session's App. This is the half CSS cannot reach: a themed component resolves its colors at construction and bakes them into an inline style, so rebranding the custom properties alone leaves those at the Material baseline. The build installs this palette around the view call, so every component the view constructs resolves against it with no call-site change; a theme= passed straight to a widget still wins. Needs tempestweb 0.67.0, which is where the floor on tempest-core reaches the version that connects the two — hence the extra's floor. None (default) keeps the Material baseline. Pair this with tempestweb.html.theme_css(theme) in the shell head, which covers what the base stylesheet paints.

None

Returns:

Name Type Description
FastAPI FastAPI

The configured server app (owns /ws + /sse).

Raises:

Type Description
ValueError

When directory is not a server tempestweb build (use :func:make_web_app_router for a static build), or when shell is a string with no markup in it — that is a path written where a document was expected.

Notes

The tempestweb runtime is imported lazily because only the server build mode needs it; a wasm build must not pay for the import.

Example
from pathlib import Path

from fastapi import Request

from tempest_fastapi_sdk.ssr import build_web_app

generated: str = (Path("dist/server") / "index.html").read_text()


def shell(request: Request) -> str:
    "Serve the generated shell with the document language fixed."
    nonce = getattr(request.state, "csp_nonce", "")
    return generated.replace('<html lang="en">', '<html lang="pt-BR">').replace(
        "<script",
        f'<script nonce="{nonce}"',
        1,
    )


web = build_web_app("dist/server", shell=shell)

detect_build_mode

detect_build_mode(directory: str | Path) -> BuildMode

Detect whether directory holds a wasm or server build.

Parameters:

Name Type Description Default
directory str | Path

A tempestweb build output directory.

required

Returns:

Name Type Description
BuildMode BuildMode

"wasm" for a static SPA artifact, "server" for

BuildMode

a live WebSocket/SSE artifact.

Raises:

Type Description
ValueError

When the directory does not look like a tempestweb build (no index.html, or neither a bootstrap.js nor a server.py marker).

make_web_app_router

make_web_app_router(
    directory: str | Path,
    *,
    asset_cache_control: str = "public, max-age=3600",
    security_headers: dict[str, str] | None = None,
    spa_fallback: bool = True,
    shell: ShellSource | None = None,
    immutable: Sequence[str] = (),
    immutable_manifest: str | None = _IMMUTABLE_MANIFEST,
    docs_locale: str | None = None,
) -> APIRouter

Serve a static tempestweb (wasm) build as an APIRouter.

The router serves every file in the build directory and, for any unmatched path, falls back to index.html so client-side routing works on a hard refresh (single-page-app history fallback). The wasm artifact references /sw.js at the site root, so mount this at the application root — app.include_router(router) — and include it after your API routers so specific routes win over the catch-all. Both GET and HEAD are answered; the HEAD routes stay out of the OpenAPI schema.

Caching: index.html and sw.js are always sent no-cache (so a redeploy is seen immediately), and so is a shell override. A path matching immutable or the build's immutable manifest is sent public, max-age=31536000, immutable; every other asset uses asset_cache_control. Every file response carries ETag and Last-Modified and honors If-None-Match / If-Modified-Since with an empty 304 Not Modified, so no-cache means "revalidate" and not "download again". No Content-Security-Policy is imposed — a wasm build runs first-party code and boots Pyodide (which needs wasm-unsafe-eval); pass security_headers to add your own.

The immutable manifest is a JSON file at the build root, {"immutable": ["client-3f2a9c/**", "tempestweb-pkg.3f2a9c.zip"]}: one list of glob patterns relative to the root, where ** crosses directories and * / ? stay within a segment. Other keys are ignored. It is read once, when the router is built. The fixed-name entry points (index.html, sw.js, bootstrap.js, register.js, manifest.webmanifest) and the manifest itself are never immutable, whatever a pattern says — their names cannot change when their bytes do.

Parameters:

Name Type Description Default
directory str | Path

The build directory (dist/wasm).

required
asset_cache_control str

Cache-Control for non-shell assets that are not declared immutable.

'public, max-age=3600'
security_headers dict[str, str] | None

Extra headers stamped on every response. Defaults to {"X-Content-Type-Options": "nosniff"}.

None
spa_fallback bool

When True (default), unmatched paths serve index.html; when False they return 404.

True
shell ShellSource | None

Replaces the artifact's index.html — the only part of the document an application owns, and where <html lang>, meta tags, a favicon link or a CSP nonce have to go. None (default) keeps the generated shell. The override also answers the SPA fallback, so a deep link renders the same document.

None
immutable Sequence[str]

Glob patterns, relative to the build root, naming content-addressed paths to cache for a year with immutable. Only list paths whose name changes whenever their bytes do. Empty (default) declares nothing.

()
immutable_manifest str | None

File name, relative to the build root, of the manifest whose patterns are added to immutable. A missing file declares nothing; None skips the lookup entirely.

_IMMUTABLE_MANIFEST
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

A router serving the static build.

Raises:

Type Description
ValueError

When directory is not a static (wasm) tempestweb build (use :func:build_web_app for a server build), when shell is a string with no markup in it — that is a path written where a document was expected —, when a pattern is empty or absolute, or when the manifest exists but is malformed.

BuildMode module-attribute

BuildMode = Literal['wasm', 'server']

ShellSource module-attribute

ShellSource: TypeAlias = str | Path | Callable[[], str] | Callable[[Request], str]

Where the app shell comes from when the generated one is overridden.

  • str — the HTML document itself.
  • Path — a file read from disk on every request.
  • callable — invoked per request, so the document can carry a value that changes per response (a Content-Security-Policy nonce). It takes either no argument or the :class:~fastapi.Request, whichever it declares.

flash

flash(request: Request, message: str, variant: AlertVariant = 'info') -> None

Queue a message for the next screen this user sees.

Call it before returning the redirect; :class:FlashMiddleware writes the queue into the signed cookie on that response. Text longer than :data:MAX_FLASH_MESSAGE_LENGTH is cut.

Parameters:

Name Type Description Default
request Request

The current request.

required
message str

The notice text. Rendered escaped, but carried readable in the cookie — never put in it what the user may not see.

required
variant AlertVariant

The severity.

'info'

Raises:

Type Description
RuntimeError

When :class:FlashMiddleware is not installed — a message queued without it would be lost silently.