'A minimal fastapi example loading index.html

In my project folder I have a basic index.html file plus static files (js, css) as well as my main.py:

from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi import Request

app = FastAPI()

templates = Jinja2Templates(directory="/")
app.mount("/", StaticFiles(directory="/"))

@app.get("/")
def serve_home(request: Request):
    return templates.TemplateResponse("index.html", context= {"request": request}) 

How can I make fastapi work here? I just want my index.html and static files served on localhost. Is it problematic not to have a static or templates folder?



Solution 1:[1]

Option 1: Static file mounting

It was easier than expected. Just needed to put all static files including index.html into static folder in project directory and mount static files.

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

That's it. My index.html is now available under http://localhost:8000/static/index.html.

In case it should be accessible right under http://localhost:8000/ without /static and the .html ending one needs to change two things. First it needs to be mounted on / instead of /static and an HTML flag must be set to true when mounting. So just use this line instead:

app.mount("/", StaticFiles(directory="static",html = True), name="static")

(Thanks to this answer)

The index.html is now available under http://localhost:8000/


Option 2: Serving only index.html

As fastapi is based on starlette, a simple FileResponse does the job.

from starlette.responses import FileResponse 

@app.get("/")
async def read_index():
    return FileResponse('index.html')

Found here.

Solution 2:[2]

The best and most simple solution that worked for me:

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

api_app = FastAPI(title="api app")

@api_app.post("/set_influencers_to_follow")
async def set_influencers_to_follow(request):
    return {}

app = FastAPI(title="main app")

app.mount("/api", api_app)
app.mount("/", StaticFiles(directory="ui", html=True), name="ui")

If project structure is like:

??? main.py
??? ui
?   ??? index.html
?   ??? style.css
?   ??? script.js

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2