### Basic Client Usage Example
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/00_core.ipynb
Demonstrates creating a FastHTML app, instantiating the test client, and making a GET request to the root route.
```python
app = FastHTML(routes=[Route('/', lambda _: Response('test'))])
cli = Client(app)
cli.get('/').text
```
--------------------------------
### Setup WebSocket Connection and Form
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/tutorials/by_example.ipynb
This example sets up a basic WebSocket connection and a form for sending messages. The 'hx_ext="ws"' and 'ws_connect="/ws"' attributes configure the WebSocket behavior.
```python
def mk_inp(): return Input(id='msg')
@rt('/')
async def get(request):
cts = Div(
Div(id='notifications'),
Form(mk_inp(), id='form', ws_send=True),
hx_ext='ws', ws_connect='/ws')
return Titled('Websocket Test', cts)
```
--------------------------------
### Full client and server WebSocket example
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
This code combines the client-side HTML setup with the server-side WebSocket route definition for a complete, runnable example. Ensure `exts='ws'` is set for the FastHTML object.
```python
from fasthtml.common import *
app = FastHTML(exts='ws')
rt = app.route
@rt('/')
def get():
cts = Div(
Div(id='notifications'),
Form(Input(id='msg'), id='form', ws_send=True),
hx_ext='ws', ws_connect='/ws')
return Titled('Websocket Test', cts)
@app.ws('/ws')
async def ws(msg:str, send):
await send(Div('Hello ' + msg, id='notifications'))
serve()
```
--------------------------------
### Make a GET request to the Jupyter server
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/06_jupyter.ipynb
After starting the server, you can make HTTP requests to it using a client. This example shows how to fetch the content of the root route.
```python
get(f'http://localhost:{port}').text
```
--------------------------------
### Install Quarto for documentation builds
Source: https://github.com/answerdotai/fasthtml/blob/main/CONTRIBUTING.md
Quarto is required for building documentation, including the README.md file. Run this command after installing the development dependencies.
```bash
nbdev_install_quarto
```
--------------------------------
### Install Stripe CLI (Optional)
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/explains/Stripe.ipynb
Installs the Stripe CLI, which is useful for local development and testing webhooks. Refer to Stripe's documentation for system-specific installation instructions.
```python
# uncomment and execute if needed
#!pip install stripe
```
--------------------------------
### Basic Starlette Application Setup
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Defines routes, including plain text responses, dynamic user routes, a WebSocket endpoint, and static file serving. This is a foundational example for setting up a Starlette application with various routing configurations.
```python
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route, Mount, WebSocketRoute
from starlette.staticfiles import StaticFiles
def homepage(request):
return PlainTextResponse('Hello, world!')
def user_me(request):
username = "John Doe"
return PlainTextResponse('Hello, %s!' % username)
def user(request):
username = request.path_params['username']
return PlainTextResponse('Hello, %s!' % username)
async def websocket_endpoint(websocket):
await websocket.accept()
await websocket.send_text('Hello, websocket!')
await websocket.close()
def startup():
print('Ready to go')
routes = [
Route('/', homepage),
Route('/user/me', user_me),
Route('/user/{username}', user),
WebSocketRoute('/ws', websocket_endpoint),
Mount('/static', StaticFiles(directory="static")),
]
app = Starlette(debug=True, routes=routes, on_startup=[startup])
```
--------------------------------
### Install FastHTML
Source: https://github.com/answerdotai/fasthtml/blob/main/README.md
Install the fasthtml Python library using pip.
```sh
pip install python-fasthtml
```
--------------------------------
### Display a Pico.css Card Example
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/04_pico.ipynb
Renders an example of the `Card` component, demonstrating its usage with a header, body, and footer. This helps visualize the card's structure.
```python
show(Card('body', header=P('head'), footer=P('foot')))
```
--------------------------------
### Initialize FastHTML App
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx.txt
Initialize the FastHTML application object and get a shortcut for routing. This is a standard setup for a FastHTML application.
```python
# The FastHTML app object and shortcut to `app.route`
app,rt = fast_app()
```
--------------------------------
### Display a Pico.css Grid Example
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/04_pico.ipynb
Renders an example of the `Grid` component with multiple color input elements. This showcases how to create a responsive grid layout for various elements.
```python
colors = [Input(type="color", value=o) for o in ('#e66465', '#53d2c5', '#f6b73c')]
show(Grid(*colors))
```
--------------------------------
### Display a Pico.css Search Example
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/04_pico.ipynb
Renders an example of the `Search` component, including a search input and a button. This demonstrates a basic search form structure.
```python
show(Search(Input(type="search"), Button("Search")))
```
--------------------------------
### Minimal FastHTML App
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/unpublished/tutorial_for_web_devs.ipynb
A basic FastHTML application setup. It imports necessary components, initializes the app, defines a root route, and starts the server.
```python
from fasthtml.common import * # <1>
app, rt = fast_app() # <2>
@rt("/") # <3>
def get(): #<4>
return Titled("FastHTML", P("Let's do this!")) # <5>
serve() # <6>
```
--------------------------------
### fasthtml.jupyter.JupyUvi.start
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/apilist.txt
Starts the JupyUvi server.
```APIDOC
## fasthtml.jupyter.JupyUvi.start
### Description
Start the JupyUvi server.
### Method Signature
def start(self)
```
--------------------------------
### Application Setup and Router Integration
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/00_core.ipynb
Sets up the FastHTML application and integrates an APIRouter.
```python
app,cli,_ = get_cli(FastHTML())
ar2.to_app(app)
```
--------------------------------
### Install Uvicorn ASGI Server
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Install Uvicorn, a recommended ASGI server, to run Starlette applications.
```shell
pip3 install uvicorn
```
--------------------------------
### fasthtml.jupyter.JupyUviAsync.start
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/apilist.txt
Starts the JupyUviAsync server.
```APIDOC
## fasthtml.jupyter.JupyUviAsync.start
### Description
Start the JupyUviAsync server.
### Method Signature
def start(self)
```
--------------------------------
### Start Async Jupyter uvicorn server
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx.txt
Provides an asynchronous version of `nb_serve` for starting a Jupyter-compatible uvicorn server. Suitable for asynchronous ASGI applications.
```python
def nb_serve_async(app, log_level, port, host, **kwargs):
"""
Async version of `nb_serve`
"""
pass
```
--------------------------------
### Websockets Application Example
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx.txt
A basic example demonstrating how to use websockets with HTMX and FastHTML for real-time communication.
```python
from asyncio import sleep
from fasthtml.common import *
app = FastHTML(exts='ws')
rt = app.route
def mk_inp(): return Input(id='msg')
nid = 'notifications'
@rt('/')
async def get():
cts = Div(
Div(id=nid),
Form(mk_inp(), id='form', ws_send=True),
hx_ext='ws', ws_connect='/ws')
return Titled('Websocket Test', cts)
async def on_connect(send): await send(Div('Hello, you have connected', id=nid))
async def on_disconnect( ): print('Disconnected!')
@app.ws('/ws', conn=on_connect, disconn=on_disconnect)
async def ws(msg:str, send):
await send(Div('Hello ' + msg, id=nid))
await sleep(2)
return Div('Goodbye ' + msg, id=nid), mk_inp()
serve()
```
--------------------------------
### Complete FastHTML Application Setup
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
This is the complete FastHTML application code, including imports, database setup, and all routes for the drawing application.
```python
from fasthtml.common import *
from datetime import datetime
def render(room):
return Li(A(room.name, href=f"/rooms/{room.id}"))
app,rt,rooms,Room = fast_app('data/drawapp.db', render=render, id=int, name=str, created_at=str, canvas_data=str, pk='id')
@rt("/")
def get():
create_room = Form(Input(id="name", name="name", placeholder="New Room Name"),
Button("Create Room"),
hx_post="/rooms", hx_target="#rooms-list", hx_swap="afterbegin")
rooms_list = Ul(*rooms(order_by='id DESC'), id='rooms-list')
return Titled("QuickDraw",
create_room, rooms_list)
@rt("/rooms")
async def post(room:Room):
room.created_at = datetime.now().isoformat()
return rooms.insert(room)
@rt("/rooms/{id}")
def get(id:int):
room = rooms[id]
canvas = Canvas(id="canvas", width="800", height="600")
color_picker = Input(type="color", id="color-picker", value="#000000")
brush_size = Input(type="range", id="brush-size", min="1", max="50", value="10")
save_button = Button("Save Canvas", id="save-canvas", hx_post=f"/rooms/{id}/save", hx_vals="js:{canvas_data: JSON.stringify(canvas.toJSON())}")
js = f""
var canvas = new fabric.Canvas('canvas');
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.color = '#000000';
canvas.freeDrawingBrush.width = 10;
// Load existing canvas data
fetch(`/rooms/{id}/load`)
.then(response => response.json())
.then(data => {{
if (data && Object.keys(data).length > 0) {{
canvas.loadFromJSON(data, canvas.renderAll.bind(canvas));
}}
}});
document.getElementById('color-picker').onchange = function() {{
canvas.freeDrawingBrush.color = this.value;
}};
document.getElementById('brush-size').oninput = function() {{
canvas.freeDrawingBrush.width = parseInt(this.value, 10);
}};
"
return Titled(f"Room: {room.name}",
A(Button("Leave Room"), href="/"),
canvas,
Div(color_picker, brush_size, save_button),
Script(src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"),
Script(js))
@rt("/rooms/{id}/save")
async def post(id:int, canvas_data:str):
rooms.update({'canvas_data': canvas_data}, id)
```
--------------------------------
### FastSQL with PostgreSQL
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/explains/minidataapi.ipynb
Example of initializing a FastSQL database connection using PostgreSQL.
```python
from fastsql import *
db = Database('postgres:...')
```
--------------------------------
### Start Notebook Server
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/06_jupyter.ipynb
Starts the FastHTML server instance running within the Jupyter notebook environment. This makes the defined routes and handlers accessible.
```python
server.start()
```
--------------------------------
### Start a FastHTML server in Jupyter
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/06_jupyter.ipynb
Initializes a FastHTML app and starts a JupyUvi server to serve it. This is useful for testing routes in a live environment within a notebook.
```python
rt = app.route
@app.route
def index(): return 'hi'
port = 8000
server = JupyUvi(app, port=port)
```
--------------------------------
### fasthtml.jupyter.JupyUvi.start_async
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/apilist.txt
Starts the JupyUvi server asynchronously.
```APIDOC
## fasthtml.jupyter.JupyUvi.start_async
### Description
Start the JupyUvi server asynchronously.
### Method Signature
def start_async(self)
```
--------------------------------
### HostRoute Usage Example 2
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/00_core.ipynb
Adds more HostRoute examples to test API-specific and general routes based on host headers. Requires a TestClient for verification.
```python
app.router.routes.append(HostRoute('/hello', lambda _: Response('api hello'), host='api.{parentdom}', methods=['GET'], name='api_hello'))
app.router.routes.append(HostRoute('/hello', lambda _: Response('normal hello'), methods=['GET'], name='hello'))
test_eq(cli.get('/hello', headers={'host': 'api.mysite.com'}).text, 'api hello')
test_eq(cli.get('/hello', headers={'host': 'mysite.com'}).text, 'normal hello')
test_eq(cli.get('/hello', headers={'host': 'other.mysite.com'}).text, 'normal hello')
print('all passed')
```
--------------------------------
### FastLite with SQLite
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/explains/minidataapi.ipynb
Example of initializing a FastLite database connection using SQLite.
```python
from fastlite import *
db = database('test.db')
```
--------------------------------
### Make an asynchronous GET request to the Jupyter server
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/06_jupyter.ipynb
This example shows how to make an asynchronous GET request to the server using `AsyncClient` after the server has been restarted with updated routes.
```python
print((await AsyncClient().get(f'http://localhost:{port}')).text)
```
--------------------------------
### fasthtml.jupyter.nb_serve
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/apilist.txt
Starts a Jupyter compatible uvicorn server with ASGI app.
```APIDOC
## fasthtml.jupyter.nb_serve
### Description
Start a Jupyter compatible uvicorn server with ASGI `app` on `port` with `log_level`; use `daemon=True` for notebook tests so failed runs don't block process shutdown.
### Method Signature
def nb_serve(app, log_level, port, host, daemon, **kwargs)
### Parameters
- `app`: The ASGI application.
- `log_level`: The logging level.
- `port`: The port to run the server on.
- `host`: The host to run the server on.
- `daemon`: Whether to run the server as a daemon.
- `**kwargs`: Additional keyword arguments.
```
--------------------------------
### Main Page Setup
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Sets up the main page with a form for image generation input and a div to display generated images. The form uses hx_post to submit to the root URL and hx_swap to append new results.
```python
from fasthtml.common import *
import os
app = FastHTML() # Assuming FastHTML is imported and initialized
generations = []
@app.get("/")
def get():
inp = Input(id="new-prompt", name="prompt", placeholder="Enter a prompt")
add = Form(Group(inp, Button("Generate")), hx_post="/", target_id='gen-list', hx_swap="afterbegin")
gen_list = Div(id='gen-list')
return Title('Image Generation Demo'), Main(H1('Magic Image Generation'), add, gen_list, cls='container')
```
--------------------------------
### Serve Application
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/explains/Stripe.ipynb
Starts the web server to serve the application. This is typically the last step in initializing and running the application.
```python
#| exports
#| hide
serve()
```
--------------------------------
### GET /ftr
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/00_core.ipynb
An example endpoint demonstrating the usage of `FtResponse` to return custom content with a specific status code and headers.
```APIDOC
## GET /ftr
### Description
An example endpoint demonstrating the usage of `FtResponse` to return custom content with a specific status code and headers.
### Method
GET
### Endpoint
/ftr
### Response
#### Success Response (201)
- **text** (str): The HTML content of the response, including title and H1 tags.
### Response Example
```html
Foo
bar
```
```
--------------------------------
### Setting and Getting Cookies
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/00_core.ipynb
Demonstrates setting a cookie with the current datetime and then retrieving it.
```python
@rt("/setcookie")
def get(req): return cookie('now', datetime.now())
@rt("/getcookie")
def get(now:parsed_date): return f'Cookie was set at time {now.time()}'
print(cli.get('/setcookie').text)
time.sleep(0.01)
cli.get('/getcookie').text
```
--------------------------------
### Create and Retrieve Price Example
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/explains/Stripe.ipynb
Demonstrates how to use the `create_price` function to create a product and retrieve its price. Asserts that exactly one price is returned for this tutorial.
```python
#| exports
app_nm = "[FastHTML Docs] Demo Product"
price_list = create_price(app_nm, amt=1999)
assert len(price_list) == 1, 'For this tutorial, we only have one price bound to our product.'
price = price_list[0]
```
--------------------------------
### Application Startup and Shutdown Event Handling
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/00_core.ipynb
Demonstrates how to register functions to be executed on application startup and shutdown using `on_startup` and `on_shutdown` hooks. The example verifies that the startup event sets a flag and the shutdown event cleans up resources.
```python
app,cli,rt = get_cli(FastHTML(on_startup=[lambda: setattr(app, '_started', True)],
on_shutdown=[lambda: setattr(app, '_stopped', True)]))
@rt
def index(): return str(app._started)
with cli: test_eq(cli.get('/').text, 'True')
test_eq(app._stopped, True)
```
--------------------------------
### Example Usage of Custom Anchor Tag A
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/02_xtend.ipynb
Demonstrates how to use the custom 'A' tag with HTMX attributes for GET requests and target element specification.
```python
A('text', ht_get='/get', target_id='id')
```
--------------------------------
### Path Parameter Encoding Example
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/00_core.ipynb
Shows how `qp` handles path parameters along with query parameters, correctly encoding both.
```python
path = '/foo/{a}/{d}/{ab:int}'
res = qp(path, **vals)
test_eq(res, '/foo/5/bar/42?b=&c=1&c=2&e=')
```
--------------------------------
### Create a FastApp instance for Jupyter
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/tutorials/jupyter_and_fasthtml.ipynb
Initialize the FastHTML application and router using `fast_app`, with `pico=True` for a minimal setup.
```python
app, rt = fast_app(pico=True)
```
--------------------------------
### Query Parameter Handling
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/00_core.ipynb
Demonstrates retrieving multiple values for a single query parameter. This example shows how to use TestClient to simulate a GET request with repeated query parameters.
```python
async def f(req): return Response(str(req.query_params.getlist('x')))
client = TestClient(Starlette(routes=[Route('/', f, methods=['GET'])]))
client.get('/?x=1&x=2').text
```
--------------------------------
### Initialize FastHTML App and TestClient
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/tutorials/by_example.ipynb
Sets up the FastHTML application and a TestClient for making requests to the app.
```python
from fasthtml.common import *
from starlette.testclient import TestClient
app = FastHTML()
cli = TestClient(app)
```
--------------------------------
### fasthtml.jupyter.nb_serve_async
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/apilist.txt
Async version of `nb_serve` to start a Jupyter compatible uvicorn server.
```APIDOC
## fasthtml.jupyter.nb_serve_async
### Description
Async version of `nb_serve`.
### Method Signature
def nb_serve_async(app, log_level, port, host, **kwargs)
### Parameters
- `app`: The ASGI application.
- `log_level`: The logging level.
- `port`: The port to run the server on.
- `host`: The host to run the server on.
- `**kwargs`: Additional keyword arguments.
```
--------------------------------
### Example Usage of Custom Anchor Tag AX
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/02_xtend.ipynb
Shows the usage of the 'AX' tag, passing HTMX GET request and target ID as positional arguments for a text-based anchor.
```python
AX('text', '/get', 'id')
```
--------------------------------
### App-Level and Route-Level Beforeware Example
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/explains/routes.ipynb
Demonstrates how to use app-level beforeware and multiple route-level decorators for sequential execution of middleware logic before a route handler is invoked.
```python
def app_beforeware():
print('App level beforeware')
app = FastHTML(before=Beforeware(app_beforeware))
client = TestClient(app)
def route_beforeware(f):
@wraps(f)
async def decorator(*args, **kwargs):
print('Route level beforeware')
return await f(*args, **kwargs)
return decorator
def second_route_beforeware(f):
@wraps(f)
async def decorator(*args, **kwargs):
print('Second route level beforeware')
return await f(*args, **kwargs)
return decorator
@app.get("/users")
@route_beforeware
@second_route_beforeware
async def users():
return "Users Page"
client.get('/users').text
```
--------------------------------
### HTML Structure for DaisyUI Chat Component
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/tutorials/by_example.ipynb
This HTML snippet shows the basic structure for a chat bubble component using DaisyUI classes. It includes examples for messages from both 'start' and 'end' alignments.
```html
```
--------------------------------
### Setup and Display Toasts
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/tutorials/quickstart_for_web_devs.ipynb
Initialize toast functionality with `setup_toasts` and add various toast types within a session-aware view. Views returning toasts must also return FastHTML components.
```python
setup_toasts(app) # <1>
@rt('/toasting')
def get(session): # <2>
# Normally one toast is enough, this allows us to see
# different toast types in action.
add_toast(session, f"Toast is being cooked", "info")
add_toast(session, f"Toast is ready", "success")
add_toast(session, f"Toast is getting a bit crispy", "warning")
add_toast(session, f"Toast is burning!", "error")
return Titled("I like toast") # <3>
```
--------------------------------
### Database Setup with SQLite
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx.txt
Initialize an SQLite database using the `database()` function. This function creates the database file if it does not exist.
```python
db = database('data/utodos.db')
```
--------------------------------
### Define and Register API Endpoints
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/00_core.ipynb
Defines data models and registers API endpoints using decorators for different HTTP methods and path parameters. Includes examples for POST, PUT, and GET requests with various data structures.
```python
from dataclasses import dataclass, asdict
from fasthtml.common import *
@dataclass
class Bodie: a:int;b:str
@rt("/bodie/{nm}")
def post(nm:str, data:Bodie):
res = asdict(data)
res['nm'] = nm
return res
@rt("/cards/{id}")
def put(card:Card): return asdict(card)
@app.post("/bodied/")
def bodied(data:dict): return data
nt = namedtuple('Bodient', ['a','b'])
@app.post("/bodient/")
def bodient(data:nt): return asdict(data)
class BodieTD(TypedDict): a:int;b:str='foo'
@app.post("/bodietd/")
def bodient(data:BodieTD): return data
class Bodie2:
a:int|None; b:str
def __init__(self, a, b='foo'): store_attr()
@rt("/bodie2/", methods=['get','post'])
def bodie(d:Bodie2): return f"a: {d.a}; b: {d.b}"
```
--------------------------------
### Create a Hello World App in FastHTML
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/tutorials/e2e.ipynb
Create a basic FastHTML application with a root route that returns 'Hello, world!'. Ensure this code is saved in a file named 'main.py'.
```python
from fasthtml.common import *
app = FastHTML()
rt = app.route
@rt('/')
def get():
return 'Hello, world!'
serve()
```
--------------------------------
### setup_ws
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/apilist.txt
Patches the application to set up WebSocket support.
```APIDOC
## setup_ws
### Description
Patches the application to set up WebSocket support.
### Method
`setup_ws(app, f)`
### Parameters
- **app**: The application instance.
- **f**: Not specified.
```
--------------------------------
### FastHTML Application Setup
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Initializes the main FastHTML application class. This is the entry point for creating a web application with FastHTML.
```python
from fasthtml.common import *
from collections import namedtuple
from typing import TypedDict
from datetime import datetime
import json,time
app = FastHTML()
```
--------------------------------
### Basic OAuth Setup and Usage
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/explains/oauth.ipynb
Demonstrates setting up a custom OAuth class and integrating it into a FastHTML app. This includes handling login, logout, and custom authentication logic based on user info.
```python
from fasthtml.oauth import OAuth
from fasthtml.common import FastHTML, RedirectResponse
class Auth(OAuth):
def get_auth(self, info, ident, session, state):
email = info.email or ''
if info.email_verified and email.split('@')[-1]=='answer.ai':
return RedirectResponse('/', status_code=303)
app = FastHTML()
oauth = Auth(app, client)
@app.get('/')
def home(auth): return P('Logged in!'), A('Log out', href='/logout')
@app.get('/login')
def login(req): return Div(P("Not logged in"), A('Log in', href=oauth.login_link(req)))
```
--------------------------------
### Sample Chatbot using FastHTML's setup_ws
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
A sample chatbot implementation using FastHTML's `setup_ws` function for managing websocket connections and message handling. It maintains a list of messages and updates the UI.
```python
from fasthtml.common import *
app = FastHTML(exts='ws')
rt = app.route
msgs = []
@rt('/')
def home():
return Div(hx_ext='ws', ws_connect='/ws')(
Div(Ul(*[Li(m) for m in msgs], id='msg-list')),
Form(Input(id='msg'), id='form', ws_send=True)
)
async def ws(msg:str):
msgs.append(msg)
await send(Ul(*[Li(m) for m in msgs], id='msg-list'))
send = setup_ws(app, ws)
```
--------------------------------
### Install development dependencies for README.md updates
Source: https://github.com/answerdotai/fasthtml/blob/main/CONTRIBUTING.md
Before updating the README.md file by editing nbs/index.ipynb, install the necessary development dependencies. This command installs the project in editable mode with development extras.
```bash
pip install -e '.[dev]'
```
--------------------------------
### Create posts directory and dummy articles
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/unpublished/tutorial_for_web_devs.ipynb
Creates a 'posts' directory and populates it with 10 dummy markdown files for testing.
```python
# Create some dummy posts
posts = Path("posts")
posts.mkdir(exist_ok=True)
for i in range(10): (posts/f"article_{i}.md").write_text(f"This is article {i}")
```
--------------------------------
### Install Starlette
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Install Starlette using pip. Python 3.8+ is required.
```shell
pip3 install starlette
```
--------------------------------
### HTMX GET Attribute for Auto-Fetching
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/00_core.ipynb
Illustrates using the `hx_get` attribute within an HTML response to automatically trigger a GET request to a specified endpoint. The response from this GET request will be used to update the element.
```python
@app.get
def autoget2(): return Html(Div('Text.', hx_get=show_host))
print(cli.get('/autoget2').text)
```
--------------------------------
### Accessing Request Method
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx.txt
Gets the HTTP method of the request (e.g., GET, POST) from `request.method`.
```python
# `request.method`: GET, POST, etc.
```
--------------------------------
### Database Setup with SQLite
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Initializes an SQLite database and defines data models for 'User' and 'Todo' using fastcore flexiclasses. The `database()` function creates the DB if it doesn't exist.
```python
db = database('data/utodos.db')
class User:
name:str
pwd:str
class Todo:
id:int
title:str
done:bool
name:str
details:str
priority:int
```
--------------------------------
### Handle Different HTTP Methods (GET and POST)
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/tutorials/quickstart_for_web_devs.ipynb
Implement handlers for different HTTP methods by naming functions accordingly (e.g., `get` for GET, `post` for POST). This allows a single URL to respond to various request types.
```python
from fasthtml.common import *
app, rt = fast_app()
@rt("/")
def get(): # <1>
return Titled("HTTP GET", P("Handle GET"))
@rt("/")
def post(): # <2>
return Titled("HTTP POST", P("Handle POST"))
serve()
```
--------------------------------
### Basic FastHTML App
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/tutorials/by_example.ipynb
A simple FastHTML application that returns a 'Hello, World' message. Install FastHTML with `pip install python-fasthtml`.
```python
from fasthtml.common import FastHTML, serve
app = FastHTML()
@app.get("/")
def home():
return "Hello, World
"
serve()
```
--------------------------------
### Example: Generate JSON-LD for a Course
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/02_xtend.ipynb
Demonstrates how to use LdCourse and LdCourseInstance to create structured data for an online course.
```python
LdCourse(
name="How to Solve It With Code",
description="A 5-week course teaching the SolveIt method...",
provider={"@type": "Organization", "name": "FastDotAI", "sameAs": "https://fast.ai/"},
course_instance=LdCourseInstance(
start_date="2025-11-03",
end_date="2025-12-10",
location={"@type": "VirtualLocation", "url": "https://solve.it.com/"},
instructor={"@type": "Person", "name": "Jeremy Howard", "sameAs": "https://www.fast.ai/about/#jeremy"}
), script=True)
```
```python
Result:
script(('{
"@type": "Course",
"@context": "https://schema.org",
"name": "How to Solve It With Code",
"description": "A 5-week course teaching the SolveIt method...",
"provider": {
"@type": "Organization",
"name": "FastDotAI",
"sameAs": "https://fast.ai/"
},
"hasCourseInstance": {
"@type": "CourseInstance",
"@context": "https://schema.org",
"courseMode": "Online",
"startDate": "2025-11-03",
"endDate": "2025-12-10",
"location": {
"@type": "VirtualLocation",
"url": "https://solve.it.com/"
},
"instructor": {
"@type": "Person",
"name": "Jeremy Howard",
"sameAs": "https://www.fast.ai/about/#jeremy"
}
}
}',),{'type': 'application/ld+json'})
```
--------------------------------
### Install Stripe Python SDK
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/explains/Stripe.ipynb
Installs the Stripe Python SDK using pip. This command should be run in your terminal or development environment.
```sh
pip install stripe
```
--------------------------------
### Basic GET Route
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/00_core.ipynb
A simple GET route that returns a string. The test client is used to retrieve and display the response text.
```python
@rt("/hi")
def get(): return 'Hi there'
r = cli.get('/hi')
r.text
```
--------------------------------
### Shorthand for GET Request Route
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/tutorials/by_example.ipynb
Illustrates the use of the shorthand `@app.get()` decorator for defining a route that specifically handles GET requests.
```python
@app.get("/")
def my_function():
return "Hello World from a GET request"
```
--------------------------------
### Implementing Authentication Beforeware in FastHTML
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Illustrates setting up authentication using Beforeware. This Beforeware checks for an 'auth' key in the session and redirects to '/login' if not found. It also defines paths to skip.
```python
from fasthtml.common import *
def user_auth_before(req, sess):
# `auth` key in the request scope is automatically provided to any handler which requests it and can not be injected
auth = req.scope['auth'] = sess.get('auth', None)
if not auth: return RedirectResponse('/login', status_code=303)
beforeware = Beforeware(
user_auth_before,
skip=[r'/favicon\.ico', r'/static/.*', r'.*\.css', r'.*\.js', '/login', '/'])
app, rt = fast_app(before=beforeware)
```
--------------------------------
### Implementing Toasts with FastHTML
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Demonstrates how to set up and use toasts for user notifications. Requires `setup_toasts()`, the session argument in handlers, and returning FT components.
```python
from fasthtml.common import *
setup_toasts(app)
@rt
def toasting(session):
add_toast(session, f"cooked", "info")
add_toast(session, f"ready", "success")
return Titled("toaster")
```
--------------------------------
### Define a Simple GET Route
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/explains/routes.ipynb
Create a FastHTML application and define a GET route that accepts a string parameter from the URL path.
```python
app = FastHTML()
@app.get('/user/{nm}')
def get_nm(nm:str): return f"Good day to you, {nm}!"
```
--------------------------------
### Initialize SQLite database and create table
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/tutorials/quickstart_for_web_devs.ipynb
Sets up a SQLite database named 'profiles.db' and creates a table for 'Profile' objects, using 'email' as the primary key. This prepares the database for data storage.
```python
#| hide
from pathlib import Path
if Path("profiles.db").exists():
Path("profiles.db").unlink()
from fastlite import database
db = database("profiles.db")
profiles = db.create(Profile, pk="email")
```
--------------------------------
### FastApp Initialization with Markdown and HighlightJS
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/ref/concise_guide.ipynb
Initializes a FastHTML app and sets up routes, including one for rendering markdown content and displaying code snippets with syntax highlighting.
```python
app, rt = fast_app(hdrs=(MarkdownJS(), HighlightJS(langs=['python', 'javascript'])))
@rt
def index():
return Titled("Example",
Div("*markdown* here", cls="marked"),
Pre(Code("def foo(): pass")))
```
--------------------------------
### Test a GET Route with TestClient
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/explains/routes.ipynb
Use Starlette's TestClient to simulate an HTTP GET request to the defined route and retrieve the response.
```python
from starlette.testclient import TestClient
```
```python
client = TestClient(app)
r = client.get('/user/Jeremy')
r
```
--------------------------------
### GitHub App Client Setup and Authentication Flow
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Sets up a GitHubAppClient and defines routes for login, authentication callback, home page, incrementing counts, and logout. It uses Beforeware for authentication checks.
```python
client = GitHubAppClient(os.getenv("AUTH_CLIENT_ID"),
os.getenv("AUTH_CLIENT_SECRET"))
auth_callback_path = "/auth_redirect"
def before(req, session):
# if not logged in, we send them to our login page
# logged in means:
# - 'user_id' in the session object,
# - 'auth' in the request object
auth = req.scope['auth'] = session.get('user_id', None)
if not auth: return RedirectResponse('/login', status_code=303)
counts.xtra(name=auth)
bware = Beforeware(before, skip=['/login', auth_callback_path])
app = FastHTML(before=bware)
# User asks us to Login
@app.get('/login')
def login(request):
redir = redir_url(request,auth_callback_path)
login_link = client.login_link(redir)
# we tell user to login at github
return P(A('Login with GitHub', href=login_link))
# User comes back to us with an auth code from Github
@app.get(auth_callback_path)
def auth_redirect(code:str, request, session):
redir = redir_url(request, auth_callback_path)
user_info = client.retr_info(code, redir)
user_id = user_info[client.id_key] # get their ID
session['user_id'] = user_id # save ID in the session
# create a db entry for the user
if user_id not in counts: counts.insert(name=user_id, count=0)
return RedirectResponse('/', status_code=303)
@app.get('/')
def home(auth):
return Div(
P("Count demo"),
P(f"Count: ", Span(counts[auth].count, id='count')),
Button('Increment', hx_get='/increment', hx_target='#count'),
P(A('Logout', href='/logout'))
)
@app.get('/increment')
def increment(auth):
c = counts[auth]
c.count += 1
return counts.upsert(c).count
@app.get('/logout')
def logout(session):
session.pop('user_id', None)
return RedirectResponse('/login', status_code=303)
serve()
```
--------------------------------
### Define a GET handler for a route
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/ref/handlers.ipynb
Registers a handler function for the '/hi' route using the `rt` decorator. This handler responds to GET requests with 'Hi there'.
```python
@rt("/hi")
def get(): return 'Hi there'
```
--------------------------------
### Mount a sub-application and define a dashboard route
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
This example demonstrates mounting a previously defined FastHTML app under a specific path and creating a dashboard route that links to it.
```python
from books import books_app
app, rt = fast_app(routes=[Mount("/books", books_app, name="books")])
@rt("/")
def get():
return Titled("Dashboard",
P(A(href="/books")("Books")),
Hr(),
P(A(link=uri("books:list"))("Books")),
)
serve()
```
--------------------------------
### Manage Jupyter uvicorn server lifecycle
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx.txt
Manages the lifecycle (start and stop) of a Jupyter-compatible uvicorn server. Allows starting the server synchronously or asynchronously.
```python
class JupyUvi:
"""
Start and stop a Jupyter compatible uvicorn server with ASGI `app` on `port` with `log_level`
"""
def __init__(self, app, log_level, host, port, start, **kwargs):
pass
def start(self):
pass
def start_async(self):
pass
def stop(self):
pass
```
--------------------------------
### Route Priority Example (Correct)
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Demonstrates the correct way to define routes by placing more specific routes before general ones to ensure proper matching.
```python
# Do this: `/users/me` is tested first.
routes = [
Route('/users/me', current_user),
Route('/users/{username}', user),
]
```
--------------------------------
### Configuring Beforeware
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx.txt
Instantiate Beforeware with the authentication function and an optional list of regexes for paths to skip.
```python
bware = Beforeware(before, skip=[r'/favicon\.ico', r'/static/.*', r'.*\.css', '/login', '/send_login'])
```
--------------------------------
### Handling Specific HTTP Methods in Routes
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Defines a route that explicitly accepts only 'GET' and 'POST' HTTP methods. By default, function endpoints only accept 'GET'.
```python
Route('/users/{user_id:int}', user, methods=["GET", "POST"])
```
--------------------------------
### Render Light Media Style Example
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/03_js.ipynb
Demonstrates the usage of the `light_media` function to apply green text color in light mode.
```python
light_media('.body {color: green;}')
```
--------------------------------
### Switching Database Engines (FastLite to FastSQL)
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Demonstrates how to switch between database engines by changing import and configuration lines, adhering to the MiniDataAPI specification.
```python
from fastlite import *
db = database('test.db')
```
```python
from fastsql import *
db = Database('postgres:...')
```
--------------------------------
### AX tag for HTMX GET requests
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx.txt
Creates an anchor tag configured for HTMX GET requests, with positional parameters for text, target, and swap behavior.
```python
@delegates(ft_hx, keep=True) def AX(txt, hx_get, target_id, hx_swap, href, **kwargs)
An A tag with just one text child, allowing hx_get, target_id, and hx_swap to be positional params
```
--------------------------------
### Simulate a GET request and retrieve response text
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/ref/handlers.ipynb
Uses the `Client` instance to simulate a GET request to the '/hi' route and retrieves the response body as text.
```python
cli.get('/hi').text
```
--------------------------------
### Using a Plain Router Instance
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Shows how to use a plain `Router` instance for lightweight ASGI applications that only handle routing, without additional middleware.
```python
app = Router(routes=[
Route('/', homepage),
Mount('/users', routes=[
Route('/', users, methods=['GET', 'POST']),
Route('/{username}', user),
])
])
```
--------------------------------
### Display a Pico.css Group Example
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/04_pico.ipynb
Renders an example of the `Group` component, showing how input and button elements can be grouped together. This is typically used within forms.
```python
show(Group(Input(), Button("Save")))
```
--------------------------------
### fasthtml.jupyter.JupyUvi.__init__
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/apilist.txt
Initializes the JupyUvi server for Jupyter environments.
```APIDOC
## fasthtml.jupyter.JupyUvi.__init__
### Description
Start and stop a Jupyter compatible uvicorn server with ASGI `app` on `port` with `log_level`.
### Method Signature
def __init__(self, app, log_level, host, port, start, **kwargs)
### Parameters
- `app`: The ASGI application.
- `log_level`: The logging level.
- `host`: The host to run the server on.
- `port`: The port to run the server on.
- `start`: Whether to start the server immediately.
- `**kwargs`: Additional keyword arguments.
```
--------------------------------
### Setup Toast Notifications
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/00_core.ipynb
Configures the application to use toast notifications, setting a default duration and adding necessary CSS and JavaScript. This function should be called once during application setup.
```python
def setup_toasts_(app, duration=5000):
app.state.toast_duration = duration
app.hdrs += [Style(toast_css), Script(js)]
app.after.append(toast_after_)
setup_toasts_(app)
```
--------------------------------
### nb_serve
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx.txt
Starts a Jupyter-compatible uvicorn server with the specified ASGI app, log level, port, and host. It accepts additional keyword arguments for further configuration.
```APIDOC
## nb_serve
### Description
Starts a Jupyter-compatible uvicorn server with the specified ASGI app, log level, port, and host. It accepts additional keyword arguments for further configuration.
### Parameters
- **app**: The ASGI application to serve.
- **log_level**: The logging level for the server (e.g., 'info', 'debug').
- **port**: The port number to run the server on.
- **host**: The host address to bind the server to.
- **kwargs**: Additional keyword arguments for server configuration.
```
--------------------------------
### Make an asynchronous GET request with AsyncClient
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/06_jupyter.ipynb
This snippet demonstrates making an asynchronous GET request to the running server using `AsyncClient` within an `async with` block, and then printing the response text.
```python
async with AsyncClient() as client:
r = await client.get(f'http://localhost:{port}')
print(r.text)
```
--------------------------------
### Example: Basic Route Generation
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/00_core.ipynb
Demonstrates generating a URL with query parameters using the `to()` method on a route object. Handles basic type conversions for query parameters.
```python
app = FastHTML()
@app.get
def foo(a:str, b:list[int]): ...
foo.to(a='bar', b=[1,2])
```
--------------------------------
### Get Authenticated User Info
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/08_oauth.ipynb
Retrieves information about the currently authenticated user using the access token. It makes a GET request to the user info URL with an `Authorization: Bearer ` header.
```python
#| export
@patch
def get_info(self:_AppClient, token=None):
"""Get the info for authenticated user"""
if not token: token = self.token["access_token"]
headers = {'Authorization': f'Bearer {token}'}
return httpx.get(self.info_url, headers=headers).json()
```
--------------------------------
### Start Jupyter uvicorn server
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx.txt
Starts a Jupyter-compatible uvicorn server with the specified ASGI app, log level, port, and host. Useful for running web applications within a Jupyter environment.
```python
def nb_serve(app, log_level, port, host, **kwargs):
"""
Start a Jupyter compatible uvicorn server with ASGI `app` on `port` with `log_level`
"""
pass
```
--------------------------------
### Show Documentation for PathFT.Q
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/05_svg.ipynb
Displays the documentation for the 'Q' (Quadratic Bézier curve) method of the PathFT class.
```python
show_doc(PathFT.Q)
```
--------------------------------
### Start Stripe Local Test Tunnel
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/explains/Stripe.ipynb
Starts a secure tunnel using the Stripe CLI to forward webhook notifications from Stripe's servers to your local application. This is essential for testing webhooks during development.
```bash
stripe listen --forward-to http://localhost:5001/webhook
```
--------------------------------
### Initialize FastHTML Client
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/ref/response_types.ipynb
Create an instance of the Client for testing route handlers. This client provides methods like .get() and .post() to simulate HTTP requests.
```python
cli = Client(app)
```
--------------------------------
### Define a basic GET route
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx-full.txt
Defines a simple GET route that accepts a string parameter from the URL path and returns a formatted string. Ensure parameter types are included for FastHTML to correctly pass arguments.
```python
from fasthtml.common import *
app = FastHTML()
@app.get('/user/{nm}')
def get_nm(nm:str): return f"Good day to you, {nm}!"
```
--------------------------------
### Setup WebSocket Connection and Message Sending
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/tutorials/quickstart_for_web_devs.ipynb
Renders the main page with a form that sends messages via WebSocket and establishes a connection to the '/ws' endpoint.
```python
@rt('/')
async def get(request):
cts = Div(
Div(id='notifications'),
Form(mk_inp(), id='form', ws_send=True), # <3>
hx_ext='ws', ws_connect='/ws') # <4>
return Titled('Websocket Test', cts)
```
--------------------------------
### Test Client GET Request for Profile
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx.txt
Uses Starlette's TestClient to send a GET request to a specific profile path. It includes an HX-Request header to simulate an HTMX request and prints the response text.
```python
path = "/profile?email=john@example.com"
client = TestClient(app)
htmx_req = {'HX-Request':'1'}
print(client.get(path, headers=htmx_req).text)
```
--------------------------------
### FastHTML Application Setup
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/llms-ctx.txt
Initialize the FastHTML application, a subclass of Starlette. Configure Beforeware, exception handlers, and HTTP headers, including CSS and JavaScript links.
```python
app = FastHTML(before=bware,
exception_handlers={404: _not_found},
hdrs=(picolink,
SortableJS('.sortable'),
Script(markdown_js, type='module'))
)
```
--------------------------------
### Example: OAuth Callback Route Handler
Source: https://github.com/answerdotai/fasthtml/blob/main/nbs/api/08_oauth.ipynb
An example of an asynchronous route handler (`@rt(redir_path)`) that processes the OAuth callback. It extracts the authorization `code` from the request, retrieves user info, and displays a success message.
```python
@rt(redir_path)
def get(request, code:str):
redir = redir_url(request, redir_path)
info = cli.retr_info(code, redir)
return P(f'Login successful for {info["name"]}!')
```