### Basic Application Setup with User Table
Source: https://context7.com/pydantic/fastui/llms.txt
This section provides a complete FastAPI application example demonstrating table rendering and navigation. It includes API endpoints for fetching user data and individual user profiles.
```APIDOC
## GET /api/
### Description
Fetches components to render the main UI, typically a user table.
### Method
GET
### Endpoint
/api/
### Query Parameters
None
### Request Body
None
### Response
#### Success Response (200)
- **FastUI** (object) - The UI components to be rendered.
#### Response Example
```json
[
{
"type": "Page",
"components": [
{
"type": "Heading",
"text": "Users",
"level": 2
},
{
"type": "Table",
"data": [
{"id": 1, "name": "John", "dob": "1990-01-01"},
{"id": 2, "name": "Jack", "dob": "1991-01-01"},
{"id": 3, "name": "Jill", "dob": "1992-01-01"},
{"id": 4, "name": "Jane", "dob": "1993-01-01"}
],
"columns": [
{"field": "name", "on_click": {"type": "GoToEvent", "url": "/user/{id}/"}},
{"field": "dob", "mode": "date"}
]
}
]
}
]
```
## GET /api/user/{user_id}/
### Description
Fetches components to render a specific user's profile details.
### Method
GET
### Endpoint
/api/user/{user_id}/
#### Path Parameters
- **user_id** (int) - Required - The ID of the user to retrieve.
### Query Parameters
None
### Request Body
None
### Response
#### Success Response (200)
- **FastUI** (object) - The UI components for the user profile.
#### Error Response (404)
- **HTTPException** - Detail message indicating user not found.
#### Response Example
```json
[
{
"type": "Page",
"components": [
{
"type": "Heading",
"text": "John",
"level": 2
},
{
"type": "Link",
"components": [
{"type": "Text", "text": "Back"}
],
"on_click": {"type": "BackEvent"}
},
{
"type": "Details",
"data": {"id": 1, "name": "John", "dob": "1990-01-01"}
}
]
}
]
```
## GET /{path:path}
### Description
Serves the prebuilt React application for all routes. This is the main entry point for the frontend.
### Method
GET
### Endpoint
/{path:path}
### Query Parameters
None
### Request Body
None
### Response
#### Success Response (200)
- **HTMLResponse** - The prebuilt HTML of the React application.
#### Response Example
```html
FastUI Demo
```
```
--------------------------------
### Serving the Prebuilt Frontend with Custom Configuration
Source: https://context7.com/pydantic/fastui/llms.txt
Examples demonstrating how to configure the prebuilt FastUI frontend, including setting the API root URL, path handling modes, and stripping prefixes.
```APIDOC
## Prebuilt HTML Configuration
### Description
Functions to generate the prebuilt HTML for the FastUI frontend with various configuration options.
### Method
N/A (These are Python function calls, not HTTP endpoints)
### Endpoint
N/A
### Parameters
`prebuilt_html` function accepts the following arguments:
- **title** (str) - Required - The title of the HTML page.
- **api_root_url** (str) - Optional - The root URL for API requests. Defaults to `/api`.
- **api_path_mode** (str) - Optional - The mode for API path handling. Can be `'append'` (default) or `'query'`.
- **api_path_strip** (str) - Optional - A prefix to strip from paths before making API requests.
### Request Example
```python
from fastui import prebuilt_html
# Basic usage
html_basic = prebuilt_html(title='My App')
# Custom API root URL
html_custom_api = prebuilt_html(
title='My App',
api_root_url='/backend/api'
)
# Use query parameter mode
html_query_mode = prebuilt_html(
title='My App',
api_path_mode='query'
)
# Strip prefix from paths
html_strip_prefix = prebuilt_html(
title='My App',
api_path_strip='/app'
)
```
### Response
#### Success Response
- **str** - The generated HTML content for the FastUI application.
#### Response Example
```html
My App
```
```
--------------------------------
### Run FastUI Demo Backend (Bash)
Source: https://github.com/pydantic/fastui/blob/main/demo/README.md
Commands to set up a virtual environment, install dependencies, and run the FastUI demo backend server. Requires Python 3.11 and assumes execution from the FastUI repository root.
```bash
# create a virtual env
python3.11 -m venv env311
# activate the env
. env311/bin/activate
# install deps
make install
# run the demo server
make dev
```
--------------------------------
### Run FastUI Demo Frontend (npm)
Source: https://github.com/pydantic/fastui/blob/main/demo/README.md
Commands to install dependencies and run the React frontend development server for the FastUI demo. This frontend connects to a backend running on localhost:3000.
```bash
npm install
npm run dev
```
--------------------------------
### FastUI: React Frontend Initialization (TypeScript)
Source: https://context7.com/pydantic/fastui/llms.txt
Provides the TypeScript setup for initializing a React application using FastUI. It configures essential props like API root URL and development mode. Dependencies include '@pydantic/fastui' and 'react-dom/client'.
```typescript
import { FastUI, FastUIProps } from '@pydantic/fastui'
import { createRoot } from 'react-dom/client'
const props: FastUIProps = {
APIRootUrl: '/api',
APIPathMode: 'append', // or 'query'
APIPathStrip: '',
devMode: process.env.NODE_ENV === 'development'
}
const root = createRoot(document.getElementById('root')!)
root.render()
```
--------------------------------
### GET /api/
Source: https://github.com/pydantic/fastui/blob/main/README.md
Fetches a list of users to be displayed in a table on the main page.
```APIDOC
## GET /api/
### Description
This endpoint serves the data for the main user table. It returns a list of components, including a heading and a table displaying user information.
### Method
GET
### Endpoint
/api/
### Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **FastUI** (object) - The FastUI response model containing page components.
- **components** (array) - An array of components to render.
- **c.Page** (object) - Represents a page container.
- **components** (array) - Components within the page.
- **c.Heading** (object) - A heading component.
- **text** (string) - The text for the heading.
- **level** (integer) - The heading level (e.g., 2 for h2).
- **c.Table** (object) - A table component.
- **data** (array) - The data to display in the table (list of users).
- **columns** (array) - Definitions for table columns.
- **DisplayLookup** (object) - Defines a table column.
- **field** (string) - The field from the data to display.
- **on_click** (object) - Event handler for clicks (e.g., GoToEvent).
- **url** (string) - The URL to navigate to.
- **mode** (string) - Display mode (e.g., DisplayMode.date).
#### Response Example
```json
[
{
"type": "Page",
"components": [
{
"type": "Heading",
"text": "Users",
"level": 2
},
{
"type": "Table",
"data": [
{"id": 1, "name": "John", "dob": "1990-01-01"},
{"id": 2, "name": "Jack", "dob": "1991-01-01"},
{"id": 3, "name": "Jill", "dob": "1992-01-01"},
{"id": 4, "name": "Jane", "dob": "1993-01-01"}
],
"columns": [
{
"type": "DisplayLookup",
"field": "name",
"on_click": {
"type": "GoToEvent",
"url": "/user/{id}/"
}
},
{
"type": "DisplayLookup",
"field": "dob",
"mode": "date"
}
]
}
]
}
]
```
```
--------------------------------
### Configure Prebuilt Frontend Serving with FastUI (Python)
Source: https://context7.com/pydantic/fastui/llms.txt
Examples of how to configure the prebuilt FastUI frontend, including setting the API root URL, choosing path handling mode (query parameter vs. path appending), and stripping prefixes from API paths. This uses the `prebuilt_html` function from the FastUI library.
```python
from fastui import prebuilt_html
# Basic usage - defaults to /api root
html = prebuilt_html(title='My App')
# Custom API root URL
html = prebuilt_html(
title='My App',
api_root_url='/backend/api'
)
# Use query parameter mode instead of appending path
html = prebuilt_html(
title='My App',
api_path_mode='query' # Use ?path=/user/1 instead of /api/user/1
)
# Strip prefix from paths before API request
html = prebuilt_html(
title='My App',
api_path_strip='/app' # /app/users becomes /api/users
)
```
--------------------------------
### Serve HTML Landing Page with FastAPI
Source: https://github.com/pydantic/fastui/blob/main/docs/index.md
Implements a catch-all FastAPI GET endpoint '/' that serves a basic HTML page using `prebuilt_html`. This endpoint is designed to load the frontend application, typically a Single Page Application (SPA).
```python
@app.get('/{path:path}')
async def html_landing() -> HTMLResponse:
"""Simple HTML page which serves the React app, comes last as it matches all paths."""
return HTMLResponse(prebuilt_html(title='FastUI Demo'))
```
--------------------------------
### GET /api/
Source: https://github.com/pydantic/fastui/blob/main/docs/index.md
Fetches a table of users. This endpoint is used by the frontend when visiting the root path to render the user data.
```APIDOC
## GET /api/
### Description
Fetches a table of users. This endpoint is used by the frontend when visiting the root path to render the user data.
### Method
GET
### Endpoint
/api/
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **data** (list[AnyComponent]) - A list of FastUI components, typically including a heading and a user table.
#### Response Example
```json
{
"data": [
{
"type": "Page",
"components": [
{
"type": "Heading",
"text": "Users",
"level": 2
},
{
"type": "Table",
"data": [
{"id": 1, "name": "John", "dob": "1990-01-01"},
{"id": 2, "name": "Jack", "dob": "1991-01-01"},
{"id": 3, "name": "Jill", "dob": "1992-01-01"},
{"id": 4, "name": "Jane", "dob": "1993-01-01"}
],
"columns": [
{
"field": "name",
"on_click": {"type": "GoToEvent", "url": "/user/{id}/"}
},
{
"field": "dob",
"mode": "date"
}
]
}
]
}
]
}
```
```
--------------------------------
### FastUI: Toast Notifications (Python)
Source: https://context7.com/pydantic/fastui/llms.txt
Illustrates how to display temporary notification messages (toasts) with different styles and positions using FastUI. Includes examples for success and error toasts, and how to include them in a page. Dependencies include PageEvent and AnyComponent.
```python
# Success toast
success_toast = c.Toast(
title='Success',
body=[c.Text(text='Operation completed successfully!')],
open_trigger=PageEvent(name='show-success'),
position='top-end'
)
# Error toast
error_toast = c.Toast(
title='Error',
body=[c.Text(text='Something went wrong.')],
open_trigger=PageEvent(name='show-error'),
position='top-end',
class_name='bg-danger'
)
# Page with toasts
page = c.Page(components=[
c.Button(
text='Save',
on_click=PageEvent(name='show-success')
),
success_toast,
error_toast
])
```
--------------------------------
### FastUI: Modal Dialogs with Event Triggers (Python)
Source: https://context7.com/pydantic/fastui/llms.txt
Demonstrates creating interactive modal dialogs with custom content and action buttons using FastUI components. It includes examples of a modal with a form and a button to open the modal. Dependencies include PageEvent and GoToEvent.
```python
# Modal with form
modal = c.Modal(
title='Confirm Action',
body=[
c.Paragraph(text='Are you sure you want to proceed?'),
c.ModelForm(
model=ConfirmForm, # Assuming ConfirmForm is defined elsewhere
submit_url='/api/confirm',
display_mode='inline'
)
],
footer=[
c.Button(text='Cancel', on_click=GoToEvent(url='#')), # Assuming GoToEvent is imported
c.Button(
text='Confirm',
on_click=PageEvent(name='submit-form'),
named_style='primary'
)
],
open_trigger=PageEvent(name='open-modal'),
open_context={'modal_open': True}
)
# Button that opens modal
button = c.Button(
text='Open Modal',
on_click=PageEvent(name='open-modal', context={'modal_open': True})
)
```
--------------------------------
### Form Handling with Validation
Source: https://context7.com/pydantic/fastui/llms.txt
This section demonstrates how to auto-generate forms from Pydantic models, enabling both client and server-side validation. It includes examples for a login form with email and password fields.
```APIDOC
## GET /login
### Description
Provides the login page with a form for user authentication.
### Method
GET
### Endpoint
/login
### Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **components** (list[AnyComponent]) - A list of FastUI components to render the page.
#### Response Example
```json
{
"components": [
{
"type": "Page",
"components": [
{
"type": "Heading",
"text": "Login",
"level": 2
},
{
"type": "ModelForm",
"model": "LoginForm",
"submit_url": "/api/auth/login",
"display_mode": "page"
}
]
}
]
}
```
## POST /login
### Description
Handles the submission of the login form, validates the provided credentials, and redirects the user upon successful login.
### Method
POST
### Endpoint
/login
### Parameters
#### Request Body
- **form** (LoginForm) - The submitted login form data, automatically validated by FastUI.
### Request Example
```json
{
"email": "user@example.com",
"password": "your_password"
}
```
### Response
#### Success Response (200)
- **components** (list[AnyComponent]) - A list containing a single event to redirect the user to the dashboard.
#### Response Example
```json
[
{
"type": "FireEvent",
"event": {
"type": "GoToEvent",
"url": "/dashboard"
}
}
]
```
```
--------------------------------
### FastAPI Endpoint for Users Table
Source: https://github.com/pydantic/fastui/blob/main/docs/index.md
Creates a FastAPI GET endpoint '/api/' that returns a FastUI Page component containing a heading and a table of users. The table displays user names as links and dates of birth in date format.
```python
@app.get("/api/", response_model=FastUI, response_model_exclude_none=True)
def users_table() -> list[AnyComponent]:
"""
Show a table of four users, `/api` is the endpoint the frontend will connect to
when a user visits `/` to fetch components to render.
"""
return [
c.Page( # Page provides a basic container for components
components=[
c.Heading(text='Users', level=2), # renders `Users
`
c.Table(
data=users,
# define two columns for the table
columns=[
# the first is the users, name rendered as a link to their profile
DisplayLookup(field='name', on_click=GoToEvent(url='/user/{id}/')),
# the second is the date of birth, rendered as a date
DisplayLookup(field='dob', mode=DisplayMode.date),
],
),
]
),
]
```
--------------------------------
### Data Formatting with Display Modes in Python
Source: https://context7.com/pydantic/fastui/llms.txt
This snippet showcases various built-in display modes provided by FastUI for formatting common data types within a `Details` component. It illustrates how to apply specific modes like currency, datetime, date, duration, markdown, and title case to different fields. A `Transaction` Pydantic model is used as an example.
```python
from datetime import date, datetime
from fastui.components.display import DisplayMode, DisplayLookup
class Transaction(BaseModel):
amount: float
created_at: datetime
date: date
duration_seconds: int
description: str
status: str
# Details view with different display modes
details = c.Details(
data=transaction,
fields=[
DisplayLookup(field='amount', mode=DisplayMode.currency),
DisplayLookup(field='created_at', mode=DisplayMode.datetime),
DisplayLookup(field='date', mode=DisplayMode.date),
DisplayLookup(field='duration_seconds', mode=DisplayMode.duration),
DisplayLookup(field='description', mode=DisplayMode.markdown),
DisplayLookup(field='status', mode=DisplayMode.as_title),
]
)
# Available modes:
# - DisplayMode.auto (default)
# - DisplayMode.plain (raw text)
# - DisplayMode.datetime (ISO datetime)
# - DisplayMode.date (date only)
# - DisplayMode.duration (seconds to readable time)
# - DisplayMode.as_title (Title Case)
# - DisplayMode.markdown (render markdown)
# - DisplayMode.json (JSON display)
# - DisplayMode.inline_code (code formatting)
# - DisplayMode.currency (money formatting)
```
--------------------------------
### FastAPI Endpoint for User Profile
Source: https://github.com/pydantic/fastui/blob/main/docs/index.md
Defines a FastAPI GET endpoint '/api/user/{user_id}/' that retrieves a specific user by ID and returns a FastUI Page component displaying the user's name, a back link, and user details. Includes error handling for non-existent users.
```python
@app.get("/api/user/{user_id}/", response_model=FastUI, response_model_exclude_none=True)
def user_profile(user_id: int) -> list[AnyComponent]:
"""
User profile page, the frontend will fetch this when the user visits `/user/{id}/`.
"""
try:
user = next(u for u in users if u.id == user_id)
except StopIteration:
raise HTTPException(status_code=404, detail="User not found")
return [
c.Page(
components=[
c.Heading(text=user.name, level=2),
c.Link(components=[c.Text(text='Back')], on_click=BackEvent()),
c.Details(data=user),
]
),
]
```
--------------------------------
### GET /api/user/{user_id}/
Source: https://github.com/pydantic/fastui/blob/main/README.md
Fetches a specific user's profile based on the provided user ID.
```APIDOC
## GET /api/user/{user_id}/
### Description
This endpoint retrieves the profile details for a specific user, identified by their `user_id`. It returns components to display the user's name, a back link, and their details.
### Method
GET
### Endpoint
/api/user/{user_id}/
### Parameters
#### Path Parameters
- **user_id** (integer) - Required - The unique identifier for the user.
### Request Example
None
### Response
#### Success Response (200)
- **FastUI** (object) - The FastUI response model containing page components.
- **components** (array) - An array of components to render.
- **c.Page** (object) - Represents a page container.
- **components** (array) - Components within the page.
- **c.Heading** (object) - A heading component displaying the user's name.
- **text** (string) - The user's name.
- **level** (integer) - The heading level (e.g., 2 for h2).
- **c.Link** (object) - A link component.
- **components** (array) - Components within the link (e.g., c.Text).
- **on_click** (object) - Event handler for the link (e.g., BackEvent).
- **c.Details** (object) - A component to display detailed data.
- **data** (object) - The user data object.
#### Error Response (404)
- **HTTPException** (object) - Details about the error if the user is not found.
- **status_code** (integer) - The HTTP status code (404).
- **detail** (string) - Error message (e.g., "User not found").
#### Response Example (Success)
```json
[
{
"type": "Page",
"components": [
{
"type": "Heading",
"text": "John",
"level": 2
},
{
"type": "Link",
"components": [
{"type": "Text", "text": "Back"}
],
"on_click": {"type": "BackEvent"}
},
{
"type": "Details",
"data": {
"id": 1,
"name": "John",
"dob": "1990-01-01"
}
}
]
}
]
```
#### Response Example (Error)
```json
{
"detail": "User not found"
}
```
```
--------------------------------
### GET /api/user/{user_id}/
Source: https://github.com/pydantic/fastui/blob/main/docs/index.md
Fetches the profile details for a specific user based on their ID. This endpoint is used when the frontend navigates to a user's profile page.
```APIDOC
## GET /api/user/{user_id}/
### Description
Fetches the profile details for a specific user based on their ID. This endpoint is used when the frontend navigates to a user's profile page.
### Method
GET
### Endpoint
/api/user/{user_id}/
### Parameters
#### Path Parameters
- **user_id** (int) - Required - The unique identifier for the user whose profile is to be fetched.
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **data** (list[AnyComponent]) - A list of FastUI components, including a heading with the user's name, a back link, and the user's details.
#### Response Example
```json
{
"data": [
{
"type": "Page",
"components": [
{
"type": "Heading",
"text": "John",
"level": 2
},
{
"type": "Link",
"components": [{"type": "Text", "text": "Back"}],
"on_click": {"type": "BackEvent"}
},
{
"type": "Details",
"data": {"id": 1, "name": "John", "dob": "1990-01-01"}
}
]
}
]
}
```
#### Error Response (404)
- **detail** (str) - "User not found" if the provided user_id does not exist.
```
--------------------------------
### Multimedia Components (Python)
Source: https://context7.com/pydantic/fastui/llms.txt
Demonstrates embedding various multimedia components in FastUI using Python, including images with lazy loading, video players with multiple sources, and iframes with sandbox attributes. It also shows how to display code blocks with syntax highlighting and JSON data. Requires importing component classes from `fastui.components`.
```python
from fastui import components as c
# Image with lazy loading
image = c.Image(
src='https://example.com/photo.jpg',
alt='Description',
loading='lazy',
referrer_policy='no-referrer',
class_name='img-fluid'
)
# Video player with multiple sources
video = c.Video(
sources=[
{'src': 'https://example.com/video.mp4', 'type': 'video/mp4'},
{'src': 'https://example.com/video.webm', 'type': 'video/webm'}
],
autoplay=False,
controls=True,
muted=False,
loop=False
)
# Iframe with sandbox
iframe = c.Iframe(
src='https://example.com/embed',
width='100%',
height='400px',
title='Embedded Content',
sandbox='allow-scripts allow-same-origin'
)
# Code block with syntax highlighting
code = c.Code(
language='python',
text='def hello():\n print("Hello, World!")'
)
# JSON display
json_data = c.Json(
value={'key': 'value', 'nested': {'data': [1, 2, 3]}}
)
```
--------------------------------
### Define Users and API Endpoints with FastUI (Python)
Source: https://github.com/pydantic/fastui/blob/main/README.md
Demonstrates defining a list of User objects and creating API endpoints using FastAPI and FastUI. The `/api/` endpoint serves a table of users, while `/api/user/{user_id}/` serves a user's profile. It utilizes FastUI components for rendering the UI elements.
```python
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from fastui import FastUI, GoToEvent, components as c, DisplayLookup, DisplayMode, BackEvent
from fastui.utils import prebuilt_html
from datetime import date
from typing import List, Any
# Define a simple User model
class User:
def __init__(self, id: int, name: str, dob: date):
self.id = id
self.name = name
self.dob = dob
# Initialize FastAPI app
app = FastAPI()
# Define some users
users = [
User(id=1, name='John', dob=date(1990, 1, 1)),
User(id=2, name='Jack', dob=date(1991, 1, 1)),
User(id=3, name='Jill', dob=date(1992, 1, 1)),
User(id=4, name='Jane', dob=date(1993, 1, 1)),
]
@app.get("/api/", response_model=FastUI, response_model_exclude_none=True)
def users_table() -> list[Any]:
"""
Show a table of four users, `/api` is the endpoint the frontend will connect to
when a user visits `/` to fetch components to render.
"""
return [
c.Page(
components=[
c.Heading(text='Users', level=2),
c.Table(
data=users,
columns=[
DisplayLookup(field='name', on_click=GoToEvent(url='/user/{id}/')),
DisplayLookup(field='dob', mode=DisplayMode.date),
],
),
]
),
]
@app.get("/api/user/{user_id}/", response_model=FastUI, response_model_exclude_none=True)
def user_profile(user_id: int) -> list[Any]:
"""
User profile page, the frontend will fetch this when the user visits `/user/{id}/`.
"""
try:
user = next(u for u in users if u.id == user_id)
except StopIteration:
raise HTTPException(status_code=404, detail="User not found")
return [
c.Page(
components=[
c.Heading(text=user.name, level=2),
c.Link(components=[c.Text(text='Back')], on_click=BackEvent()),
c.Details(data=user),
]
),
]
@app.get('/{path:path}')
async def html_landing() -> HTMLResponse:
"""Simple HTML page which serves the React app, comes last as it matches all paths."""
return HTMLResponse(prebuilt_html(title='FastUI Demo'))
```
--------------------------------
### FastAPI App with User Table and Navigation (Python)
Source: https://context7.com/pydantic/fastui/llms.txt
A complete FastAPI application demonstrating table rendering with navigation. It defines Pydantic models for users, sets up API endpoints for fetching user data and profiles, and serves the FastUI prebuilt HTML. Dependencies include FastAPI, Pydantic, and FastUI.
```python
from datetime import date
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from fastui import FastUI, AnyComponent, prebuilt_html, components as c
from fastui.components.display import DisplayMode, DisplayLookup
from fastui.events import GoToEvent, BackEvent
from pydantic import BaseModel, Field
app = FastAPI()
class User(BaseModel):
id: int
name: str
dob: date = Field(title='Date of Birth')
users = [
User(id=1, name='John', dob=date(1990, 1, 1)),
User(id=2, name='Jack', dob=date(1991, 1, 1)),
User(id=3, name='Jill', dob=date(1992, 1, 1)),
User(id=4, name='Jane', dob=date(1993, 1, 1)),
]
@app.get("/api/", response_model=FastUI, response_model_exclude_none=True)
def users_table() -> list[AnyComponent]:
"""Frontend fetches components from /api when user visits /"""
return [
c.Page(
components=[
c.Heading(text='Users', level=2),
c.Table(
data=users,
columns=[
DisplayLookup(field='name', on_click=GoToEvent(url='/user/{id}/')),
DisplayLookup(field='dob', mode=DisplayMode.date),
],
),
]
),
]
@app.get("/api/user/{user_id}/", response_model=FastUI, response_model_exclude_none=True)
def user_profile(user_id: int) -> list[AnyComponent]:
"""User detail page"""
try:
user = next(u for u in users if u.id == user_id)
except StopIteration:
raise HTTPException(status_code=404, detail="User not found")
return [
c.Page(
components=[
c.Heading(text=user.name, level=2),
c.Link(components=[c.Text(text='Back')], on_click=BackEvent()),
c.Details(data=user),
]
),
]
@app.get('/{path:path}')
async def html_landing() -> HTMLResponse:
"""Serve React app for all routes"""
return HTMLResponse(prebuilt_html(title='FastUI Demo'))
```
--------------------------------
### Complete Layout with Navbar and Footer (Python)
Source: https://context7.com/pydantic/fastui/llms.txt
Provides a Python function to create a complete page layout in FastUI, including a navigation bar, main content area, and a footer. The layout supports custom links, titles, and event handling for navigation. It requires importing `AnyComponent` and specific component classes from `fastui.components` and event types.
```python
from typing import Any
from fastui import components as c, FastUI
from fastui.events import GoToEvent, PageEvent, BackEvent
# Assuming AnyComponent is correctly imported or defined
# For example:
# from fastui.types import AnyComponent
def create_layout(body_components: list[Any]) -> list[Any]:
return [
c.Page(components=[
c.Navbar(
title='My Application',
title_event=GoToEvent(url='/'),
start_links=[
c.Link(
components=[c.Text(text='Home')],
on_click=GoToEvent(url='/'),
active='/'
),
c.Link(
components=[c.Text(text='About')],
on_click=GoToEvent(url='/about'),
active='/about'
),
],
end_links=[
c.Link(
components=[c.Text(text='Login')],
on_click=GoToEvent(url='/login'),
active='/login'
),
]
),
c.Div(
components=body_components,
class_name='container my-4'
),
c.Footer(
extra_text='© 2024 My Company',
links=[
c.Link(
components=[c.Text(text='Privacy')],
on_click=GoToEvent(url='/privacy')
),
c.Link(
components=[c.Text(text='Terms')],
on_click=GoToEvent(url='/terms')
),
]
)
])
]
# Assuming 'app' is a FastAPI instance
# @app.get("/api/", response_model=FastUI, response_model_exclude_none=True)
# def home() -> list[AnyComponent]:
# return create_layout([
# c.Heading(text='Welcome', level=1),
# c.Paragraph(text='This is the home page.')
# ])
```
--------------------------------
### Basic Form Handling with Pydantic Validation in FastAPI
Source: https://context7.com/pydantic/fastui/llms.txt
Demonstrates creating a login form using Pydantic models with FastAPI and FastUI. It includes automatic client and server-side validation and redirection after successful submission. Dependencies include fastapi, fastui, and pydantic.
```python
from typing import Annotated
from fastapi import APIRouter
from fastui import AnyComponent, FastUI, components as c
from fastui.events import GoToEvent
from fastui.forms import fastui_form
from pydantic import BaseModel, EmailStr, Field, SecretStr
router = APIRouter()
class LoginForm(BaseModel):
email: EmailStr = Field(
title='Email Address',
description="Try 'x@y' to trigger server side validation"
)
password: SecretStr
@router.get('/login', response_model=FastUI, response_model_exclude_none=True)
def login_page() -> list[AnyComponent]:
return [
c.Page(components=[
c.Heading(text='Login', level=2),
c.ModelForm(
model=LoginForm,
submit_url='/api/auth/login',
display_mode='page'
),
])
]
@router.post('/login', response_model=FastUI, response_model_exclude_none=True)
async def login_submit(form: Annotated[LoginForm, fastui_form(LoginForm)]):
# Form is automatically validated and parsed
print(f"Email: {form.email}, Password: {form.password.get_secret_value()}")
# Redirect after successful login
return [c.FireEvent(event=GoToEvent(url='/dashboard'))]
```
--------------------------------
### Complete Layout with Navbar and Footer
Source: https://context7.com/pydantic/fastui/llms.txt
Defines a full page structure including a navigation bar, main content area, and a footer.
```APIDOC
## Complete Layout with Navbar and Footer
### Description
Creates a complete page layout with a customizable navigation bar and footer. This includes defining links, titles, and content areas.
### Method
GET
### Endpoint
`/api/`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```python
from typing import Any
from fastui import components as c
from fastui.events import GoToEvent
from fastui.api import FastUI
def create_layout(body_components: list[Any]) -> list[Any]:
return [
c.Page(components=[
c.Navbar(
title='My Application',
title_event=GoToEvent(url='/'),
start_links=[
c.Link(
components=[c.Text(text='Home')],
on_click=GoToEvent(url='/'),
active='/'
),
c.Link(
components=[c.Text(text='About')],
on_click=GoToEvent(url='/about'),
active='/about'
),
],
end_links=[
c.Link(
components=[c.Text(text='Login')],
on_click=GoToEvent(url='/login'),
active='/login'
),
]
),
c.Div(
components=body_components,
class_name='container my-4'
),
c.Footer(
extra_text='© 2024 My Company',
links=[
c.Link(
components=[c.Text(text='Privacy')],
on_click=GoToEvent(url='/privacy')
),
c.Link(
components=[c.Text(text='Terms')],
on_click=GoToEvent(url='/terms')
),
]
)
])
]
@app.get("/api/", response_model=FastUI, response_model_exclude_none=True)
def home() -> list[Any]:
return create_layout([
c.Heading(text='Welcome', level=1),
c.Paragraph(text='This is the home page.')
])
```
### Response
#### Success Response (200)
Returns a list of FastUI components representing the page layout.
#### Response Example
```json
[
{
"type": "Page",
"components": [
{
"type": "Navbar",
"title": "My Application",
"title_event": {"type": "GoToEvent", "url": "/"},
"start_links": [
{
"type": "Link",
"components": [{"type": "Text", "text": "Home"}],
"on_click": {"type": "GoToEvent", "url": "/"},
"active": "/"
},
{
"type": "Link",
"components": [{"type": "Text", "text": "About"}],
"on_click": {"type": "GoToEvent", "url": "/about"},
"active": "/about"
}
],
"end_links": [
{
"type": "Link",
"components": [{"type": "Text", "text": "Login"}],
"on_click": {"type": "GoToEvent", "url": "/login"},
"active": "/login"
}
]
},
{
"type": "Div",
"components": [
{"type": "Heading", "text": "Welcome", "level": 1},
{"type": "Paragraph", "text": "This is the home page."}
],
"class_name": "container my-4"
},
{
"type": "Footer",
"extra_text": "© 2024 My Company",
"links": [
{
"type": "Link",
"components": [{"type": "Text", "text": "Privacy"}],
"on_click": {"type": "GoToEvent", "url": "/privacy"}
},
{
"type": "Link",
"components": [{"type": "Text", "text": "Terms"}],
"on_click": {"type": "GoToEvent", "url": "/terms"}
}
]
}
]
}
]
```
```
--------------------------------
### FastUI: Navigation with Tabs and Dynamic Loading (Python)
Source: https://context7.com/pydantic/fastui/llms.txt
Implements tab navigation with lazy-loaded content using PageEvent triggers. It defines routes for the dashboard view and dynamically loads content based on the selected tab. Dependencies include fastui.events and AnyComponent.
```python
from fastui.events import PageEvent
from typing import Any
from fastui import components as c
from fastapi import APIRouter
router = APIRouter()
@router.get('/dashboard/{tab}')
def dashboard_view(tab: str) -> list[Any]:
return [
c.Page(components=[
c.Heading(text='Dashboard', level=2),
c.LinkList(
links=[
c.Link(
components=[c.Text(text='Overview')],
on_click=PageEvent(
name='tab-change',
push_path='/dashboard/overview',
context={'tab': 'overview'}
),
active='/dashboard/overview'
),
c.Link(
components=[c.Text(text='Analytics')],
on_click=PageEvent(
name='tab-change',
push_path='/dashboard/analytics',
context={'tab': 'analytics'}
),
active='/dashboard/analytics'
),
c.Link(
components=[c.Text(text='Settings')],
on_click=PageEvent(
name='tab-change',
push_path='/dashboard/settings',
context={'tab': 'settings'}
),
active='/dashboard/settings'
),
],
mode='tabs',
class_name='+ mb-4'
),
c.ServerLoad(
path='/dashboard/content/{tab}',
load_trigger=PageEvent(name='tab-change'),
components=get_tab_content(tab)
)
])
]
@router.get('/dashboard/content/{tab}')
def get_tab_content(tab: str) -> list[Any]:
if tab == 'overview':
return [c.Paragraph(text='Overview content')]
elif tab == 'analytics':
return [c.Paragraph(text='Analytics content')]
else:
return [c.Paragraph(text='Settings content')]
```
--------------------------------
### FastAPI App with FastUI for User Profiles (Python)
Source: https://github.com/pydantic/fastui/blob/main/README.md
This Python code defines a FastAPI application that utilizes FastUI to display a list of user profiles. It includes Pydantic models for user data and FastUI components for rendering the UI. The application serves an HTML page containing the FastUI interface.
```python
from datetime import date
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from fastui import FastUI, AnyComponent, prebuilt_html, components as c
from fastui.components.display import DisplayMode, DisplayLookup
from fastui.events import GoToEvent, BackEvent
from pydantic import BaseModel, Field
app = FastAPI()
class User(BaseModel):
id: int
name: str
dob: date = Field(title='Date of Birth')
```
--------------------------------
### Server-Sent Events (SSE) with FastUI
Source: https://context7.com/pydantic/fastui/llms.txt
Demonstrates how to use Server-Sent Events for real-time content updates. It includes a content generator that streams updates and a FastUI page using the `ServerLoad` component to consume these events. Uses 'asyncio' for asynchronous operations and 'starlette.responses.StreamingResponse'.
```python
from collections.abc import AsyncIterable
import asyncio
from fastui import FastUI, components as c
from starlette.responses import StreamingResponse
async def content_generator() -> AsyncIterable[str]:
"""Generate streaming updates"""
output = '# Real-time Content\n\n'
for i in range(10):
await asyncio.sleep(0.5)
output += f'- Update {i}\n'
# Serialize FastUI components as SSE data
m = FastUI(root=[c.Markdown(text=output)])
yield f'data: {m.model_dump_json(by_alias=True, exclude_none=True)}\n\n'
@router.get('/sse-stream')
async def sse_stream() -> StreamingResponse:
return StreamingResponse(
content_generator(),
media_type='text/event-stream'
)
# In the page, use ServerLoad to consume the stream
page = c.Page(components=[
c.Heading(text='Live Updates', level=2),
c.ServerLoad(
path='/sse-stream',
sse=True, # Enable SSE mode
components=[c.Text(text='Loading...')] # Placeholder for loaded content
)
])
```
--------------------------------
### Event Chaining and Context Passing
Source: https://context7.com/pydantic/fastui/llms.txt
Demonstrates chaining multiple events and passing context data between them for complex interactions.
```APIDOC
## Event Chaining and Context Passing
### Description
Chain multiple events to execute sequentially and pass context data between them. This allows for sophisticated user interactions and state management.
### Method
N/A (Event Configuration)
### Endpoint
N/A (Event Configuration)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```python
from fastui import components as c
from fastui.events import GoToEvent, PageEvent, BackEvent
# Chain events: navigate, then fire another event
chained_event = GoToEvent(
url='/success',
next_event=PageEvent(name='show-toast', context={'message': 'Saved!'})
)
button = c.Button(text='Save', on_click=chained_event)
# PageEvent with context
page_event = PageEvent(
name='filter-changed',
push_path='/filtered',
context={'filter': 'active', 'sort': 'date'},
clear=False # Don't clear previous context
)
# BackEvent to navigate back in history
back_link = c.Link(
components=[c.Text(text='Go Back')],
on_click=BackEvent()
)
```
### Response
#### Success Response (200)
N/A (Event definitions)
#### Response Example
N/A
```