Search code examples
filesystemsfastapi

List files from a static folder in FastAPI


I know how to serve static files in FastAPI using StaticFiles, how can I enable directory listing like in Apache web server?

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI(...)

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

# GET http://localhost:8000/samples/path/to/file.jpg -> OK
# GET http://localhost:8000/samples -> not found error

Solution

  • I am not sure FastAPI/Starlette exposes functionality to do that out of the box.

    But it shouldn't be too hard to implement something yourself. This could be a starting point:

    import os
    from fastapi import FastAPI, Request
    from fastapi.responses import HTMLResponse
    from fastapi.staticfiles import StaticFiles
    from fastapi.templating import Jinja2Templates
    
    app = FastAPI()
    
    app.mount("/static", StaticFiles(directory="static"), name="static")
    
    
    templates = Jinja2Templates(directory="templates")
    
    
    @app.get("/static", response_class=HTMLResponse)
    def list_files(request: Request):
    
        files = os.listdir("./static")
        files_paths = sorted([f"{request.url._url}/{f}" for f in files])
        print(files_paths)
        return templates.TemplateResponse(
            "list_files.html", {"request": request, "files": files_paths}
        )
    
    

    list_files.html

    <html>
      <head>
        <title>Files</title>
      </head>
      <body>
        <h1>Files:</h1>
        <ul>
          {% for file in files %}
          <li><a href="{{file}}">{{file}}</a></li>
          {% endfor %}
        </ul>
      </body>
    </html>
    
    

    When you hit /static you would see:

    enter image description here


    Additional notes

    Note that list_files.html is an html template and should sit in the directory templates/ as @Michel Hua pertinently mentioned in his comment. For more info on templates check the templates docs.