Skip to content

Instantly share code, notes, and snippets.

@cgarciae
Last active August 3, 2024 15:04
Show Gist options
  • Save cgarciae/a11185da9d693a1f60389c49412c476f to your computer and use it in GitHub Desktop.
Save cgarciae/a11185da9d693a1f60389c49412c476f to your computer and use it in GitHub Desktop.
FastHTMLResponse class for FastAPI
from typing import Iterable
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
import fasthtml.common as fasthtml
from fasthtml.components import *
app = FastAPI()
class FastHTMLResponse(HTMLResponse):
def render(self, content) -> bytes:
if isinstance(content, str):
pass
elif isinstance(content[0], str):
content = fasthtml.to_xml(content)
else:
content = "\n".join(fasthtml.to_xml(c) for c in content)
return super().render(content)
@app.get("/", response_class=FastHTMLResponse)
def index():
return [
Title("App"),
Div(
H1("Hello, World!"),
P("This is a paragraph."),
),
]
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=5001, reload=True)
@cgarciae
Copy link
Author

cgarciae commented Aug 2, 2024

FastHTML integration with FastAPI

Simple example of how to use FastHTML python components with FastAPI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment