3

I need to serve a directory that contains data, like how Apache serves an index, and I would like to serve it through my FastAPI application.

Is that possible with FastAPI or Starlette?

If not, Simplehttpserver alternatives suggests Twistd as a python package. Is it possible to have FastAPI redirect to a twistd server at the directory mount?

Matt Leader
  • 133
  • 1
  • 8

1 Answers1

0

You're looking for the StaticFiles utility:

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

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

Arguments usage is documented on FastAPI documentation:

  • The first "/" refers to the path this "sub-application" will be "mounted" on. Kn this case, all paths will be handled by it.

  • The directory="static" refers to the name of the directory that contains your static files on your local filesystem.

  • The name="static" gives it a name that can be used internally by FastAPI.

All these parameters can be different than "static", adjust them with the needs and specific details of your own application.

Note: You will need to install aiofiles: pip install aiofiles

gcharbon
  • 1,561
  • 12
  • 20