FastUI Documentation

repository·main·Indexed 27 days ago

https://github.com/pydantic/fastui

A framework for building web interfaces using Python. FastUI allows developers to define UI components in Python (via the fastui PyPI package) that are rendered by a React-based frontend. It includes a variety of Python components in the `fastui.components` module, support for FastAPI integration, and multiple frontend options including a custom React frontend (@pydantic/fastui), a Bootstrap-based implementation (@pydantic/fastui-bootstrap), and pre-built files (@pydantic/fastui-prebuilt).

Tokens
9K
Snippets
8
Records
85
Agent score
94%

What's inside FastUI

  1. Install FastUI components

    main

    FastUI consists of four main parts depending on your needs:

    • Python Backend: Install the fastui PyPI package to access Pydantic models for UI components and utilities.
    • Custom React Frontend: Use the @pydantic/fastui npm package to implement your own components using FastUI's machinery and types.
    • Bootstrap Frontend: Use the @pydantic/fastui-bootstrap npm package for a pre-built implementation of all FastUI components using Bootstrap.
    • Pre-built/No-build Frontend: Use the @pydantic/fastui-prebuilt npm package (or its jsdelivr CDN version) to use a pre-built React app without installing npm packages or building anything. The Python package provides prebuilt_html() to serve this app easily.
  2. Run the FastUI React frontend dev server

    main

    To run the development version of the React frontend, use npm. The frontend will run at http://localhost:3000 and is configured to connect to the backend running at localhost:3000.

    npm install
    npm run dev
  3. Run the FastUI demo backend

    main

    To run the FastUI demo backend, execute the following commands from the repository root. This requires Python 3.11. The backend server will be available at http://localhost:8000.

    # 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
  4. Use FastUI with FastAPI

    main

    To build a web application with FastUI, define your UI components in Python using the fastui library. Your API endpoints should return a list of AnyComponent (or a FastUI model) which the frontend will then render.

    Key patterns:

    • Use c.Page as a basic container for components.
    • Use c.Table with DisplayLookup to define columns and how data fields are rendered (e.g., as links or formatted dates).
    • Use prebuilt_html() to serve the React frontend via a standard HTML response.
    from datetime import date
    from fastapi import FastAPI
    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)),
    ]
    
    @app.get("/api/", response_model=FastUI, response_model_exclude_none=True)
    def users_table() -> list[AnyComponent]:
        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('/{path:path}')
    async def html_landing() -> HTMLResponse:
        return HTMLResponse(prebuilt_html(title='FastUI Demo'))
  5. Customize FormField appearance via JSON Schema

    main

    You can influence how model_json_schema_to_fields renders components by using specific JSON schema properties in your Pydantic models:

    • Boolean Fields: Use mode to switch between 'checkbox' and 'switch'.
    • String/Textarea: Use format: 'textarea' to render a FormFieldTextarea. You can also specify rows and cols.
    • File Uploads: Use format: 'binary' to render a FormFieldFile. You can specify accept (e.g., 'image/*').
    • Enums/Selects: Use enum to create a FormFieldSelect. Use enum_labels (a dict) to map enum values to human-readable labels.
    • Searchable Selects: Use search_url to render a FormFieldSelectSearch.
    • Numbers: Use minimum, maximum, multipleOf, etc., to apply constraints.
  6. Generate TypeScript definitions from Python objects

    main

    Use the fastui generation utility to create TypeScript type definitions from a Python object string. This is useful for keeping your frontend types in sync with your FastUI Python models. The process involves generating a JSON schema from the Python object and then converting that schema into a TypeScript file using json-schema-to-typescript via npx.

    Requirements:

    • npx must be installed on your system.
    • json-schema-to-typescript must be available via npx.

    Note: The generated file includes a warning header stating it was automatically generated and should not be modified by hand.

  7. Navigate using GoToEvent and BackEvent

    main

    FastUI allows you to handle navigation through events returned by components:

    • GoToEvent(url=...): Navigates the user to a specific URL. You can use path parameters like {id} which will be populated by the data in the component.
    • BackEvent(): Triggers a browser-level back navigation.
  8. Configure Table columns with DisplayLookup

    main

    When using c.Table, use DisplayLookup within the columns list to specify how data fields from your Pydantic models are displayed and how they behave.

    Common options:

    • field: The name of the field in the data model.
    • on_click: An event to trigger when the cell is clicked (e.g., GoToEvent(url='/path/{id}/')).
    • mode: The display mode for the data (e.g., DisplayMode.date for date objects).