Category
Pythonバックエンド(FastAPI / SQLAlchemy / Pydantic)の実装ガイド
Pythonバックエンドは、動的言語でも「型と検証」を境界に効かせることで本番品質に届きます。FastAPIの非同期とDI、Pydantic v2での入力検証、SQLAlchemy 2の型付きORM、Alembicでの無停止マイグレーション——スキーマを単一真実源に、安全に進化し続けるサーバー設計を扱います。さらにFastAPIの入力検証(クエリ/パス/ボディ/フォームをAnnotated×Query/Path/Bodyで型安全に宣言・min_length/pattern/ge/leなどの制約・クエリパラメータモデルとextra=forbid・Body(embed)/Field・UUID/datetime等の特殊型・422整形)、認証・認可(OAuth2パスワードフロー・PyJWTによるJWT発行/検証・pwdlib(Argon2)のパスワードハッシュ・Security scopesによる権限制御)と、大規模アプリ設計(APIRouterによる分割・公式推奨プロジェクト構成・グローバル/ルーター/デコレータ/引数の4階層の依存性注入・router→service→repositoryのレイヤリング・循環インポート回避・APIバージョニング)まで、公式ドキュメント最新版に忠実な実コードで体系化します。Pydantic v2に特化した設計(境界バリデーション・パフォーマンス・カスタム型・PydanticAI・LLM構造化出力)は『Pydantic・型安全バリデーション』クラスタにまとめています。
11 articles in total
Foundational guide
Foundational guide (start here)
FastAPI Production-Operations Guide: Building APIs That Don't Fall Over with the Right Use of async, Pydantic v2 Boundary Validation, DI, and Observability
An implementation guide to operating FastAPI at production quality. Faithful to the official documentation, it explains the use of async def / def, Pydantic v2 boundary validation, dependency injection with Depends, structured logs and OpenTelemetry observability, the limits of BackgroundTasks and how to offload to a task queue, and testing and deployment—all in real code.
Related practical articles
- Python型安全アーキテクチャ設計パフォーマンスPydantic
Python Data Types Complete Guide: The 'Right Use' of Numbers, Strings, and Collections, and Designs That Don't Break in Production
Systematizing Python's built-in data types (int / float / Decimal, str, bool, None, list / tuple / dict / set) from CPython's internal structure, mutability, and complexity to production design. From float error and handling money, mutable default arguments, is vs ==, type hints, to boundary validation with Pydantic / marshmallow, explained as 'axes for deciding which to use' with practical knowledge from real projects.
25 min read - Pythonアーキテクチャ設計型安全パフォーマンスPydantic
The Complete Guide to Python Mappings: dict Internals, Choosing Among collections, Designing Custom Mappings, and Production Operation
We systematize Python mappings (the correspondence of keys and values) — dict's behavior and internals, collections (defaultdict / Counter / OrderedDict / ChainMap) and types.MappingProxyType, custom mappings via collections.abc / UserDict, structural pattern matching, the __hash__/__eq__ contract, and type validation at the boundary. A production-quality practical guide that lifts you from 'using' dict to 'designing' it.
18 min read - PythonFastAPIセキュリティ認証・認可JWT
FastAPI Authentication & Authorization Production Guide: Protecting an API with the OAuth2 Password Flow × JWT (PyJWT) × Security Scopes
A guide to implementing production-quality authentication and authorization in FastAPI. Faithful to the latest official docs: pwdlib + Argon2 password hashing, JWT issuance/verification with PyJWT, the OAuth2 password flow's /token, get_current_user, and Security scopes, plus production hardening with short-lived tokens + refresh, CORS, rate limiting, HTTPS, and testing—all in real code.
23 min read - PythonFastAPIファイルアップロードストリーミングセキュリティ
FastAPI File Uploads, Forms, and Streaming Production Guide: Handling UploadFile / Form / StreamingResponse Safely and Idempotently Without Exhausting Memory
A guide to handling FastAPI file uploads (UploadFile/File), forms (Form), and streaming (StreamingResponse/FileResponse) at production quality. Explained with real code: the design judgment of going straight to object storage with a presigned URL, avoiding memory exhaustion with chunk reads, and size limits, MIME/magic-byte validation, path-traversal defense, malware scanning, and content-hash idempotency.
22 min read - PythonFastAPIアーキテクチャ設計依存性注入保守性
FastAPI Large-App Design: Building a 'Maintainable API' with APIRouter, Tiered Dependency Injection, and Project Structure
A design guide for keeping a large FastAPI API maintainable. Explained with real code, faithful to the official Bigger Applications: APIRouter, the recommended project structure, and relative imports, plus 4-tier DI (global/router/decorator/argument), router→service→repository layering, avoiding circular imports, API versioning, docs maintenance, and testing.
19 min read - PythonFastAPIバリデーション型安全Pydantic
FastAPI Input Validation Practical Guide: Type-Safe Query/Path/Body/Form with Annotated, Killing External Input at the Boundary
A guide to implementing the declaration and validation of query/path/body/form type-safely in FastAPI. Faithful to the latest official version: Annotated × Query/Path/Body constraints (min_length, pattern, ge/le, gt/lt), multiple values, alias, deprecated, query-parameter models and extra=forbid, Body(embed) and Field, special types like UUID/datetime, formatting 422, and testing boundary validation—all in real code.
21 min read - PythonFastAPISQLModelデータベースSQLAlchemy
A Production Guide to Putting a DB on FastAPI: CRUD, Multi-Model Boundaries, Relations, and Async Alembic with SQLModel (Pydantic × SQLAlchemy Integration)
A guide to handling relational DBs at production quality with SQLModel—the choice in FastAPI's official SQL tutorial. From table=True model definitions of SQLModel (which integrates Pydantic and SQLAlchemy under one author), yield session dependencies, CRUD, a design that guards input/public/update boundaries with multiple models, relations, to SQLite→PostgreSQL async, Alembic, connection pools, N+1 avoidance, transactions, and testing—all in real code.
23 min read - PythonFastAPIWebSocketリアルタイム可観測性
FastAPI WebSocket Production Guide: Building Bidirectional Realtime Comms with Connection Management, Auth, and Horizontal Scaling
A guide to implementing bidirectional realtime communication over WebSockets in FastAPI at production quality. Faithful to the latest official docs—@app.websocket, accept, receive/send, WebSocketDisconnect—plus connection management and broadcast with ConnectionManager, boundary validation with Pydantic, JWT auth via query/subprotocol, horizontal scaling with Redis Pub/Sub, and heartbeats, reconnection, and observability, all in real code.
23 min read - PythonAlembicSQLAlchemyPostgreSQLデータベース
Alembic practical guide: safely evolving a SQLAlchemy schema with zero downtime
Faithful to the Alembic official documentation, this concretely explains, from a production-operation viewpoint, wiring env.py's target_metadata, accurately discerning the changes autogenerate can and can't detect, stabilizing diffs with naming conventions, upgrade/downgrade operation, batch operations, and zero-downtime schema changes via expand/contract.
17 min read - PythonSQLAlchemyPostgreSQLORM型安全
SQLAlchemy 2.0 Practical Guide: Designing a Type-Safe ORM Data-Access Layer That Survives Production
Faithful to the SQLAlchemy 2.0 official docs, a thorough walkthrough — from type-safe model definitions with Mapped/mapped_column, the unified select() API, the Session's unit-of-work, loader strategies that crush N+1, asyncio support, connection-pool design, all the way to maximizing maintainability with the Repository pattern — explained from a production-operations viewpoint with concrete Python code.
17 min read