Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

FastAPI Static Files

FastAPI Static Files

FastAPI can easily serve static files (such as images, CSS, and JavaScript files) using Starlette's StaticFiles implementation based on the dynamic type of the object.


Install dependencies

StaticFiles included in aiofiles , you need to install:

pip install aiofiles


Mount a static files directory

Use app.mount() Mount a static files directory on the application:

Example

from

fastapi

import

FastAPI

from

fastapi.

staticfiles

import

StaticFiles

app

=

FastAPI

(

)

Mount a static files directory

"/static" is the URL path prefix

directory="static" is the local directory name

app.

mount

(

"/static"

,

StaticFiles

(

directory

=

"static"

)

,

name

=

"static"

)

@

app.

get

(

"/"

)

async

def

root

(

)

:

   

return

{

"message"

:

"Hello World"

}

Code explanation:

Parameters Description
"/static" URL path prefix, e.g. when visiting /static/logo.png
directory="static" Local directory name, the folder that stores static files
name="static" Internal name used to generate URLs (via url_for)

mount mounts an independent "sub-application" at a specified path.StaticFiles is itself an ASGI application that handles static file requests. After mounting, all requests starting with /static are handled by StaticFiles , and do not pass through FastAPI's routing system.


Example directory structure

project/

├── main.py

└── static/

    ├── css/

    │   └── style.css

    ├── js/

    │   └── app.js

    └── images/

        └── logo.png

How to access:

File path URL
static/css/style.css http://127.0.0.1:8000/static/css/style.css
static/js/app.js http://127.0.0.1:8000/static/js/app.js
static/images/logo.png http://127.0.0.1:8000/static/images/logo.png

HTML template rendering

FastAPI supports the Jinja2 template engine, allowing dynamic rendering of HTML pages:

Example

from

fastapi

import

FastAPI

,

Request

from

fastapi.

staticfiles

import

StaticFiles

from

fastapi.

templating

import

Jinja2Templates

app

=

FastAPI

(

)

Static files

app.

mount

(

   

"/static"

,

    StaticFiles

(

directory

=

"static"

)

,

    name

=

"static"

)

Jinja2 Templates

templates

=

Jinja2Templates

(

    directory

=

"templates"

)

@

app.

get

(

"/hello/{name}"

)

async

def

hello

(

request: Request

,

name:

str

)

:

   

return

templates.

TemplateResponse

(

        request

=

request

,

        name

=

"hello.html"

,

        context

=

{

           

"name"

: name

       

}

   

)

Template files templates/hello.html:

Example

   

<p>Hello</p>

   

   

Hello, {{ name }}!

   

Logo

When rendering templates, you must pass the request object, because the template may need to use the request context (e.g. to generate URLs).


Summary