Top Related Projects
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Streamlit — A faster way to build and share data apps.
Data Apps & Dashboards for Python. No JavaScript Required.
Build and share delightful machine learning apps, all in Python. 🌟 Star to support our work!
Panel: The powerful data exploration & web app framework for Python
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:
- Install the FastUI library using pip:
pip install fastui
- 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()
- 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
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.
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.
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.
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.
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.
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
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
NOTE: this project is inactive, see #368
FastUI
Find the documentation here. Join the discussion in the #fastui slack channel here
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:
fastui
PyPI package â Pydantic models for UI components, and some utilities. While it works well with FastAPI it doesn't depend on FastAPI, and most of it could be used with any python web framework.@pydantic/fastui
npm package â a React TypeScript package that lets you reuse the machinery and types of FastUI while implementing your own components@pydantic/fastui-bootstrap
npm package â implementation/customisation of all FastUI components using Bootstrap@pydantic/fastui-prebuilt
npm package (available on jsdelivr.com CDN) providing a pre-built version of the FastUI React app so you can use it without installing any npm packages or building anything yourself. The Python package provides a simple HTML page to serve this app.
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:
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
Top Related Projects
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Streamlit — A faster way to build and share data apps.
Data Apps & Dashboards for Python. No JavaScript Required.
Build and share delightful machine learning apps, all in Python. 🌟 Star to support our work!
Panel: The powerful data exploration & web app framework for Python
Flet enables developers to easily build realtime web, mobile and desktop apps in Python. No frontend experience required.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot