はじめに
Python のモダン開発では、依存管理に Poetry、Web API に FastAPI を組み合わせる構成が最強です。
- 速い
- 再現性が高い
- CI/CD に強い
- 開発〜本番まで一貫した運用ができる
- Docker 化もスムーズ
本記事では、実務ですぐ使える「Poetry × FastAPI」テンプレートをまとめます。
1. 新規プロジェクトの作成
まず空のディレクトリで:
poetry new fastapi-app
cd fastapi-app
構成が生成される:
fastapi-app/
├── fastapi_app/
│ └── __init__.py
├── tests/
├── pyproject.toml
└── README.md
2. Poetry に FastAPI 依存を追加
本体
poetry add fastapi
ASGI サーバー(uvicorn)
poetry add uvicorn[standard]
(※ [standard] は uvloop + httptools で高速化)
3. ディレクトリ構成(実務向け)
FastAPI は後で機能が増えるので、最初から整理された構造を作るのがおすすめ。
fastapi-app/
├── fastapi_app/
│ ├── api/
│ │ ├── __init__.py
│ │ └── v1/
│ │ ├── __init__.py
│ │ └── router.py
│ ├── core/
│ │ ├── __init__.py
│ │ └── config.py
│ ├── main.py
│ └── __init__.py
├── tests/
├── pyproject.toml
└── README.md
4. FastAPI の基本ファイルを作成
fastapi_app/main.py
from fastapi import FastAPI
from fastapi_app.api.v1.router import router as v1_router
def create_app() -> FastAPI:
app = FastAPI(
title="FastAPI × Poetry App",
version="1.0.0",
)
app.include_router(v1_router, prefix="/api/v1")
return app
app = create_app()
fastapi_app/api/v1/router.py
from fastapi import APIRouter
router = APIRouter()
@router.get("/health")
def health_check():
return {"status": "ok"}
fastapi_app/core/config.py(設定管理)
後で DB 設定や JWT 設定を加える場合もここ。
from pydantic import BaseSettings
class Settings(BaseSettings):
app_name: str = "FastAPI × Poetry App"
debug: bool = True
settings = Settings()
5. ローカル実行
Poetry の仮想環境を起動:
poetry shell
起動:
uvicorn fastapi_app.main:app --reload
または、shell に入らず:
poetry run uvicorn fastapi_app.main:app --reload
アクセス:
http://127.0.0.1:8000/api/v1/health
Swagger UI:
http://127.0.0.1:8000/docs
6. テスト(pytest)
依存追加:
poetry add --dev pytest
テスト例:tests/test_health.py
from fastapi.testclient import TestClient
from fastapi_app.main import app
client = TestClient(app)
def test_health():
resp = client.get("/api/v1/health")
assert resp.status_code == 200
assert resp.json() == {"status": "ok"}
実行:
poetry run pytest
7. Docker 構成(実務向け)
Production-ready な Dockerfile をテンプレ化するよ。
Dockerfile
FROM python:3.11-slim AS builder
# Poetry install
ENV POETRY_VERSION=1.8.3
RUN pip install poetry==$POETRY_VERSION
WORKDIR /app
COPY pyproject.toml poetry.lock /app/
# 仮想環境は使わず、システムに直接インストールする
RUN poetry config virtualenvs.create false \
&& poetry install --no-dev --no-interaction --no-ansi
COPY . /app
CMD ["uvicorn", "fastapi_app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Docker build & run
docker build -t fastapi-poetry .
docker run -p 8000:8000 fastapi-poetry
8. requirements.txt を出力(必要なら)
Docker や Lambda 用に。
poetry export -f requirements.txt --without-hashes > requirements.txt
9. .env による設定管理(Optional)
追加:
poetry add python-dotenv
config.py で:
from pydantic import BaseSettings
class Settings(BaseSettings):
debug: bool = True
class Config:
env_file = ".env"
settings = Settings()
10. 本番(Production)構成 Tips
---workers を設定して gunicorn + uvicorn workers にする
- Logging を構成
- CORS 設定
- DB(SQLAlchemy / PostgreSQL)を追加
- JWT 認証を追加
- API ルート分割
- サービス / Repository 層の分離(Clean Architecture)
まとめ
| 項目 | 理由 |
|---|---|
| 依存管理 | lockfile で超安定 |
| 環境再現性 | Docker / CI/CD と相性抜群 |
| 速度 | uvicorn + FastAPI で高速 |
| 拡張性 | モジュール構成が自由 |
| 開発体験 | Beautiful API & Poetry CLI |
このテンプレさえ押さえれば、
さまざまな FastAPI プロジェクトにすぐ対応できます。