API Reference
This section provides automatically generated documentation from the FastStrap source code. It is useful for looking up exact parameter names and types.
Core Utilities
merge_classes
merge_classes(base, user) combines a base class string with user-provided classes, deduplicating while preserving order.
from faststrap import merge_classes
merged = merge_classes("btn btn-primary", "btn-lg custom")
# Result: "btn btn-primary btn-lg custom"
This is the standard way FastStrap components merge default Bootstrap classes with user overrides. Use it when authoring custom components.
convert_attrs
convert_attrs() converts Python-friendly kwargs such as hx_get, data_bs_toggle, aria_label, style={...}, and css_vars={...} into valid HTML attributes.
from faststrap import convert_attrs
attrs = {"cls": "btn btn-primary"}
attrs.update(
convert_attrs(
{
"hx_post": "/save",
"hx_target": "#result",
"data": {"mode": "inline"},
"css_vars": {"brand_color": "#5B6CFF"},
}
)
)
For component authors, routing **kwargs through convert_attrs(kwargs) is the standard way to preserve HTMX support and attribute conversion consistently.
UNSET Sentinel
UNSET is a sentinel value used to distinguish "not provided" from None. Component defaults are stored as UNSET and resolved at render time, allowing you to pass None explicitly to clear a default.
from faststrap import UNSET, set_component_defaults, get_component_defaults
set_component_defaults("Button", {"variant": "primary"})
defaults = get_component_defaults("Button")
# Clear a default by passing None: Button("Click", variant=None)
See Component Defaults for the full API reference on UNSET.
faststrap.core.base.merge_classes(*class_lists)
Merge multiple class strings or lists, removing duplicates.
Source code in src/faststrap/core/base.py
faststrap.utils.attrs.convert_attrs(kwargs)
Convert Python kwargs to HTML attributes (hx_get -> hx-get).
Rules:
- None values are dropped
- boolean False values are dropped (except aria_*, which are preserved)
- boolean True values are kept (FastHTML will serialize appropriately)
- style may be a str or a dict (dict is serialized)
- css_vars may be a dict and will be merged into style
- data={...} expands to data-*
- aria={...} expands to aria-*
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kwargs
|
dict[str, Any]
|
Python-style keyword arguments |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
HTML-style attributes with hyphens |
Source code in src/faststrap/utils/attrs.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
Attributes Helper
faststrap.utils.attrs.convert_attrs(kwargs)
Convert Python kwargs to HTML attributes (hx_get -> hx-get).
Rules:
- None values are dropped
- boolean False values are dropped (except aria_*, which are preserved)
- boolean True values are kept (FastHTML will serialize appropriately)
- style may be a str or a dict (dict is serialized)
- css_vars may be a dict and will be merged into style
- data={...} expands to data-*
- aria={...} expands to aria-*
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kwargs
|
dict[str, Any]
|
Python-style keyword arguments |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
HTML-style attributes with hyphens |
Source code in src/faststrap/utils/attrs.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
Application Setup
faststrap.core.assets.add_bootstrap(app, theme=None, mode='light', use_cdn=None, mount_static=True, static_url='/static', force_static_url=False, include_favicon=True, favicon_url=None, font_family=None, font_weights=None, components=None, include_modern_toast=None, htmx4=None, htmx_compat=False, allow_extensions=None)
Enhance FastHTML app with Bootstrap and FastStrap assets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
Any
|
FastHTML application instance |
required |
theme
|
str | Theme | None
|
Color theme - either a built-in name (e.g., "green-nature", "purple-magic"), a Theme instance created via create_theme(), or a community theme |
None
|
mode
|
ModeType
|
Color mode for light/dark backgrounds: - "light": Light background, dark text (default) - "dark": Dark background, light text - "auto": Follows user's system preference (prefers-color-scheme) |
'light'
|
use_cdn
|
bool | None
|
When True, ALL assets (Bootstrap CSS/JS, Bootstrap Icons, Faststrap CSS files, favicon) are served from CDN. No local StaticFiles are mounted. Required for serverless deployments (Vercel, AWS Lambda, Google Cloud Run). Default: False. |
None
|
mount_static
|
bool
|
Auto-mount static directory |
True
|
static_url
|
str
|
Preferred URL prefix for static files |
'/static'
|
force_static_url
|
bool
|
Force use of this URL even if already mounted |
False
|
include_favicon
|
bool
|
Include default FastStrap favicon |
True
|
favicon_url
|
str | None
|
Custom favicon URL (overrides default) |
None
|
font_family
|
str | None
|
Google Font name (e.g., "Inter", "Roboto", "Poppins") |
None
|
font_weights
|
list[int] | None
|
Font weights to load (default: [400, 500, 700]) |
None
|
components
|
list[Any] | None
|
Optional list of Faststrap component functions used in the app. When provided, Bootstrap JS is only injected if at least one component has requires_js=True in its registry metadata. Components without @register() metadata are treated as requires_js=False. When None (default), JS is always injected. |
None
|
include_modern_toast
|
bool | None
|
Explicitly include the ModernToast runtime script.
When None (default), the script is included only if |
None
|
htmx4
|
bool | None
|
Whether the app runs htmx 4 (FastHTML(htmx4=True)). When None (default), Faststrap auto-detects from the app's headers. This gates the htmx 4 compatibility and allow-list integrations below. |
None
|
htmx_compat
|
bool
|
When running htmx 4, load the official htmx-2-compat extension so downstream code using legacy event names keeps working. |
False
|
allow_extensions
|
list[str] | None
|
When running htmx 4, restrict which HTMX extensions may register by merging an allow-list into the page's htmx-config meta element (htmx 4 security model). |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Modified app instance |
Examples:
Basic setup with light mode
add_bootstrap(app)
Dark mode with a color theme
add_bootstrap(app, theme="purple-magic", mode="dark")
Auto mode (follows system preference)
add_bootstrap(app, theme="green-nature", mode="auto")
Custom theme with dark mode
from faststrap import create_theme my_theme = create_theme(primary="#7BA05B", secondary="#48C774") add_bootstrap(app, theme=my_theme, mode="dark")
Built-in theme with custom font
add_bootstrap(app, theme="green-nature", font_family="Inter")
Custom theme with custom font
my_theme = create_theme(primary="#7BA05B") add_bootstrap(app, theme=my_theme, font_family="Roboto", font_weights=[400, 600, 700])
Font only, no theme
add_bootstrap(app, font_family="Poppins")
CDN mode for production
add_bootstrap(app, theme="blue-ocean", mode="auto", use_cdn=True)
Source code in src/faststrap/core/assets.py
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 | |
faststrap.core.assets.get_assets(use_cdn=None, include_custom=True, static_url=None, theme=None, mode='light', font_family=None, font_weights=None, include_js=True, include_favicon=False, include_modern_toast=False)
Get Bootstrap assets for injection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_cdn
|
bool | None
|
Use CDN (True) or local files (False) |
None
|
include_custom
|
bool
|
Include FastStrap custom styles |
True
|
static_url
|
str | None
|
Custom static URL (if using local assets) |
None
|
theme
|
str | Theme | None
|
Theme name (str) or Theme instance |
None
|
mode
|
ModeType
|
Color mode - "light", "dark", or "auto" |
'light'
|
font_family
|
str | None
|
Google Font name (e.g., "Inter", "Roboto", "Poppins") |
None
|
font_weights
|
list[int] | None
|
Font weights to load (default: [400, 500, 700]) |
None
|
include_js
|
bool
|
Include Bootstrap JavaScript bundle |
True
|
include_favicon
|
bool
|
Include default Faststrap favicon (CDN mode only) |
False
|
include_modern_toast
|
bool
|
Include ModernToast runtime script |
False
|
Returns:
| Type | Description |
|---|---|
tuple[Any, ...]
|
Tuple of FastHTML elements for app.hdrs |
Source code in src/faststrap/core/assets.py
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 | |
faststrap.core.assets.mount_assets(app, directory, url_path='/assets', name=None, priority=True, allow_override=False, base_dir=None)
Mount a static files directory to your FastHTML app.
This is a convenience wrapper around Starlette's Mount and StaticFiles that handles path resolution and mounting order automatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
Any
|
FastHTML application instance |
required |
directory
|
str
|
Path to directory containing static files.
Can be absolute, relative to |
required |
url_path
|
str
|
URL path to mount at (default: "/assets"). Must start with "/". |
'/assets'
|
name
|
str | None
|
Mount name for Starlette routing. If None, auto-generated from url_path. |
None
|
priority
|
bool
|
If True, insert at start of routes to take precedence over catch-all routes (default: True). |
True
|
allow_override
|
bool
|
If True, allow overriding Faststrap's static mount. NOT recommended as it will break Bootstrap CSS/JS loading. (default: False) |
False
|
base_dir
|
str | PathLike[str] | None
|
Optional explicit base directory for resolving relative
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If url_path doesn't start with "/" or conflicts with Faststrap |
FileNotFoundError
|
If directory doesn't exist |
Warning
Do not use the same url_path as Faststrap's static files (usually "/static"). This will cause Bootstrap CSS/JS to fail loading. Use "/assets" or another path.
Examples:
Basic usage:
>>> from fasthtml.common import FastHTML
>>> from faststrap import add_bootstrap, mount_assets
>>>
>>> app = FastHTML()
>>> add_bootstrap(app)
>>> mount_assets(app, "assets") # Mounts assets/ at /assets/
Multiple directories:
>>> mount_assets(app, "images", url_path="/img")
>>> mount_assets(app, "uploads", url_path="/uploads")
Absolute path:
Custom static URL for Faststrap (to use /static for your files):
>>> add_bootstrap(app, static_url="/faststrap-static")
>>> mount_assets(app, "static", url_path="/static") # Now safe!
Source code in src/faststrap/core/assets.py
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 | |
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
faststrap.utils.static_management.cleanup_static_resources()
Clean up extracted static resources.
Source code in src/faststrap/utils/static_management.py
Theme System
Notes:
- add_bootstrap() supports font_family and font_weights for Google Fonts injection.
- set_component_defaults() modifies process-global defaults. Configure it at application startup before rendering components.
- Component calls can pass None to clear a configured default for that instance.
- convert_attrs() is available from faststrap directly for custom components and wrappers.
- BaseComponent / Component are extension points for third-party class-based components; built-ins remain function-based.
- BaseComponent.merge_attrs() applies convert_attrs() so class-based components keep the same attribute conversion behavior as function-based components.
When To Use BaseComponent
Use BaseComponent only when a class-based API is genuinely helpful, for example:
- stateful third-party component libraries
- reusable abstractions with internal helper methods
- advanced wrappers that benefit from inheritance
For normal FastStrap components, prefer plain function-based components such as
Button(...), Card(...), or Row(...). That remains the default style across
the framework.
faststrap.core.base.Component
Bases: Protocol
Protocol for FastStrap components.
Source code in src/faststrap/core/base.py
faststrap.core.base.BaseComponent
Bases: Component, ABC
Base class for stateful components with shared functionality.
Note: Most Faststrap components are implemented as functions for simplicity. This base class is provided for:
- Advanced users who want to create stateful component classes
- Future framework extensions that may need class-based components
- Third-party component libraries built on Faststrap
For most use cases, prefer function-based components as shown in the Faststrap component library (see Button, Card, Navbar, etc.).
Examples:
Creating a custom stateful component:
>>> from faststrap.core.base import BaseComponent
>>> from faststrap import Card, Button
>>>
>>> class StatefulCounter(BaseComponent):
... def __init__(self, initial=0, **kwargs):
... super().__init__(**kwargs)
... self.count = initial
...
... def render(self):
... return Card(
... Button(f"Count: {self.count}"),
... **self.merge_attrs(cls="counter-card")
... )
Source code in src/faststrap/core/base.py
add_class(*classes)
merge_attrs(**defaults)
Merge component attributes with defaults.
The merged attribute set is passed through convert_attrs() so
class-based components preserve the same HTMX, data_*, aria_*,
style={...}, and css_vars={...} behavior as function-based
FastStrap components.
Source code in src/faststrap/core/base.py
faststrap.core.theme.create_theme(primary=None, secondary=None, success=None, danger=None, warning=None, info=None, **extra_vars)
Create a custom theme from color values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
primary
|
str | None
|
Primary color (e.g., "#7BA05B") |
None
|
secondary
|
str | None
|
Secondary color |
None
|
success
|
str | None
|
Success color (defaults to Bootstrap green) |
None
|
danger
|
str | None
|
Danger color (defaults to Bootstrap red) |
None
|
warning
|
str | None
|
Warning color (defaults to Bootstrap yellow) |
None
|
info
|
str | None
|
Info color (defaults to Bootstrap cyan) |
None
|
**extra_vars
|
str
|
Additional CSS variables. Keys like |
{}
|
Returns:
| Type | Description |
|---|---|
Theme
|
Theme instance |
Examples:
>>> theme = create_theme(
... primary="#7BA05B",
... secondary="#48C774",
... )
>>> add_bootstrap(app, theme=theme, mode="dark")
Source code in src/faststrap/core/theme.py
faststrap.core.theme.get_builtin_theme(name)
Get a built-in theme by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Theme name (e.g., "green-nature", "blue-ocean") |
required |
Returns:
| Type | Description |
|---|---|
Theme
|
Theme instance |
Raises:
| Type | Description |
|---|---|
ValueError
|
If theme name is not found |
Source code in src/faststrap/core/theme.py
faststrap.core.theme.list_builtin_themes()
List all available built-in theme names.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of theme names |
faststrap.core.theme.set_component_defaults(component, **defaults)
Set default values for a component globally.
This updates process-global state shared by all requests. Configure defaults during application startup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
component
|
str
|
Component name (e.g., "Button") |
required |
**defaults
|
Any
|
Default values to set |
{}
|
Examples:
>>> set_component_defaults("Button", variant="outline-primary", size="sm")
>>> # Now all Button() calls use these defaults unless overridden
Source code in src/faststrap/core/theme.py
faststrap.core.theme.reset_component_defaults(component=None)
Reset component defaults to original values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
component
|
str | None
|
Component name to reset, or None to reset all |
None
|
Source code in src/faststrap/core/theme.py
Component Discovery
Faststrap exposes a small registry so users and agents can discover existing components before inventing new wrappers.
from faststrap import (
find_components,
get_component,
get_components_by_pattern,
list_component_metadata,
list_components,
)
list_components(category="display")
find_components("card")
get_components_by_pattern("toast")
metadata = list_component_metadata()
Button = get_component("Button")
faststrap.core.registry.list_components(category=None)
List all registered components, optionally filtered by category. Args: category: Filter by category (layout, display, feedback, etc.) Returns: List of component names Examples: >>> list_components(category="feedback") ['Alert', 'Toast', 'Modal', 'Spinner']
Source code in src/faststrap/core/registry.py
faststrap.core.registry.find_components(query, *, category=None)
Find components by name, category, module, or docstring text.
Source code in src/faststrap/core/registry.py
faststrap.core.registry.get_components_by_pattern(pattern, *, category=None)
Return component callables matching a pattern.
This is a convenience API for agents and app builders that need to discover existing components before inventing new UI.
Source code in src/faststrap/core/registry.py
faststrap.core.registry.list_component_metadata(category=None)
List registered component metadata records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category
|
str | None
|
Optional category filter. |
None
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
Metadata dictionaries with a stable |
Source code in src/faststrap/core/registry.py
faststrap.core.registry.get_component(name)
Theme Variant CSS
Use theme_variant_css() when a polished component needs small light/dark CSS differences without repeating selector boilerplate.
from fasthtml.common import Style
from faststrap import theme_variant_css
Style(
theme_variant_css(
".premium-card",
light={"background": "rgba(255, 255, 255, 0.78)"},
dark={"background": "rgba(15, 23, 42, 0.62)"},
)
)
faststrap.core.theme.theme_variant_css(selector, *, light=None, dark=None)
Create light/dark CSS blocks for a selector.
This helper keeps premium component styling aligned with Faststrap's
data-bs-theme mode convention without requiring every app to hand-write
repetitive selectors.
Examples:
>>> theme_variant_css(
... ".metric-card",
... light={"background": "rgba(255,255,255,.85)"},
... dark={"background": "rgba(15,23,42,.72)"},
... )