FastAPI - serve static files - JavaScript example
examples/fastapi/static-files/main.py
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")
examples/fastapi/static-files/js/demo.js
function demo() { console.log("demo"); document.getElementById("content").innerHTML = "Written by JavaScript"; } demo();
examples/fastapi/static-files/index.html
<h1>Static HTML</h2> <div id="content"></div> <script src="/js/demo.js"></script>