Skip to content

Utility API

These helpers support static asset inspection, SVG rendering, form-validation mapping, and DataTable URL construction. They are useful when building wrappers or integrating Faststrap with an existing application layer.

DataTable Query Helpers

from faststrap import datatable_page_url, datatable_query_params

params = datatable_query_params(
    sort="created_at",
    direction="desc",
    search="pending",
    page=2,
    per_page=25,
)
url = datatable_page_url("/orders", page=2, per_page=25, sort="created_at", direction="desc")

The helpers preserve repeated filter values and keep URL construction in one place. Use datatable_export_params() when an export endpoint should receive the current sort, search, and filter state without pagination.

Form Error Helpers

from faststrap import extract_field_error, map_formgroup_validation

message = extract_field_error(errors, "email")
state = map_formgroup_validation(errors, "email")

These helpers accept mapping-shaped validation errors and return values suitable for FormGroup, Input, and related form components.

API Reference

faststrap.components.display.data_table.datatable_export_params(*, sort=None, direction='asc', search=None, search_param='q', filters=None, include_pagination=False, page=None, per_page=None)

Build query params for exporting DataTable state.

This helper mirrors the DataTable query contract and is intended to be passed into ExportButton(extra_params=...).

Source code in src/faststrap/components/display/data_table.py
def datatable_export_params(
    *,
    sort: str | None = None,
    direction: SortableDirection = "asc",
    search: str | None = None,
    search_param: str = "q",
    filters: dict[str, Any] | None = None,
    include_pagination: bool = False,
    page: int | None = None,
    per_page: int | None = None,
) -> dict[str, Any]:
    """Build query params for exporting DataTable state.

    This helper mirrors the DataTable query contract and is intended to be passed
    into ExportButton(extra_params=...).
    """
    params: dict[str, Any] = {}

    if filters:
        for key, value in filters.items():
            normalized = _normalize_query_value(value)
            if normalized is None:
                continue
            params[str(key)] = normalized

    if sort:
        params["sort"] = sort
        params["direction"] = direction

    if search is not None:
        params[search_param] = search

    if include_pagination:
        if page is not None:
            params["page"] = page
        if per_page is not None:
            params["per_page"] = per_page

    return params

faststrap.components.display.data_table.datatable_query_params(*, sort=None, direction='asc', search=None, search_param='q', filters=None, page=None, per_page=None)

Build the common DataTable query contract for links and handlers.

Source code in src/faststrap/components/display/data_table.py
def datatable_query_params(
    *,
    sort: str | None = None,
    direction: SortableDirection = "asc",
    search: str | None = None,
    search_param: str = "q",
    filters: dict[str, Any] | None = None,
    page: int | None = None,
    per_page: int | None = None,
) -> dict[str, Any]:
    """Build the common DataTable query contract for links and handlers."""
    return datatable_export_params(
        sort=sort,
        direction=direction,
        search=search,
        search_param=search_param,
        filters=filters,
        include_pagination=page is not None or per_page is not None,
        page=page,
        per_page=per_page,
    )

faststrap.components.display.data_table.datatable_page_url(base_url, *, page, per_page=None, sort=None, direction='asc', search=None, search_param='q', filters=None)

Build a URL for one DataTable page while preserving current state.

Source code in src/faststrap/components/display/data_table.py
def datatable_page_url(
    base_url: str,
    *,
    page: int,
    per_page: int | None = None,
    sort: str | None = None,
    direction: SortableDirection = "asc",
    search: str | None = None,
    search_param: str = "q",
    filters: dict[str, Any] | None = None,
) -> str:
    """Build a URL for one DataTable page while preserving current state."""
    params = datatable_query_params(
        sort=sort,
        direction=direction,
        search=search,
        search_param=search_param,
        filters=filters,
        page=max(1, page),
        per_page=per_page,
    )
    return _build_url(base_url, params)

faststrap.components.forms.errors.extract_field_error(errors, field)

Extract a single displayable error message for a field.

Source code in src/faststrap/components/forms/errors.py
def extract_field_error(errors: Mapping[str, Any] | None, field: str) -> str | None:
    """Extract a single displayable error message for a field."""
    if not errors or field not in errors:
        return None
    value = errors[field]
    if isinstance(value, str):
        return value
    if isinstance(value, (list, tuple)):
        if not value:
            return None
        return str(value[0])
    if isinstance(value, dict):
        if "msg" in value:
            return str(value["msg"])
        if "message" in value:
            return str(value["message"])
    return str(value)

faststrap.components.forms.errors.map_formgroup_validation(errors, field)

Return FormGroup-ready validation flags for a given field.

Source code in src/faststrap/components/forms/errors.py
def map_formgroup_validation(
    errors: Mapping[str, Any] | None,
    field: str,
) -> dict[str, Any]:
    """Return FormGroup-ready validation flags for a given field."""
    error = extract_field_error(errors, field)
    return {
        "error": error,
        "is_invalid": bool(error),
    }

faststrap.utils.static_management.get_faststrap_static_url(app)

Get the URL where FastStrap static files are mounted for this specific app.

Parameters:

Name Type Description Default
app Any

The FastHTML app instance

required

Returns:

Type Description
str | None

The static URL if mounted, None otherwise

Source code in src/faststrap/utils/static_management.py
def get_faststrap_static_url(app: Any) -> str | None:
    """
    Get the URL where FastStrap static files are mounted for this specific app.

    Args:
        app: The FastHTML app instance

    Returns:
        The static URL if mounted, None otherwise
    """
    return getattr(app, "_faststrap_static_url", None)

faststrap.utils.static_management.cleanup_static_resources()

Clean up extracted static resources.

Source code in src/faststrap/utils/static_management.py
def cleanup_static_resources() -> None:
    """Clean up extracted static resources."""
    global _APP_STATIC_STACK, _EXTRACTED_STATIC_PATH, _ATEXIT_REGISTERED
    if _APP_STATIC_STACK:
        try:
            _APP_STATIC_STACK.close()
        finally:
            _APP_STATIC_STACK = None
            _EXTRACTED_STATIC_PATH = None
            _ATEXIT_REGISTERED = False

faststrap.components.display.svg.render_svg(svg, *, sanitize=True, allowed_tags=None, allowed_attributes=None, allowed_protocols=None)

Render SVG markup with optional sanitization.

Source code in src/faststrap/components/display/svg.py
def render_svg(
    svg: str,
    *,
    sanitize: bool = True,
    allowed_tags: list[str] | None = None,
    allowed_attributes: dict[str, list[str]] | None = None,
    allowed_protocols: list[str] | None = None,
) -> str:
    """Render SVG markup with optional sanitization."""
    if not sanitize:
        return svg

    bleach_module = _load_bleach_module()
    return cast(
        str,
        bleach_module.clean(
            svg,
            tags=allowed_tags or DEFAULT_SVG_TAGS,
            attributes=allowed_attributes or DEFAULT_SVG_ATTRIBUTES,
            protocols=allowed_protocols or DEFAULT_SVG_PROTOCOLS,
            strip=True,
        ),
    )