AnswerDotAI / fasthtml

The fastest way to create an HTML app
https://fastht.ml/
Apache License 2.0
5.09k stars 206 forks source link

Is there way to use it along with fastapi? Import fastapi inside fasthtml? Backend with fastapi and frontend with fasthtml, if yes please share examples #88

Closed saitej123 closed 1 month ago

saitej123 commented 1 month ago

Is there way to use it along with fastapi? Import fastapi inside fasthtml? Backend with fastapi and frontend with fasthtml !

In streamlit frontend and backend not decoupled

jph00 commented 1 month ago

There's not much need to, since fasthtml can already create json endpoints. Just return a dict from your handler.

Having said that, we'd recommend avoiding that where possible, and instead just returning FT/HTML partials the HTMX way!

saitej123 commented 1 month ago

Thanks for the clarification @jph00

AartGoossens commented 1 month ago

(I am re-using this issue as it's closely related)

I have an existing FastAPI application with a bunch of API endpoints. What would be the recommended way to serve a frontend generated by FastHTML from the same application?

  1. Switch from app = fastapi.FastAPI() to app, rt = fast_app() for the entire application.
  2. Use to_xml() to render FastHTML output in combination with response_class=HTMLResponse (see example 1 below)
  3. Mount the FastHTML application as a sub application within the original application, as documented here. See example 2 below.
  4. Another way that I haven't thought of.

What are the benefits, limitations and drawbacks of each of these options?

Example 1: using to_xml() and HTMLResponse

from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fasthtml import *
from fasthtml.core import to_xml

app = FastAPI()

@app.get("/", response_class=HTMLResponse)
def read_root():
    html = Titled("FastHTML", P("Let's do this!"))
    return to_xml(html)

Example 2: with mounting FastHTML as a sub application

from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fasthtml.fastapp import *

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "ok"}

fasthtml_app, rt = fast_app()

@rt("/")
def get():
    return Titled("FastHTML", P("Let's do this!"))

app.mount("/fasthtml", fasthtml_app)
bennettandrews commented 1 month ago

I'm also interested in this approach. In my case I have FastAPI applications with API endpoints for various ML tasks, but would like to also provide an admin UI to enable more control and visibility without standing up multiple apps.

ved93 commented 1 month ago

I am also looking for the same backend with fastapi and front end with fasthtml