アプリを拡張する
このページでは、shop に /users リソースを追加します。最初は 1 つの main.py に手作業で追加し、次に layered レベルのプロジェクトで fastkit addroute を使って追加します。FastAPI がアプリケーションをルーター(APIRouter と include_router)に分割する方法、依存関係(Depends)がエンドポイントにオブジェクトを渡す仕組み、設定が環境変数や .env から読み込まれる仕組み、そして CORS ミドルウェアの役割を学びます。
/users を手作業で追加する
エンドポイントを追加するいちばん手早い方法は、動いているエンドポイントをコピーすることです。アプリを生成するで作成した hello プロジェクトで、Item モデルと 2 つのアイテム用エンドポイントを main.py の末尾にコピーし、ユーザー用に名前を変えます。
class User(BaseModel):
name: str = Field(min_length=1, max_length=100)
email: str = Field(min_length=3, max_length=254)
class StoredUser(User):
id: int
users: dict[int, StoredUser] = {}
@app.post("/users", status_code=status.HTTP_201_CREATED)
async def create_user(user: User) -> StoredUser:
stored = StoredUser(id=len(users) + 1, **user.model_dump())
users[stored.id] = stored
return stored
@app.get("/users/{user_id}")
async def read_user(user_id: int) -> StoredUser:
if user_id not in users:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="User not found")
return users[user_id]
tests/test_main.py では、import 文を from main import app, items, users に変え、empty_store フィクスチャの中にある各 items.clear() の後に users.clear() を加えます。そして、末尾に 2 つのテストを追加します。
ADA = {"name": "Ada", "email": "ada@example.com"}
def test_create_user_returns_it_with_a_new_id() -> None:
response = client.post("/users", json=ADA)
assert response.status_code == 201
assert response.json() == {**ADA, "id": 1}
def test_read_user_that_does_not_exist() -> None:
response = client.get("/users/42")
assert response.status_code == 404
assert response.json() == {"detail": "User not found"}
1 ファイルでは足りなくなったら
fastkit addroute はリソースを自動で追加しますが、新しいモジュールを置くためのパッケージが必要です。hello プロジェクトでは追加を断り、その理由を表示します。
$ fastkit addroute users .
╭───────────────────────────────── Error ──────────────────────────────────╮
│ ❌ This project keeps its whole application in main.py, so there is no │
│ package to add route modules to. Add the endpoint to main.py by hand, │
│ next to the existing ones (copy one endpoint and its test), or create a │
│ project at a later level with `fastkit init --level layered` (`fastkit │
│ list-templates` lists the templates). │
╰──────────────────────────────────────────────────────────────────────────╯
layered レベルでは、アプリケーションがルート、データアクセス(crud)、スキーマ、コア設定の各パッケージに分かれています。fastkit はプロジェクトを別のレベルに変換しないので、hello プロジェクトのフォルダーの外に新しいプロジェクトを作成してください(shop フォルダーがまだ存在しない場所である必要があります)。-y を付けると、質問せずにすべての既定値を受け入れます。
$ fastkit init --level layered --name shop -y
...
$ cd shop
$ find src -name '*.py' -not -name '__init__.py' | sort
src/api/api.py
src/api/deps.py
src/api/routes/items.py
src/core/config.py
src/core/pagination.py
src/core/responses.py
src/crud/items.py
src/main.py
src/schemas/items.py
アイテムは src/mocks/mock_items.json というファイルに保存されるようになったので、再起動しても残ります。また、すべてのエンドポイントは /api/v1/items のように /api/v1 の下に置かれます。
ルーターと依存関係
APIRouter は、専用のモジュールに書くパスオペレーションのまとまりで、@app.get(...) の代わりに @router.get(...) を使います。src/api/routes/items.py は APIRouter(prefix="/items", tags=["items"]) でルーターを作成しており、このプレフィックスとタグはそのルーターのすべてのエンドポイントに適用されます。include_router は、あるルーターのエンドポイントを別のルーターやアプリに追加します。src/api/api.py は、各リソースのルーターを 1 つにまとめます。
# One APIRouter collects the routers of every module; main.py mounts it once.
# https://fastapi.tiangolo.com/tutorial/bigger-applications/
api_router = APIRouter()
api_router.include_router(items.router)
# fastkit:routes
続いて src/main.py が、app.include_router(api_router, prefix=settings.API_V1_PREFIX) でこのルーターを一度だけ組み込みます。両方のファイルにある # fastkit:imports と # fastkit:routes のコメントは、fastkit addroute が行を追加する位置を示す目印なので、消さずに残してください。
依存関係とは、エンドポイントより先に FastAPI が呼び出す関数で、その戻り値がエンドポイントに渡されます。依存関係は Depends(...) で宣言します。Annotated で別名を付けておくと、どのエンドポイントからでも再利用できます。
def get_item_store() -> ItemStore:
"""Return the item store (tests override this dependency)."""
return item_store
# ...
ItemStoreDep = Annotated[ItemStore, Depends(get_item_store)]
アイテム用の各エンドポイントは、def get_item(item_id: int, store: ItemStoreDep) -> ItemRead のように store: ItemStoreDep を宣言しています。ストアを自分で作成するエンドポイントは 1 つもないので、テストでは get_item_store を独自のストアに置き換えられます(その方法はアプリをテストするで説明します)。
設定と CORS
設定とは、シークレットキーや許可するオリジンのように、マシンによって変わる値です。pydantic-settings の BaseSettings クラスは、各フィールドの値を同じ名前の環境変数または .env ファイルから読み込み、どちらにもなければ既定値を使います。
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
env_ignore_empty=True,
extra="ignore",
)
fastkit は、固有の SECRET_KEY を入れた .env を書き出しました。.env は Git の管理対象から除外されており、次に作業する人のために .env.example にすべての設定が列挙されています。その設定の 1 つが BACKEND_CORS_ORIGINS です。別のオリジン(スキーム、ホスト、ポートの組)の Web ページが API を呼び出すと、ブラウザーは API の CORS ヘッダーを読み、そのページがレスポンスを読み取ってよいかどうかを判断します。CORS ミドルウェアは、列挙したオリジンに対してこのヘッダーを送ります。たとえば .env に BACKEND_CORS_ORIGINS=http://localhost:3000 と書きます。src/main.py は、このリストが空でない場合にだけミドルウェアを組み込みます。CORS は認証ではありません。curl やほかのサーバーのような、ほかのクライアントが API を呼び出すことは防げません。
fastkit で users を追加する
--dry-run を付けると、fastkit addroute が書き込む予定のファイルを一覧表示します。--diff を付けると、それぞれの変更内容も表示します。
$ fastkit addroute users . --dry-run
...
Files to create (4):
+ src/api/routes/users.py
+ src/crud/users.py
+ src/schemas/users.py
+ tests/test_users.py
Files to modify (2):
~ src/api/deps.py
~ src/api/api.py
...
--dry-run を外してもう一度実行し、確認に答えます。新しいリソースには、/api/v1/users の下に、ページネーション付きの一覧、作成(201)、取得、置換(PUT)、更新(PATCH)、削除(204)があり、それぞれにテストがあります。スキーマは最初は name と description を持っています。自分のフィールドに合わせて src/schemas/users.py を編集してください。src/api/api.py には 2 つの目印の下にルーターの import 文と include_router の行が追加され、src/api/deps.py には新しい依存関係の別名が追加されます。この別名は src/api/routes/users.py が import します。
from src.crud.users import UserRepository, get_user_repository
# ...
UserRepositoryDep = Annotated[UserRepository, Depends(get_user_repository)]
ここで uv run pytest -q を実行すると、91 passed と表示されます。プロジェクトに最初から含まれていた 74 個のテストと、tests/test_users.py に追加された 17 個のテストです。
hello と layered の間には single-file レベルがあります。このレベルでは、アプリケーション全体が 1 つの src/main.py にまとまっており、設定とテストも用意されています。このレベルで fastkit addroute を初めて使うと、src/main.py の周りに api、crud、schemas、core の各パッケージが追加されます。
FastAPI のドキュメント
次へ
アプリをテストするでは、layered レベルのプロジェクトのテストを読み、新しいテストを書きます。