Convert Figma logo to code with AI

pydantic logoFastUI

Build better UIs faster.

8,765
337
8,765
148

Top Related Projects

82,358

FastAPI framework, high performance, easy to learn, fast to code, ready for production

38,313

Streamlit — A faster way to build and share data apps.

22,355

Data Apps & Dashboards for Python. No JavaScript Required.

36,839

Build and share delightful machine learning apps, all in Python. 🌟 Star to support our work!

5,118

Panel: The powerful data exploration & web app framework for Python

12,734

Flet enables developers to easily build realtime web, mobile and desktop apps in Python. No frontend experience required.

Quick Overview

FastUI is a Python web framework built on top of the Pydantic library, which provides a declarative and type-safe way to define and interact with web applications. It aims to simplify the development of modern web applications by leveraging the power of Pydantic's data validation and serialization capabilities.

Pros

  • Declarative Approach: FastUI encourages a declarative style of web development, where the application structure and behavior are defined in a clear and concise manner.
  • Type Safety: By building on Pydantic, FastUI inherits the strong type-checking and validation features, which can help catch errors early in the development process.
  • Rapid Prototyping: The framework's simplicity and focus on developer productivity can enable rapid prototyping and iteration of web applications.
  • Flexibility: FastUI is designed to be flexible and extensible, allowing developers to customize and extend the framework to fit their specific needs.

Cons

  • Relatively New: As a relatively new framework, FastUI may have a smaller community and ecosystem compared to more established web frameworks like Flask or Django.
  • Limited Documentation: The project's documentation, while improving, may still be limited compared to more mature web frameworks, which could make it harder for new developers to get started.
  • Performance Concerns: The use of Pydantic and the overhead of the framework itself may impact the performance of larger, more complex web applications.
  • Limited Ecosystem: The ecosystem of third-party libraries and plugins for FastUI may be more limited than for other popular web frameworks.

Code Examples

Defining a FastUI Application

from fastui import FastUI, Page, Component

app = FastUI()

@app.page("/")
class HomePage(Page):
    title = "Home Page"

    def render(self):
        return "Welcome to my FastUI app!"

if __name__ == "__main__":
    app.run()

This code defines a simple FastUI application with a single page, the HomePage. The @app.page decorator is used to register the page with the application, and the render method is used to define the content of the page.

Creating a Component

from fastui import Component, prop

class HelloComponent(Component):
    name: str = prop()

    def render(self):
        return f"Hello, {self.name}!"

This code defines a HelloComponent that takes a name property and renders a greeting message. The prop function is used to define the property, which will be automatically validated and type-checked by Pydantic.

Using Components in a Page

from fastui import FastUI, Page
from .components import HelloComponent

app = FastUI()

@app.page("/")
class HomePage(Page):
    title = "Home Page"

    def render(self):
        return HelloComponent(name="Alice")

This code demonstrates how the HelloComponent can be used within the HomePage by simply instantiating it and passing the required name property.

Getting Started

To get started with FastUI, you can follow these steps:

  1. Install the FastUI library using pip:
pip install fastui
  1. Create a new Python file (e.g., app.py) and define your FastUI application:
from fastui import FastUI, Page, Component

app = FastUI()

@app.page("/")
class HomePage(Page):
    title = "Home Page"

    def render(self):
        return "Welcome to my FastUI app!"

if __name__ == "__main__":
    app.run()
  1. Run the application:
python app.py

This will start the FastUI development server, and you can access your application at http://localhost:8000.

For more advanced usage and customization, refer to the FastUI documentation.

Competitor Comparisons

82,358

FastAPI framework, high performance, easy to learn, fast to code, ready for production

Pros of FastAPI

  • More mature and widely adopted project with extensive documentation
  • Supports both synchronous and asynchronous programming
  • Integrates well with other Python libraries and frameworks

Cons of FastAPI

  • Steeper learning curve for beginners
  • Requires more boilerplate code for simple applications
  • Less focus on frontend development and UI components

Code Comparison

FastAPI:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

FastUI:

from fastui import FastUI, AnyComponent
from fastui.components.display import Markdown

app = FastUI()

@app.page("/")
def root() -> AnyComponent:
    return Markdown("# Hello World")

Summary

FastAPI is a more established and feature-rich framework for building APIs, while FastUI is a newer project focused on simplifying the creation of full-stack applications with a unified Python codebase. FastAPI offers more flexibility and integration options, but FastUI provides a more streamlined approach for building user interfaces alongside backend logic. The choice between the two depends on the specific requirements of your project and your familiarity with web development concepts.

38,313

Streamlit — A faster way to build and share data apps.

Pros of Streamlit

  • More mature and established project with a larger community and ecosystem
  • Easier to get started with for beginners, requiring less boilerplate code
  • Extensive documentation and tutorials available

Cons of Streamlit

  • Less flexibility in UI customization compared to FastUI
  • Can be slower for complex applications due to its stateless nature
  • Limited support for more advanced web development features

Code Comparison

Streamlit:

import streamlit as st

st.title("Hello World")
name = st.text_input("Enter your name")
st.write(f"Hello, {name}!")

FastUI:

from fastui import FastUI, AnyComponent
from fastui.components import Heading, TextInput, Paragraph

def index() -> list[AnyComponent]:
    return [
        Heading("Hello World"),
        TextInput(name="name", label="Enter your name"),
        Paragraph("Hello, {name}!")
    ]

app = FastUI(routes=[("/", index)])

Summary

Streamlit is more beginner-friendly and has a larger ecosystem, while FastUI offers more flexibility and potentially better performance for complex applications. Streamlit's syntax is more concise, but FastUI provides greater control over the UI structure. The choice between the two depends on the specific requirements of your project and your familiarity with web development concepts.

22,355

Data Apps & Dashboards for Python. No JavaScript Required.

Pros of Dash

  • Mature and well-established framework with extensive documentation
  • Rich set of pre-built components for data visualization
  • Seamless integration with Plotly for interactive charts and graphs

Cons of Dash

  • Steeper learning curve, especially for developers new to React
  • Can be slower for complex applications due to client-side rendering
  • Less flexibility in UI customization compared to more modern frameworks

Code Comparison

FastUI:

from fastui import FastUI, AnyComponent
from fastui.components import Heading, Paragraph

def index() -> AnyComponent:
    return [
        Heading('Hello World'),
        Paragraph('Welcome to FastUI')
    ]

Dash:

import dash
import dash_html_components as html

app = dash.Dash(__name__)
app.layout = html.Div([
    html.H1('Hello World'),
    html.P('Welcome to Dash')
])

Summary

FastUI is a newer, lightweight framework focused on rapid development with Python, while Dash is a more established solution with robust data visualization capabilities. FastUI offers simpler syntax and faster rendering, but Dash provides a wider range of pre-built components and better integration with Plotly for complex data visualizations.

36,839

Build and share delightful machine learning apps, all in Python. 🌟 Star to support our work!

Pros of Gradio

  • More mature and widely adopted project with a larger community
  • Supports a broader range of input/output types, including audio and video
  • Offers more pre-built components and templates for rapid prototyping

Cons of Gradio

  • Can be more resource-intensive, especially for complex interfaces
  • Less flexibility in terms of custom UI design and layout
  • May require more setup for integration with existing web applications

Code Comparison

Gradio example:

import gradio as gr

def greet(name):
    return f"Hello, {name}!"

demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()

FastUI example:

from fastui import FastUI, AnyComponent
from fastui.components.display import Markdown

async def page() -> list[AnyComponent]:
    return [Markdown(text='# Welcome to FastUI')]

app = FastUI(components_=page)

While both frameworks aim to simplify UI creation for Python applications, Gradio focuses on rapid prototyping and demo creation, especially for machine learning models. FastUI, on the other hand, is designed for building more complex, production-ready web applications with a focus on type safety and integration with FastAPI.

5,118

Panel: The powerful data exploration & web app framework for Python

Pros of Panel

  • More mature and established project with a larger community
  • Supports a wider range of data visualization libraries and frameworks
  • Offers more advanced layout and styling options out-of-the-box

Cons of Panel

  • Steeper learning curve due to its extensive feature set
  • Can be more resource-intensive for complex applications
  • Less focused on modern web development practices

Code Comparison

Panel example:

import panel as pn

pn.extension()

slider = pn.widgets.FloatSlider(start=0, end=10, value=5)
text = pn.widgets.StaticText(value='Slider value:')

pn.Row(text, slider).servable()

FastUI example:

from fastui import FastUI, AnyComponent, components as c

@app.get("/")
def index() -> list[AnyComponent]:
    return [
        c.Heading(text="Hello World"),
        c.Slider(min=0, max=10, value=5)
    ]

Both libraries aim to simplify the creation of interactive web applications, but Panel focuses more on data visualization and dashboards, while FastUI is geared towards rapid development of modern web interfaces with a Python-first approach.

12,734

Flet enables developers to easily build realtime web, mobile and desktop apps in Python. No frontend experience required.

Pros of Flet

  • Cross-platform support for desktop, web, and mobile applications
  • Simpler setup and deployment process, especially for beginners
  • Rich set of pre-built UI components and controls

Cons of Flet

  • Less flexibility in terms of custom UI design and layout
  • Limited integration with existing web frameworks and technologies
  • Potentially steeper learning curve for developers familiar with web technologies

Code Comparison

FastUI example:

from fastui import FastUI, AnyComponent, components as c

@app.get("/")
def index() -> list[AnyComponent]:
    return [
        c.Page(components=[
            c.Heading(text="Hello World!"),
            c.Paragraph(text="Welcome to FastUI")
        ])
    ]

Flet example:

import flet as ft

def main(page: ft.Page):
    page.add(
        ft.Text("Hello World!"),
        ft.ElevatedButton("Welcome to Flet")
    )

ft.app(target=main)

Both FastUI and Flet aim to simplify UI development in Python, but they take different approaches. FastUI focuses on integrating with existing web technologies and frameworks, while Flet provides a more self-contained ecosystem for building cross-platform applications. The choice between them depends on the specific project requirements and developer preferences.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

NOTE: this project is inactive, see #368

FastUI

Find the documentation here. Join the discussion in the #fastui slack channel here

CI pypi versions license

Please note: FastUI is still an active work in progress, do not expect it to be complete.

The Principle (short version)

You can see a simple demo of an application built with FastUI here.

FastUI is a new way to build web application user interfaces defined by declarative Python code.

This means:

  • If you're a Python developer — you can build responsive web applications using React without writing a single line of JavaScript, or touching npm.
  • If you're a frontend developer — you can concentrate on building magical components that are truly reusable, no copy-pasting components for each view.
  • For everyone — a true separation of concerns, the backend defines the entire application; while the frontend is free to implement just the user interface

At its heart, FastUI is a set of matching Pydantic models and TypeScript interfaces that allow you to define a user interface. This interface is validated at build time by TypeScript and pyright/mypy and at runtime by Pydantic.

The Practice — Usage

FastUI is made up of 4 things:

Here's a simple but complete FastAPI application that uses FastUI to show some user profiles:

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')


# 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[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 `<h2>Users</h2>`
                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),
                    ],
                ),
            ]
        ),
    ]


@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),
            ]
        ),
    ]


@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'))

Which renders like this:

screenshot

Of course, that's a very simple application, the full demo is more complete.

Components

FastUI already defines a rich set of components.

All components are listed in the demo app.

The Principle (long version)

FastUI is an implementation of the RESTful principle; but not as it's usually understood, instead I mean the principle defined in the original PhD dissertation by Roy Fielding, and excellently summarised in this essay on htmx.org (HTMX people, I'm sorry to use your article to promote React which I know you despise 🙏).

The RESTful principle as described in the HTMX article is that the frontend doesn't need to (and shouldn't) know anything about the application you're building. Instead, it should just provide all the components you need to construct the interface, the backend can then tell the frontend what to do.

Think of your frontend as a puppet, and the backend as the hand within it — the puppet doesn't need to know what to say, that's kind of the point.

Building an application this way has a number of significant advantages:

  • You only need to write code in one place to build a new feature — add a new view, change the behavior of an existing view or alter the URL structure
  • Deploying the front and backend can be completely decoupled, provided the frontend knows how to render all the components the backend is going to ask it to use, you're good to go
  • You should be able to reuse a rich set of opensource components, they should end up being better tested and more reliable than anything you could build yourself, this is possible because the components need no context about how they're going to be used (note: since FastUI is brand new, this isn't true yet, hopefully we get there)
  • We can use Pydantic, TypeScript and JSON Schema to provide guarantees that the two sides are communicating with an agreed schema

In the abstract, FastUI is like the opposite of GraphQL but with the same goal — GraphQL lets frontend developers extend an application without any new backend development; FastUI lets backend developers extend an application without any new frontend development.

Beyond Python and React

Of course, this principle shouldn't be limited to Python and React applications — provided we use the same set of agreed schemas and encoding to communicate, we should be able to use any frontend and backend that implements the schema. Interchangeably.

This could mean:

  • Implementing a web frontend using another JS framework like Vue — lots of work, limited value IMHO
  • Implementing a web frontend using an edge server, so the browser just sees HTML — lots of work but very valuable
  • Implementing frontends for other platforms like mobile or IOT — lots of work, no idea if it's actually a good idea?
  • Implementing the component models in another language like Rust or Go — since there's actually not that much code in the backend, so this would be a relatively small and mechanical task