Hosting Static Website using FastAPI and Uvicorn

Here is an example program that allows you to host a static website with HTML, CSS and JPEG files using FastAPI and Uvicorn. The example assumes that all the static files are located inside the “site” directory and its sub-directories (e.g. css, images sub-directories etc).

from os.path import isfile
from fastapi import Response
from mimetypes import guess_type
from fastapi.responses import FileResponse
from fastapi import FastAPI

app = FastAPI()

@app.get("/{filename}")
async def get_site(filename):
    filename = './site/' + filename

    if not isfile(filename):
        return Response(status_code=404)
    else:
        return FileResponse(filename)

@app.get("/")
async def get_site_default_filename():
    return await get_site('index.html')

Leave a comment