Skip to main content

The fastest way to create an HTML app

Project description


Please note: this repo is public so that we can build in the open, and interested folks can participate and/or observe. But it’s not released yet, so please don’t share links to this project on social media etc – the project is not ready yet for public use and it would be very distracting to deal with publicity of an unreleased project.

fasthtml is a library for writing fast and scalable Starlette-powered web applications, without having to learn much (if any!) Starlette. Instead, you just use plain python functions for each page in your app – you don’t even need to learn Javascript. The finished app will be about as fast as a Python web server can be (which is pretty fast – e.g. Instagram runs on Python), and you can create pretty much anything. This isn’t one of those stripped-down dashboard making thingies.

This is a way to write real web applications, without the fuss.

To learn how to use it, please visit the documentation.


pip install python-fasthtml

For a minimal app, create a file “” as follows:

from fasthtml.all import *
import uvicorn

app = FastHTML()
rt = app.route

def get():
  return Title("FastHTML"), H1("Hello World!")

if __name__ == '__main__':, host='', port=int(os.getenv("PORT", default=8000)))

How to use

Import from fasthtml.all:

from fasthtml.all import *

Create your app.

app = FastHTML()

Create your routes. The syntax is largely the same as the wonderful FastAPI (which is what you should be using instead of this if you’re creating a JSON service. FastHTML is for mainly for making HTML web apps, not APIs).

Note that you need to include the types of your parameters, so that FastHTML knows what to pass to your function. Here, we’re just expecting a string:

def get_nm(nm:str): return f"Good day to you, {nm}!"

Normally you’d save this into a file such as, and then run it in uvicorn using:

uvicorn main:app

However, for testing, we can use Starlette’s TestClient to try it out:

from starlette.testclient import TestClient
client = TestClient(app)
r = client.get('/user/Jeremy')
<Response [200 OK]>

TestClient uses httpx behind the scenes, so it returns a httpx.Response, which has a text attribute with our response body:

'Good day to you, Jeremy!'

In the previous example, the function name (get_nm) didn’t actually matter – we could have just called it _, for instance, since we never actually call it directly. It’s just called through HTTP. In fact, we often do call our functions _ when using this style of route, since that’s one less thing we have to worry about naming.

An alternative approach to creating a route is to use app.route instead, in which case you make the function name the HTTP method you want. Since this is such a common pattern, you might like to give a shorter name to app.route – we normally use rt:

rt = app.route

def post(): return "Going postal!"'/').text
'Going postal!'

FastHTML has special handling of tags created using fastcore.xml, so you can return web pages without worrying about Jinja, templates, or any of that stuff. This also means you can pip install styled rich component libraries, since it’s all just pure python:

async def _(idx:int):
    return Body(
        H4("Wow look here"),
        P(f'It looks like you are visitor {idx}! Next is {idx+1}.')
from IPython import display

Wow look here

It looks like you are visitor 1! Next is 2.


Here’s a brief demo of all the features of the library:

from starlette.responses import Response
from datetime import datetime
from fastcore.utils import *
from dataclasses import dataclass, asdict
def todict(req): return {k:str(v) for k,v in req.items()}
app = FastHTML()
rt = app.route

def _(req): return todict(req.scope)
cli = TestClient(app)
r = cli.get('/')
{"type":"http","http_version":"1.1","method":"GET","path":"/","raw_path":"b'/'","root_path":"","scheme":"http","query_string":"b''","headers":"[(b'host', b'testserver'), (b'accept', b'*/*'), (b'accept-encoding', b'gzip, deflate, br'), (b'connection', b'keep-alive'), (b'user-agent', b'testclient')]","client":"['testclient', 50000]","server":"['testserver', 80]","extensions":"{'http.response.debug': {}}","state":"{}","app":"<fasthtml.core.FastHTML object>","session":"{}","starlette.exception_handlers":"({<class 'starlette.exceptions.HTTPException'>: <bound method ExceptionMiddleware.http_exception of <starlette.middleware.exceptions.ExceptionMiddleware object>>, <class 'starlette.exceptions.WebSocketException'>: <bound method ExceptionMiddleware.websocket_exception of <starlette.middleware.exceptions.ExceptionMiddleware object>>}, {})","router":"<fasthtml.core.RouterX object>","endpoint":"<function _wrap_ep.<locals>._f>","path_params":"{}"}
def _(nm:str): return f"Good day to you, {nm}!"

'Good day to you, jph!'
async def get(idx:int):
    return Body(
        H4("Wow look here"),
        P(f'It looks like you are visitor {idx}! Next is {idx+1}.')


Wow look here

It looks like you are visitor 1! Next is 2.

reg_re_param("imgext", "ico|gif|jpg|jpeg|webm")

def get_img(fn:str, path:str, ext:str): return f"Getting {fn}.{ext} from /{path}"

'Getting jph.ico from /foo/'
ModelName = str_enum('ModelName', "alexnet", "resnet", "lenet")

def model(nm:ModelName): return nm

async def txt(path: Path): return path.with_suffix('.txt')

fake_db = [{"name": "Foo"}, {"name": "Bar"}]

def read_item(idx:int|None = 0): return fake_db[idx]

def booly(coming:bool=True): return 'Coming' if coming else 'Not coming'

Not coming
def datie(d:date): return d

date_str = "17th of May, 2024, 2p"
2024-05-17 14:00:00
class Bodie:

async def post(nm:str, data:Bodie):
    res = asdict(data)
    res['nm'] = nm
    return res'/bodie/me', data=dict(a=1, b='foo')).text
async def setc(req):
    now =
    res = Response(f'Set to {now}')
    res.set_cookie('now', str(now))
    return res

'Set to 2024-06-01 19:55:03.088788'
async def getc(now:date): return f'Cookie was set at time {now.time()}'

'Cookie was set at time 19:55:03.088788'
async def ua(user_agent:str): return user_agent

cli.get('/ua', headers={'User-Agent':'FastHTML'}).text
def hxtest(htmx): return htmx.request

cli.get('/hxtest', headers={'HX-Request':'1'}).text

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python-fasthtml-0.0.10.tar.gz (26.7 kB view hashes)

Uploaded Source

Built Distribution

python_fasthtml-0.0.10-py3-none-any.whl (24.9 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page