Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

FastAPI - serve static files - JavaScript example

import os

from fastapi import FastAPI, Response
from fastapi.staticfiles import StaticFiles

root = os.path.dirname(os.path.abspath(__file__))

app = FastAPI()

app.mount("/js", StaticFiles(directory=os.path.join(root, 'js')), name="js")

@app.get("/")
async def main():
    with open(os.path.join(root, 'index.html')) as fh:
        data = fh.read()
    return Response(content=data, media_type="text/html")


function demo() {
    console.log("demo");
    document.getElementById("content").innerHTML = "Written by JavaScript";
}

demo();
<h1>Static HTML</h2>

<div id="content"></div>

<script src="/js/demo.js"></script>