Ir para o conteúdo

tempest_fastapi_sdk.ui.forms

Formulários gerados de schemas Pydantic e lidos de volta para eles.

« Web, UI e utilitários


form_for

form_for(
    schema: type[BaseModel],
    *,
    action: str,
    method: str = "post",
    values: Mapping[str, Any] | None = None,
    errors: Mapping[str, Sequence[str]] | None = None,
    include: Sequence[str] = (),
    exclude: Sequence[str] = (),
    submit_label: str = "Enviar",
    submit: bool = True,
    form_errors: Sequence[str] = (),
    attrs: Mapping[str, str] | None = None,
    classes: FormClasses | None = None,
    id_prefix: str = "f",
    describe: bool = True,
    confirm: str | None = None,
) -> Widget

Generate and render a form for a Pydantic schema in one call.

Sugar over :func:~tempest_fastapi_sdk.ui.forms.form_spec_for followed by :func:render_form. Reach for the two-step version when you want to patch the generated specification before rendering.

Parameters:

Name Type Description Default
schema type[BaseModel]

The schema describing the form.

required
action str

The form action URL.

required
method str

"post" (default) or "get".

'post'
values Mapping[str, Any] | None

Current values, overriding the schema defaults.

None
errors Mapping[str, Sequence[str]] | None

Per-field validation messages.

None
include Sequence[str]

Render only these fields, in order.

()
exclude Sequence[str]

Field names to drop.

()
submit_label str

Text of the submit button.

'Enviar'
submit bool

Whether to render the submit button.

True
form_errors Sequence[str]

Form-level messages.

()
attrs Mapping[str, str] | None

Extra attributes on the <form> element (hx-post, enctype, …).

None
classes FormClasses | None

CSS class overrides.

None
id_prefix str

Prefix of the generated control ids.

'f'
describe bool

Whether a field description becomes the hint under its control when the ui block sets no help_text. The description is also the schema's OpenAPI documentation; pass False when it is written for developers rather than for the reader of the form.

True
confirm str | None

Question asked before the form submits, emitted as data-confirm on the <form> (see :func:tempest_fastapi_sdk.ssr.confirm). :func:~tempest_fastapi_sdk.ssr.html_response then includes the locally-served listener. The text is read from the attribute, never interpolated into script, so it may quote a user-supplied name. Without JavaScript the form still submits, just without the question. An explicit data-confirm in attrs wins.

None

Returns:

Name Type Description
Widget Widget

The rendered <form> tree.

Raises:

Type Description
ImportError

When the optional [ssr] extra is missing.

UnsupportedFieldError

When a field is a nested model or a bytes payload and was not excluded.

ValueError

When confirm is blank.

Example
from pydantic import BaseModel, EmailStr

from tempest_fastapi_sdk.ui.forms import form_for


class SignupSchema(BaseModel):
    email: EmailStr
    password: str


widget = form_for(SignupSchema, action="/signup")

render_form

render_form(spec: FormSpec) -> Widget

Render a whole form from its specification.

Messages of hidden fields join the form-level errors, prefixed with the field label, because the field itself shows nothing. A form holding a file field gets enctype="multipart/form-data" unless :attr:FormSpec.attrs sets an enctype of its own.

Parameters:

Name Type Description Default
spec FormSpec

The form description.

required

Returns:

Name Type Description
Widget Widget

The <form> element, holding the form-level errors,

Widget

every field, and the submit button when

Widget

attr:FormSpec.submit is on.

Raises:

Type Description
ImportError

When the optional [ssr] extra is missing.

render_field

render_field(spec: FormSpec, field: FieldSpec) -> Widget

Render one field: label, control, hint and messages.

A hidden field is the exception: it renders as the bare <input type="hidden">, with no wrapper, label or hint. Its messages have nowhere to show, so :func:render_form lists them with the form-level errors instead.

Parameters:

Name Type Description Default
spec FormSpec

The owning form, read for class names and the id prefix.

required
field FieldSpec

The field to render.

required

Returns:

Name Type Description
Widget Widget

The field wrapper, or the hidden input itself.

Raises:

Type Description
ImportError

When the optional [ssr] extra is missing.

fields_for

fields_for(
    schema: type[BaseModel],
    *,
    values: Mapping[str, Any] | None = None,
    errors: Mapping[str, Sequence[str]] | None = None,
    include: Sequence[str] = (),
    exclude: Sequence[str] = (),
    describe: bool = True,
) -> list[FieldSpec]

Derive the field specifications of a Pydantic schema.

Parameters:

Name Type Description Default
schema type[BaseModel]

The schema describing the form.

required
values Mapping[str, Any] | None

Current values, overriding the schema defaults. Accepts raw submitted strings (as returned by :class:~tempest_fastapi_sdk.ui.forms.FormResult) or Python objects (as returned by model.model_dump()).

None
errors Mapping[str, Sequence[str]] | None

Validation messages per field name, rendered under the matching control.

None
include Sequence[str]

When non-empty, render only these fields, in the given order.

()
exclude Sequence[str]

Field names to drop.

()
describe bool

Whether a field description becomes the hint under its control when the ui block sets no help_text. The description is also the OpenAPI documentation of the schema; turn this off when it is written for developers rather than for the reader of the form.

True

Returns:

Type Description
list[FieldSpec]

list[FieldSpec]: One spec per rendered field, in schema

list[FieldSpec]

declaration order (or include order when given).

Raises:

Type Description
UnsupportedFieldError

When a field is a nested model or a bytes payload and was not excluded.

KeyError

When include names a field the schema lacks.

Example
from pydantic import BaseModel, EmailStr

from tempest_fastapi_sdk.ui.forms import fields_for


class SignupSchema(BaseModel):
    email: EmailStr
    age: int


specs = fields_for(SignupSchema)
assert [spec.input_type for spec in specs] == ["email", "number"]

form_spec_for

form_spec_for(
    schema: type[BaseModel],
    *,
    action: str,
    method: str = "post",
    values: Mapping[str, Any] | None = None,
    errors: Mapping[str, Sequence[str]] | None = None,
    include: Sequence[str] = (),
    exclude: Sequence[str] = (),
    submit_label: str = "Enviar",
    submit: bool = True,
    form_errors: Sequence[str] = (),
    attrs: Mapping[str, str] | None = None,
    classes: FormClasses | None = None,
    id_prefix: str = "f",
    describe: bool = True,
) -> FormSpec

Build the full :class:FormSpec of a schema.

Parameters:

Name Type Description Default
schema type[BaseModel]

The schema describing the form.

required
action str

The form action URL.

required
method str

"post" (default) or "get".

'post'
values Mapping[str, Any] | None

Current values.

None
errors Mapping[str, Sequence[str]] | None

Per-field messages.

None
include Sequence[str]

Render only these fields, in order.

()
exclude Sequence[str]

Field names to drop.

()
submit_label str

Text of the submit button.

'Enviar'
submit bool

Whether to render the submit button.

True
form_errors Sequence[str]

Form-level messages.

()
attrs Mapping[str, str] | None

Extra attributes on the <form> element (hx-post, enctype, …).

None
classes FormClasses | None

CSS class overrides.

None
id_prefix str

Prefix of the generated control ids. Give each form on the same page its own prefix.

'f'
describe bool

Whether field descriptions fill in the hint of fields without a help_text (see :func:fields_for).

True

Returns:

Name Type Description
FormSpec FormSpec

The form description, ready to render or to patch.

Raises:

Type Description
ValueError

When method is neither "post" nor "get".

UnsupportedFieldError

Bases: ValueError

Raised when a schema field has no meaningful HTML control.

Nested models and bytes payloads are the two cases: a nested model needs a form of its own, and a file upload is declared as FastAPI's UploadFile rather than a value coerced from a string.

parse_form async

parse_form(
    schema: type[T],
    request: FormRequestLike,
    *,
    include: Sequence[str] = (),
    exclude: Sequence[str] = (),
    extra: Mapping[str, Any] | None = None,
    error_message: Callable[[Mapping[str, Any]], str] | None = None,
) -> FormResult[T]

Read, coerce and validate a submitted form against a schema.

Only the schema's own fields are read from the body; anything else the browser sent (CSRF tokens, HTMX bookkeeping) is ignored, so a stray input cannot smuggle a value into the model.

A key the body does not carry at all is left out of the payload rather than sent as None, so the schema's own default applies and a required field reports Field required against itself. Booleans are the exception: an unchecked checkbox submits nothing, so an absent boolean key means False.

A file field (UploadFile, list[UploadFile], or a field whose ui block forces {"control": "file"}) receives the uploaded UploadFile objects themselves. An empty file control counts as an absent key, and a file never goes back into :attr:FormResult.values — a browser cannot pre-fill a file input, so the re-rendered control comes back empty.

Parameters:

Name Type Description Default
schema type[T]

The schema to validate against — the same one the form was generated from.

required
request FormRequestLike

The incoming fastapi.Request (or any object exposing an awaitable form()).

required
include Sequence[str]

When non-empty, read only these fields from the body.

()
exclude Sequence[str]

Field names never read from the body. Use it for values the server owns (an owner id, a status) and pass them through extra.

()
extra Mapping[str, Any] | None

Server-side values merged in after the body, overriding anything submitted under the same name.

None
error_message Callable[[Mapping[str, Any]], str] | None

Maps a raw Pydantic error dict to the message shown to the reader. Defaults to Pydantic's own msg — pass a callable to translate or reword.

None

Returns:

Type Description
FormResult[T]

FormResult[T]: The validated model, or the messages and raw

FormResult[T]

values needed to re-render the form.

Example
from fastapi import Request
from pydantic import BaseModel

from tempest_fastapi_sdk.ui.forms import parse_form


class SignupSchema(BaseModel):
    email: str


async def handle(request: Request) -> str:
    result = await parse_form(SignupSchema, request)
    return result.value.email if result.ok else "invalid"

FormRequestLike

Bases: Protocol

Any request exposing an awaitable form() returning a mapping.

Matches fastapi.Request and starlette.requests.Request as well as lightweight test doubles.

form

form() -> Awaitable[Mapping[str, object]]

Return the parsed form body.

FormResult dataclass

FormResult(
    value: T | None = None,
    errors: dict[str, list[str]] = dict(),
    form_errors: list[str] = list(),
    values: dict[str, Any] = dict(),
)

Bases: Generic[T]

The outcome of parsing a submitted form.

Attributes:

Name Type Description
value T | None

The validated model, or None when validation failed.

errors dict[str, list[str]]

Validation messages per field name, ready to hand back to :func:~tempest_fastapi_sdk.ui.forms.form_for.

form_errors list[str]

Messages that belong to no single field (model-level validators).

values dict[str, Any]

The raw submitted values, so a re-rendered form keeps what the reader typed.

ok property

ok: bool

Whether the submission validated.

Returns:

Name Type Description
bool bool

True when a model was produced and no message was

bool

collected.

unwrap

unwrap() -> T

Return the validated model, or fail loudly.

Returns:

Name Type Description
T T

The validated model.

Raises:

Type Description
ValueError

When the submission did not validate. Check :attr:ok first and re-render the form instead of calling this on an invalid result.

form_dependency

form_dependency(
    schema: type[T],
    *,
    include: Sequence[str] = (),
    exclude: Sequence[str] = (),
    extra: Mapping[str, Any] | None = None,
    error_message: Callable[[Mapping[str, Any]], str] | None = None,
) -> Callable[[Request], Awaitable[FormResult[T]]]

Build a FastAPI dependency that parses a form into a schema.

The dependency is :func:parse_form bound to schema and the given options, taking the Request itself so the route does not have to. It is a framework hook, not a wrapper: FastAPI injects the Request into the returned callable and hands its result to the route.

Parameters:

Name Type Description Default
schema type[T]

The schema to validate against.

required
include Sequence[str]

Read only these fields from the body.

()
exclude Sequence[str]

Field names never read from the body.

()
extra Mapping[str, Any] | None

Fixed server-side values merged in after the body. A value that depends on the request (the current user) is not known when the dependency is built: exclude the field, parse, and set it in the route — or call :func:parse_form directly.

None
error_message Callable[[Mapping[str, Any]], str] | None

Maps a raw Pydantic error dict to the message shown to the reader.

None

Returns:

Type Description
Callable[[Request], Awaitable[FormResult[T]]]

Callable[[Request], Awaitable[FormResult[T]]]: The dependency,

Callable[[Request], Awaitable[FormResult[T]]]

ready for Depends(...).

Example
from typing import Annotated

from fastapi import Depends, FastAPI
from pydantic import BaseModel

from tempest_fastapi_sdk.ui.forms import FormResult, form_dependency

app: FastAPI = FastAPI()


class SignupSchema(BaseModel):
    email: str


SignupForm = Annotated[
    FormResult[SignupSchema],
    Depends(form_dependency(SignupSchema)),
]


@app.post("/signup")
async def signup(result: SignupForm) -> dict[str, bool]:
    return {"ok": result.ok}

FormSpec dataclass

FormSpec(
    action: str,
    fields: Sequence[FieldSpec],
    method: Literal["post", "get"] = "post",
    submit_label: str = "Enviar",
    errors: Sequence[str] = (),
    submit: bool = True,
    attrs: Mapping[str, str] = dict(),
    classes: FormClasses = FormClasses(),
    id_prefix: str = "f",
)

A whole form: where it posts, what it holds, how it is labelled.

Attributes:

Name Type Description
action str

The action URL.

fields Sequence[FieldSpec]

The fields, in render order.

method Literal['post', 'get']

The HTTP method.

submit_label str

Text of the submit button.

errors Sequence[str]

Form-level messages, rendered above the fields.

submit bool

Whether to render the submit button. Turn it off to place your own actions around the generated fields.

attrs Mapping[str, str]

Extra attributes on the <form> element — this is where hx-post / hx-target go.

classes FormClasses

The CSS class names to apply.

id_prefix str

Prefix of the generated control ids ({id_prefix}-{field name}), which also anchor the <label for=…> and aria-describedby wiring. Give each form on a page its own prefix so the ids stay unique.

multipart property

multipart: bool

Whether the form must be submitted as multipart/form-data.

Returns:

Name Type Description
bool bool

True when at least one field is a file control,

bool

which is what makes

bool

func:~tempest_fastapi_sdk.ui.forms.render_form set the

bool

enctype on its own.

field_named

field_named(name: str) -> FieldSpec

Return one field by name.

Parameters:

Name Type Description Default
name str

The field name to look up.

required

Returns:

Name Type Description
FieldSpec FieldSpec

The matching field.

Raises:

Type Description
KeyError

When no field carries that name.

FieldSpec dataclass

FieldSpec(
    name: str,
    label: str,
    control: Control = "input",
    input_type: str = "text",
    value: str = "",
    selected_values: Sequence[str] = (),
    options: Sequence[SelectOption] = (),
    required: bool = False,
    multiple: bool = False,
    placeholder: str = "",
    help_text: str = "",
    errors: Sequence[str] = (),
    autocomplete: str = "",
    rows: int = 4,
    accept: str = "",
    constraints: Mapping[str, str] = dict(),
    attrs: Mapping[str, str] = dict(),
)

Everything needed to render one form field.

Attributes:

Name Type Description
name str

The submitted field name, matching the schema field.

label str

The <label> text.

control Control

Which HTML control to render.

input_type str

The type attribute when control is "input" (text, email, number, date, password, …).

value str

The current single value, pre-filled into the control.

selected_values Sequence[str]

Current values for a multiple select. Ignored by the other controls.

options Sequence[SelectOption]

Options of a select.

required bool

Whether the control renders required.

multiple bool

Whether a select or a file control accepts many values.

placeholder str

Placeholder text for text-like controls.

help_text str

Hint rendered under the control and wired to it through aria-describedby.

errors Sequence[str]

Validation messages for this field. A non-empty list also marks the control aria-invalid.

autocomplete str

The autocomplete attribute, when known.

rows int

Row count for a textarea.

accept str

The accept attribute of a file control ("image/*", ".pdf,.csv"). Ignored by the other controls.

constraints Mapping[str, str]

Native validation attributes derived from the schema — minlength, maxlength, min, max, step, pattern.

attrs Mapping[str, str]

Extra attributes merged into the control, last, so they win.

has_errors property

has_errors: bool

Whether the field carries at least one validation message.

Returns:

Name Type Description
bool bool

True when :attr:errors is non-empty.

with_value

with_value(value: str) -> FieldSpec

Return a copy pre-filled with a different value.

Parameters:

Name Type Description Default
value str

The new single value.

required

Returns:

Name Type Description
FieldSpec FieldSpec

A copy with value replaced and any select

FieldSpec

options re-marked to match.

SelectOption dataclass

SelectOption(value: str, label: str, selected: bool = False)

One <option> of a <select> control.

Attributes:

Name Type Description
value str

The submitted value.

label str

The text shown to the reader.

selected bool

Whether the option renders as selected.

FormClasses dataclass

FormClasses(
    form: str = "tui-form",
    errors: str = "tui-form__errors",
    field: str = "tui-field",
    field_invalid: str = "tui-field--invalid",
    label: str = "tui-field__label",
    control: str = "tui-field__control",
    help_text: str = "tui-field__help",
    error: str = "tui-field__error",
    actions: str = "tui-form__actions",
    submit: str = "tui-btn",
    required_mark: str = "tui-field__required",
)

CSS class names used by the rendered form.

The defaults match the classes defined by :data:tempest_fastapi_sdk.ui.forms.FORM_STYLESHEET, so including that sheet styles a generated form with no further work. Override them to plug the form into a design system of your own.

Attributes:

Name Type Description
form str

Class of the <form> element.

errors str

Class of the form-level error list.

field str

Class of each field wrapper.

field_invalid str

Extra class added to a wrapper holding an invalid field.

label str

Class of each <label>.

control str

Class of each input / select / textarea.

help_text str

Class of the hint under a control.

error str

Class of a field-level error message.

actions str

Class of the wrapper holding the submit button.

submit str

Class of the submit button.

required_mark str

Class of the marker appended to a required field's label.

form_stylesheet

form_stylesheet(
    *, classes: FormClasses | None = None, theme: ThemeTokens | None = None
) -> StyleSheet

Build the stylesheet that styles a generated form.

Parameters:

Name Type Description Default
classes FormClasses | None

The class names to target. Defaults to the same names :func:~tempest_fastapi_sdk.ui.forms.form_for applies.

None
theme ThemeTokens | None

The tokens whose custom properties the rules reference. Only the prefix matters here — pass the same theme your application sheet emits, or leave it at the default --t- prefix.

None

Returns:

Name Type Description
StyleSheet StyleSheet

The form rules, with no reset and no token block of

StyleSheet

their own, ready to :meth:~StyleSheet.merge into the

StyleSheet

application sheet.