nikkie-ftnextの日記

イベントレポートや読書メモを発信

FastAPIは0.138.0でフロントエンドアプリを配信できるようになりました!

はじめに

ロンリーユニバース、エモ... nikkie (UUID 28fb3f96-a221-462c-93bd-567b431715b9) です。

FastAPIがやってくれました!👏

目次

✨ Add support for app.frontend("/", directory="dist") and router.frontend("/", directory="dist")

0.138.0の目玉機能!

FastAPI作者のtiangolo氏による実装です

テストコードを一例見ると、distディレクトリに置いたHTMLを配信しています。
https://github.com/fastapi/fastapi/blob/0.138.0/tests/test_frontend.py#L20

FastAPI Tutorial「Frontend」

今回追加されたドキュメント

fastapi.tiangolo.com

ディレクトリ構造の例1

.
├── pyproject.toml
├── app
│   ├── __init__.py
│   └── main.py
└── dist  # npm run buildなどで生成
    ├── index.html
    └── assets
        └── app.js

app/main.pyapp.frontend("/", directory="dist")としたとき

a request for /assets/app.js can serve dist/assets/app.js.

FastAPIのpath operationと組合せられる点に可能性を感じます!

引数についての説明もありました

fallback引数

FastAPI uses this fallback only for requests that look like browser navigation.

  • fallback="index.html"2:SPA想定
    • if accessing that URL directly (instead of navigating through the app), the backend should serve the frontend app from index.html, so that the frontend framework can then handle the client-side routing.

  • fallback="404.html"3:静的な404.htmlページ
    • That response keeps a status code of 404.

  • fallback="auto"4デフォルト値
    • 404.html -> index.htmlの順で存在するファイルを探す
  • fallback=None5:無効化
    • Then missing frontend paths return the normal 404.

check_dir引数

https://fastapi.tiangolo.com/tutorial/frontend/#check-directory

By default, app.frontend() checks that the directory exists when the app is created.

If your frontend files are created later, for example by a separate build step after the app object is created, set check_dir=False:

その他

FastAPIインスタンスだけでなく、APIRouterでも.frontend()は使えます[^5]。

フロントエンドビルドで生成済みのファイルを配信するだけです6

It does not run server-side rendering. It is for frontend frameworks that generate static files, not for frameworks that need dynamic rendering on the server for each request.

Reveal.js製スライドHTMLを配信!

HTMLでもいいと聞いて、sphinx-revealjsで作ったスライド7をPC内で配信してみました8

# 完全版 https://github.com/ftnext/2026-slides/blob/735e2882f67c91c0a6693a3611b0ce0f12373fd2/app.py
from fastapi import FastAPI

app = FastAPI()
app.frontend("/", directory="build/revealjs")

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app)

実用的ではなさそうですが、Sphinxのドキュメント(静的HTML)をFastAPIで配信できる

終わりに

FastAPI 0.138.0で追加されたapp.frontend()を触りました。
私はフロントエンドが書けないのですが、静的なHTMLだけでもFastAPIで配信できました。