0
1

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>

説明

  1. FastAPIインスタンスを作成し、Jinja2Templatesオブジェクトを初期化して、テンプレートディレクトリを指定します。

  2. ルートパス("/")へのGETリクエストを処理する関数を定義します。この関数はHTMLResponseを返すように設定されています。

  3. templates.TemplateResponseを使用して、テンプレートをレンダリングします。テンプレート名と、テンプレートに渡すデータ(この場合はrequestオブジェクトとmessage)を指定します。

  4. テンプレートファイル(index.html)では、Jinja2の構文を使用して動的にデータを挿入します。{{ message }}は、Pythonコードから渡されたmessage変数の値に置き換えられます。

実行方法

プロジェクトディレクトリで以下のコマンドを実行します:

python main.py

その後、ブラウザでhttp://localhost:8000にアクセスすると、"Hello, FastAPI!"というメッセージが表示されます。

image.png

まとめ

FastAPIは主にAPIの構築に使用されますが、このように簡単にHTMLテンプレートを使用して画面を出力することもできます。これにより、APIと画面の両方を1つのフレームワークで効率的に開発することが可能になります。

より複雑なアプリケーションを構築する場合は、静的ファイルの提供、フォーム処理、データベース連携などの機能を追加することで、フル機能のWebアプリケーションを開発することができます。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1