from fasthtml.common import *
fasthtml
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.
Install
pip install python-fasthtml
For a minimal app, create a file “main.py” as follows:
main.py
from fasthtml.fastapp import *
= fast_app()
app = app.route
rt
@rt("/")
def get():
return Titled("FastHTML", P("Let's do this!"))
run_uv()
How to use
Import from fasthtml.common
:
Create your app.
= FastHTML() app
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:
@app.get('/user/{nm}')
def get_nm(nm:str): return f"Good day to you, {nm}!"
Normally you’d save this into a file such as main.py, 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
= TestClient(app)
client = client.get('/user/Jeremy')
r r
<Response [200 OK]>
TestClient uses httpx
behind the scenes, so it returns a httpx.Response
, which has a text
attribute with our response body:
r.text
'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
:
= app.route
rt
@rt('/')
def post(): return "Going postal!"
'/').text client.post(
'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:
@app.get('/html/{idx}')
async def _(idx:int):
return Body(
"Wow look here"),
H4(f'It looks like you are visitor {idx}! Next is {idx+1}.')
P( )
from IPython import display
'/html/1').text) display.HTML(client.get(
Wow look here
It looks like you are visitor 1! Next is 2.
Features
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()}
= FastHTML()
app = app.route
rt
@app.get("/")
def _(req): return todict(req.scope)
= TestClient(app)
cli = cli.get('/')
r print(r.text)
{"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":"{}"}
@app.get('/user/{nm}')
def _(nm:str): return f"Good day to you, {nm}!"
'/user/jph').text cli.get(
'Good day to you, jph!'
@rt('/html/{idx}')
async def get(idx:int):
return Body(
"Wow look here"),
H4(f'It looks like you are visitor {idx}! Next is {idx+1}.')
P(
)
'/html/1').text) display.HTML(cli.get(
Wow look here
It looks like you are visitor 1! Next is 2.
"imgext", "ico|gif|jpg|jpeg|webm")
reg_re_param(
@app.get(r'/static/{path:path}{fn}.{ext:imgext}')
def get_img(fn:str, path:str, ext:str): return f"Getting {fn}.{ext} from /{path}"
'/static/foo/jph.ico').text cli.get(
'Getting jph.ico from /foo/'
= str_enum('ModelName', "alexnet", "resnet", "lenet")
ModelName
@app.get("/models/{nm}")
def model(nm:ModelName): return nm
print(cli.get('/models/alexnet').text)
alexnet
@app.get("/files/{path}")
async def txt(path: Path): return path.with_suffix('.txt')
print(cli.get('/files/foo').text)
foo.txt
= [{"name": "Foo"}, {"name": "Bar"}]
fake_db
@app.get("/items/")
def read_item(idx:int|None = 0): return fake_db[idx]
print(cli.get('/items/?idx=1').text)
{"name":"Bar"}
print(cli.get('/items/').text)
{"name":"Foo"}
@app.get("/booly/")
def booly(coming:bool=True): return 'Coming' if coming else 'Not coming'
print(cli.get('/booly/?coming=true').text)
Coming
print(cli.get('/booly/?coming=no').text)
Not coming
@app.get("/datie/")
def datie(d:date): return d
= "17th of May, 2024, 2p"
date_str print(cli.get(f'/datie/?d={date_str}').text)
2024-05-17 14:00:00
@dataclass
class Bodie:
int;b:str
a:
@rt("/bodie/{nm}")
async def post(nm:str, data:Bodie):
= asdict(data)
res 'nm'] = nm
res[return res
'/bodie/me', data=dict(a=1, b='foo')).text cli.post(
'{"a":1,"b":"foo","nm":"me"}'
@app.get("/setcookie")
async def setc(req):
= datetime.now()
now = Response(f'Set to {now}')
res 'now', str(now))
res.set_cookie(return res
'/setcookie').text cli.get(
'Set to 2024-06-01 19:55:03.088788'
@app.get("/getcookie")
async def getc(now:date): return f'Cookie was set at time {now.time()}'
'/getcookie').text cli.get(
'Cookie was set at time 19:55:03.088788'
@app.get("/ua")
async def ua(user_agent:str): return user_agent
'/ua', headers={'User-Agent':'FastHTML'}).text cli.get(
'FastHTML'
@app.get("/hxtest")
def hxtest(htmx): return htmx.request
'/hxtest', headers={'HX-Request':'1'}).text cli.get(
'1'
Live Reloading
When building your app it can be useful to view your changes in a web browser as you make them. FastHTML supports live reloading which means that it watches for any changes to your code and automatically refreshes the webpage in your browser.
To enable live reloading simply replace FastHTML
in your app with FastHTMLWithLiveReload
.
from fasthtml.common import *
= FastHTMLWithLiveReload() app
Then in your terminal run uvicorn
with reloading enabled.
uvicorn: main:app --reload
⚠️ Gotchas - A reload is only triggered when you save your changes. - FastHTMLWithLiveReload
should only be used during development. - If your app spans multiple directories you might need to use the --reload-dir
flag to watch all files in each directory. See the uvicorn docs for more info.