The fastest way to create HTML apps - a next-generation Python web framework for building fast, scalable web applications with minimal code
—
Core functionality for creating FastHTML applications, defining routes, and handling HTTP requests and responses.
Create FastHTML applications with comprehensive configuration options including database integration, middleware, authentication, and development features.
def fast_app(
db=None,
render=None,
hdrs=None,
ftrs=None,
tbls=None,
before=None,
middleware=None,
live=False,
debug=False,
routes=None,
exception_handlers=None,
on_startup=None,
on_shutdown=None,
lifespan=None,
default_hdrs=True,
pico=True,
surreal=True,
htmx=True,
ws_hdr=False,
secret_key=None,
key_fname='.sesskey',
session_cookie='session',
max_age=365*24*3600,
sess_path='/',
same_site='lax',
sess_https_only=False,
sess_domain=None,
htmlkw=None,
**bodykw
) -> tuple[FastHTML, RouteFuncs]:
"""
Create FastHTML app with sensible defaults and optional database integration.
Args:
db: Database connection or path for SQLite
render: Custom rendering function
hdrs: Additional HTTP headers to include
ftrs: Footer elements to include in pages
tbls: Database tables to create/manage
before: Beforeware middleware functions
middleware: ASGI middleware stack
live: Enable live reload for development
debug: Enable debug mode
routes: Additional routes to include
exception_handlers: Custom exception handlers
on_startup: Startup event handlers
on_shutdown: Shutdown event handlers
lifespan: Application lifespan manager
default_hdrs: Include default headers (HTMX, etc.)
pico: Include PicoCSS framework
surreal: Include Surreal.js for client-side scripting
htmx: Include HTMX for dynamic interactions
ws_hdr: Include WebSocket headers
secret_key: Session encryption key
key_fname: Filename to store session key
session_cookie: Session cookie name
max_age: Session cookie max age in seconds
sess_path: Session cookie path
same_site: Session cookie SameSite attribute
sess_https_only: Session cookie secure flag
sess_domain: Session cookie domain
htmlkw: Additional HTML element kwargs
**bodykw: Additional body element kwargs
Returns:
tuple: (FastHTML app instance, RouteFuncs for routing)
"""
class FastHTML:
"""
Main FastHTML application class (extends Starlette).
Provides ASGI application with FastHTML-specific functionality
including HTML generation, HTMX integration, and enhanced routing.
"""
def __init__(
self,
debug=False,
routes=None,
middleware=None,
exception_handlers=None,
on_startup=None,
on_shutdown=None,
lifespan=None
):
"""Initialize FastHTML application."""Start development server with hot reload and configuration options.
def serve(
appname=None,
app='app',
host='0.0.0.0',
port=None,
reload=True,
reload_includes=None,
reload_excludes=None
):
"""
Start development server with hot reload.
Args:
appname: Name of the application module
app: Application instance or attribute name
host: Host to bind server to
port: Port to bind server to (auto-selected if None)
reload: Enable hot reload for development
reload_includes: Additional file patterns to watch
reload_excludes: File patterns to exclude from watching
"""Define HTTP routes using the RouteFuncs container with method-specific decorators.
class RouteFuncs:
"""
Dynamic route function container for HTTP methods.
Provides decorators for all HTTP methods and path patterns.
Routes are defined using method decorators that specify the path.
"""
def __call__(self, path: str, methods=None):
"""Generic route decorator for any HTTP method."""
def get(self, path: str):
"""GET route decorator."""
def post(self, path: str):
"""POST route decorator."""
def put(self, path: str):
"""PUT route decorator."""
def delete(self, path: str):
"""DELETE route decorator."""
def patch(self, path: str):
"""PATCH route decorator."""
def head(self, path: str):
"""HEAD route decorator."""
def options(self, path: str):
"""OPTIONS route decorator."""
def trace(self, path: str):
"""TRACE route decorator."""
def ws(self, path: str):
"""WebSocket route decorator."""
class APIRouter:
"""
Route organization and modularity system.
Enables grouping related routes with common prefixes, middleware,
and shared configuration for better code organization.
"""
def __init__(self, prefix: str = "", body_wrap=None):
"""
Initialize API router with optional prefix and configuration.
Args:
prefix: URL prefix for all routes in this router
body_wrap: Default body wrapper function for routes
"""
def __call__(self, path: str, methods=None, name=None, include_in_schema=True, body_wrap=None):
"""Add route to router."""
def get(self, path: str, name=None, include_in_schema=True, body_wrap=None):
"""GET route decorator."""
def post(self, path: str, name=None, include_in_schema=True, body_wrap=None):
"""POST route decorator."""
def put(self, path: str, name=None, include_in_schema=True, body_wrap=None):
"""PUT route decorator."""
def delete(self, path: str, name=None, include_in_schema=True, body_wrap=None):
"""DELETE route decorator."""
def patch(self, path: str, name=None, include_in_schema=True, body_wrap=None):
"""PATCH route decorator."""
def head(self, path: str, name=None, include_in_schema=True, body_wrap=None):
"""HEAD route decorator."""
def options(self, path: str, name=None, include_in_schema=True, body_wrap=None):
"""OPTIONS route decorator."""
def trace(self, path: str, name=None, include_in_schema=True, body_wrap=None):
"""TRACE route decorator."""
def ws(self, path: str, conn=None, disconn=None, name=None, middleware=None):
"""WebSocket route decorator."""
def to_app(self, app):
"""Apply all router routes to FastHTML app."""Create and manage HTTP responses with FastHTML-specific enhancements.
class FtResponse:
"""FastHTML response wrapper with HTML generation support."""
def respond(
content=None,
status_code: int = 200,
headers: dict = None,
media_type: str = None
):
"""
Create HTTP response.
Args:
content: Response content (HTML, text, or FastHTML elements)
status_code: HTTP status code
headers: Additional response headers
media_type: Content-Type header value
Returns:
Response object
"""
class JSONResponse:
"""JSON response class with custom rendering."""
def __init__(self, content, status_code: int = 200, headers: dict = None):
"""Create JSON response."""
class Redirect:
"""Redirect response class."""
def __init__(self, url: str, status_code: int = 302):
"""Create redirect response."""Handle HTTP requests with parameter extraction and processing utilities.
def form2dict(form) -> dict:
"""
Convert FormData to dictionary.
Args:
form: FormData object from request
Returns:
dict: Converted form data
"""
def qp(**kwargs) -> str:
"""
Build query parameter string.
Args:
**kwargs: Query parameters as key-value pairs
Returns:
str: URL-encoded query string
"""
def uri(path: str, **kwargs) -> str:
"""
Build URI with query parameters.
Args:
path: Base path
**kwargs: Query parameters
Returns:
str: Complete URI with query string
"""
def decode_uri(uri: str) -> str:
"""Decode URI components."""Pre-processing middleware and request handling utilities.
class Beforeware:
"""
Middleware base for preprocessing.
Allows modification of requests before route handling.
"""
def __init__(self, f, skip=None):
"""Initialize middleware with processing function."""
class MiddlewareBase:
"""Base class for middleware."""
def __init__(self, app):
"""Initialize middleware with application."""Helper functions for application development and request processing.
def get_key(key_fname: str = '.sesskey') -> str:
"""
Get session key from file.
Args:
key_fname: Filename containing the session key
Returns:
str: Session encryption key
"""
def signal_shutdown():
"""Handle graceful application shutdown."""
def unqid() -> str:
"""Generate unique identifier."""
def reg_re_param(name: str, pattern: str):
"""
Register regex route parameter.
Args:
name: Parameter name
pattern: Regular expression pattern
"""
def cookie(
key: str,
value: str = '',
max_age: int = None,
expires: str = None,
path: str = '/',
domain: str = None,
secure: bool = False,
httponly: bool = False,
samesite: str = 'lax'
):
"""
Create HTTP cookie.
Args:
key: Cookie name
value: Cookie value
max_age: Cookie lifetime in seconds
expires: Cookie expiration date
path: Cookie path
domain: Cookie domain
secure: Secure flag (HTTPS only)
httponly: HTTP-only flag (no JavaScript access)
samesite: SameSite attribute ('strict', 'lax', 'none')
Returns:
Cookie object
"""from fasthtml.common import *
# Create app with database and authentication
app, rt = fast_app(
db='myapp.db',
secret_key='your-secret-key',
pico=True,
htmx=True
)
# Define routes
@rt('/')
def homepage():
return Titled("My App",
Div(
H1("Welcome"),
P("This is my FastHTML application"),
A("Click me", hx_get="/dynamic")
)
)
@rt('/dynamic')
def dynamic_content():
return Div("This content loaded dynamically!", style="color: green;")
# Start server
if __name__ == '__main__':
serve()from fasthtml.common import *
app, rt = fast_app()
# Route with path parameters
@rt('/user/{user_id}')
def user_profile(user_id: int):
return Div(
H2(f"User Profile: {user_id}"),
P(f"Displaying information for user {user_id}")
)
# Route with query parameters
@rt('/search')
def search(request):
query = request.query_params.get('q', '')
return Div(
H3("Search Results"),
P(f"Searching for: {query}") if query else P("No search query provided")
)
# POST route for form handling
@rt('/submit', methods=['POST'])
def handle_form(form_data):
data = form2dict(form_data)
return Div(
H3("Form Submitted"),
P(f"Received: {data}")
)from fasthtml.common import *
def auth_middleware(req, call_next):
# Custom authentication logic
if not req.headers.get('authorization'):
return Redirect('/login')
return call_next(req)
app, rt = fast_app(
before=[auth_middleware],
middleware=[],
debug=True
)
@rt('/protected')
def protected_route():
return Div("This is a protected route")Install with Tessl CLI
npx tessl i tessl/pypi-python-fasthtml