FastAPIは高速なWeb APIを構築するためのモダンなPythonフレームワークですが、HTMLテンプレートを使用して画面を出力することも可能です。この記事では、FastAPIとJinja2テンプレートエンジンを組み合わせて、動的なHTML画面を生成する方法を説明します。
環境設定
まず、必要なパッケージをインストールします:
pip install fastapi uvicorn jinja2
プロジェクト構造
プロジェクトは以下のような構造にします:
my_fastapi_project/
│
├── main.py
└── templates/
└── index.html
コード実装
main.py
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse("index.html", {"request": request, "message": "Hello, FastAPI!"})
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
templates/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FastAPI Template Example</title>
</head>
<body>
<h1>{{ message }}</h1>
</body>
</html>
説明
-
FastAPI
インスタンスを作成し、Jinja2Templates
オブジェクトを初期化して、テンプレートディレクトリを指定します。 -
ルートパス("/")へのGETリクエストを処理する関数を定義します。この関数は
HTMLResponse
を返すように設定されています。 -
templates.TemplateResponse
を使用して、テンプレートをレンダリングします。テンプレート名と、テンプレートに渡すデータ(この場合はrequest
オブジェクトとmessage
)を指定します。 -
テンプレートファイル(index.html)では、Jinja2の構文を使用して動的にデータを挿入します。
{{ message }}
は、Pythonコードから渡されたmessage
変数の値に置き換えられます。
実行方法
プロジェクトディレクトリで以下のコマンドを実行します:
python main.py
その後、ブラウザでhttp://localhost:8000
にアクセスすると、"Hello, FastAPI!"というメッセージが表示されます。
まとめ
FastAPIは主にAPIの構築に使用されますが、このように簡単にHTMLテンプレートを使用して画面を出力することもできます。これにより、APIと画面の両方を1つのフレームワークで効率的に開発することが可能になります。
より複雑なアプリケーションを構築する場合は、静的ファイルの提供、フォーム処理、データベース連携などの機能を追加することで、フル機能のWebアプリケーションを開発することができます。