FastHTML Documentation

repository·main·Indexed 27 days ago

https://github.com/answerdotai/fasthtml

A next-generation Python web framework for building fast, scalable, and interactive web applications. FastHTML maps 1:1 to HTML and HTTP, leveraging HTMX for hypermedia-based interactivity. It features a Starlette-based core, integrated support for SurrealDB, built-in WebSocket endpoints, and automated deployment tools for Railway.

Tokens
24.2K
Snippets
76
Records
170
Agent score
91%

What's inside FastHTML

  1. Create a minimal FastHTML app

    main

    To create a basic FastHTML application, use fast_app() to initialize the app and route handler, define routes using the @rt decorator, and use serve() to start the server. FastHTML uses components like Div and P that map to HTML elements.

    By default, the app will run on http://localhost:5001.

    from fasthtml.common import *
    
    app,rt = fast_app()
    
    @rt('/')
    def get(): return Div(P('Hello World!'), hx_get="/change")
    
    serve()
  2. Provide FastHTML context to AI coding assistants

    main

    Since FastHTML is a newer framework, LLMs (like ChatGPT, Claude, or Copilot) may lack up-to-date knowledge. To improve AI-generated code accuracy, provide the following LLM-friendly context link to your assistant:

    • https://www.fastht.ml/docs/llms-ctx.txt

    For Cursor users: Type @doc, select "Add new doc", and paste the link above.

  3. Understand FT (FastTags) components

    main

    FT components (FastTags) are the display components of FastHTML that turn Python objects into HTML. They are Python callables (functions, classes, methods, etc.) that return a structure representing an HTML tag.

    Key characteristics:

    • They use PascalCase naming (e.g., Div(), Ul(), H1()) to distinguish them from standard Python variables.
    • They can be accessed via the fasthtml.ft namespace if you prefer PEP8-compliant variable naming.
    • They are highly dynamic and can evaluate to various types like str, None, tuple, or objects implementing __ft__, __html__, or __str__.
    from fasthtml.common import *
    
    def example():
        return Div(
                H1("FastHTML APP"),
                P("Let's do this"),
                cls="go"
        )
  4. Implement Toasts with setup_toasts

    main

    Toasts (info, success, warning, error) can be added to the session.

    1. Call setup_toasts(app) during app initialization.
    2. Ensure route handlers include session in their arguments.
    3. Use add_toast(session, message, type) within the handler.
    4. Handlers must return FastTag components.
  5. Handle Form Submissions and Data Validation

    main

    To handle forms with validation:

    1. Define a dataclass representing the form data.
    2. Create a Form component.
    3. Use fill_form(form_component, dataclass_instance) to populate an existing form with data.
    4. In the post route, type-hint the argument with your dataclass to trigger automatic validation.
    from dataclasses import dataclass
    from fasthtml.common import *
    
    @dataclass
    class Profile: 
        email: str
        phone: str
        age: int
    
    # The form component
    profile_form = Form(method="post", action="/profile")( 
        Fieldset(
            Label('Email', Input(name="email")),
            Label('Phone', Input(name="phone")),
            Label('Age', Input(name="age")),
        ),
        Button("Save", type="submit"),
    )
    
    @rt("/profile")
    def post(profile: Profile): 
        # 'profile' is automatically validated against the Profile dataclass
        return RedirectResponse(url=f"/profile/{profile.email}")
  6. Render FT components in Jupyter notebooks with show()

    main

    The show() function allows you to render FastHTML (FT) components directly within a Jupyter notebook cell.

    • show(ft, ...): Renders the component as HTML.
    • iframe=True: Renders the component inside an iframe, which is useful for displaying full pages or isolating styles.
    • height: Sets the height of the iframe if used.
    sentence = P(Strong("FastHTML is ", I("Fast")), id='sentence_id')
    show(sentence)
    
    # Displaying a full page in an iframe
    fullpage = Html(Head(Link(rel="stylesheet", href="...")), Body(H2("Heading")))
    show(fullpage, height=100, iframe=True)
  7. Create an OAuth Client

    main

    To manage OAuth settings and state, use the specific Client classes provided by FastHTML. You will need a client_id and client_secret from your provider. It is recommended to store these in environment variables.

    Supported clients include:

    • GoogleAppClient
    • GitHubAppClient
    • HuggingFaceClient
    • DiscordAppClient
    import os
    from fasthtml.oauth import GoogleAppClient
    client = GoogleAppClient(os.getenv("AUTH_CLIENT_ID"),
                             os.getenv("AUTH_CLIENT_SECRET"))
  8. Deploy to Replit

    main

    To run FastHTML on Replit:

    1. Use a template or fork an existing FastHTML repl.
    2. Ensure .replit is configured with the correct run command: run = ["uvicorn", "main:app", "--reload"].
    3. Install dependencies using poetry add python-fasthtml.
    4. Use the 'Secrets' tab in Replit settings to manage API keys.
    5. Note: You may need to open the webview in a new tab for features like cookies to work correctly.
  9. Send JavaScript values to the server via HTMX

    main

    You can use the hx_vals attribute with the js: prefix to execute JavaScript and send the result as part of an HTMX request. This is useful for sending complex data like JSON strings from a client-side canvas.

    # Example: Sending canvas JSON data to the server
    save_button = Button("Save Canvas", 
                         id="save-canvas", 
                         hx_post=f"/rooms/{id}/save", 
                         hx_vals="js:{canvas_data: JSON.stringify(canvas.toJSON())}")
  10. Create a basic FastHTML application

    main

    A minimal FastHTML app defines routes and returns HTML. You can use the @app.get decorator to handle GET requests and serve() to start the development server.

    from fasthtml.common import FastHTML, serve
    
    app = FastHTML()
    
    @app.get("/")
    def home():
        return "<h1>Hello, World</h1>"
    
    serve()