Category
Pydantic v2 実装ガイド(境界バリデーション/パフォーマンス/カスタム型/設定管理/v1→v2移行/エラー設計/技術選定/テスト/PydanticAI/LLM構造化出力)
Pydanticは「システム境界の外から来るデータを信頼しない」という規律を、型アノテーションで宣言的に表現するライブラリです。Rust製pydantic-coreを中核に、外部入力・設定・API・LLM出力をモデルとして検証し、信頼できるデータだけを内側へ通す。本クラスタは、BaseModel/Field/field_validator/model_validator/strictの基礎(境界バリデーション)から、TypeAdapter再利用・判別共用体・融合パースによるパフォーマンス最適化、Annotatedパターンで検証を再利用可能なドメイン型へ昇格させるカスタム型設計、pydantic-settingsによる型安全な設定・シークレット管理、v1→v2の安全な移行、ValidationErrorを使いやすく安全なAPIエラーに変える設計、dataclasses/TypedDict/attrs/msgspecとの技術選定、polyfactory/Hypothesisによるテスト戦略、そしてPydanticAIによる型安全なAIエージェントと生APIでのLLM構造化出力まで——型安全・セキュリティ・可観測性・回復性・テスト容易性を軸に、Pydantic v2公式ドキュメントに忠実な実コードで体系化します。FastAPI/SQLAlchemy/Alembicを含むPythonバックエンド全体の設計は『Pythonバックエンド』クラスタ、marshmallowとの比較・使い分けは『marshmallow』クラスタを参照してください。
10 articles in total
Foundational guide
Foundational guide (start here)
Pydantic v2 Practical Guide: Protect the System Boundary with Types and Pass Only Trustworthy Data
Faithful to the Pydantic v2 official documentation, we explain — from a boundary-validation practical perspective — declarative models with BaseModel/Field, field_validator/model_validator, model_dump, ConfigDict and strict mode, pydantic-settings, and v1 migration.
Related practical articles
- PythonPydanticPydanticAIAIエージェントLLM
PydanticAI practical guide: running a type-safe AI agent in production (structured output, tools, DI, observability)
Faithful to the PydanticAI official documentation, this explains in real code production-quality AI-agent design: how to make an Agent, type-safe structured output via output_type, dependency injection with @agent.tool/tool_plain and deps_type, self-repair with output_validator and ModelRetry, streaming with run_stream, Logfire observability, and durable execution with Temporal/DBOS.
14 min read - PythonPydantic型安全バリデーションデータモデリング
Pydantic advanced-types / custom-validators practical guide: make reusable 'domain types' with Annotated
Faithful to the Pydantic v2 official documentation, this explains in real code advanced validation that designs reusable domain types — the Annotated pattern of AfterValidator/BeforeValidator/WrapValidator/PlainValidator, the constraint types of StringConstraints and annotated_types, custom types via __get_pydantic_core_schema__, discriminated unions, RootModel, and generic models.
12 min read - PythonPydanticLLM構造化出力型安全
LLM structured output built with Pydantic: implementing JSON Schema generation, validation, and a self-healing loop with the raw API
Faithful to the Pydantic v2 official docs, with real code it explains provider-independent LLM structured output: LLM tool-schema generation with model_json_schema, designing to guide the model with Field(description/examples), validation with model_validate_json, a re-prompting self-healing loop using ValidationError.errors, and partial validation via TypeAdapter's experimental_allow_partial.
12 min read - PythonPydanticpydantic-settings設定管理セキュリティ
Practical pydantic-settings guide: realize 12-factor with type-safe configuration management and secret protection
Faithful to the pydantic-settings official documentation, with real code it explains production-durable configuration management: BaseSettings' typed config model, .env and env_nested_delimiter, secret protection with SecretStr/secrets_dir, the priority of settings, JSON/TOML/cloud (AWS/Azure/GCP) integration via settings_customise_sources, and CLI.
10 min read - PythonPydanticテスト型安全バリデーション
Pydantic testing strategy: thoroughly testing validation logic with polyfactory and Hypothesis
A practical guide to testing Pydantic v2 models and validation at production quality. With real code, from the viewpoints of testability and CI, it covers: contract tests with pytest.raises, automatic test-data generation with polyfactory, property-based testing with Hypothesis (the correct way after the plugin was dropped in v2), fast invalid fixtures with model_construct, and testing pydantic-settings.
9 min read - PythonPydantic型安全バリデーションアーキテクチャ設計
Complete Pydantic v1 → v2 migration guide: bump-pydantic, staged migration, and crushing 'silently breaking' changes
Faithful to the Pydantic official migration guide, with real code and a verification path it explains mechanical renames with bump-pydantic, staged migration in the pydantic.v1 namespace, the correspondence tables for methods/config/validators, and how to crush 'silently breaking' breaking changes such as the abolition of Optional's implicit default, changes in type coercion, and behavior changes in union/regex.
10 min read - PythonPydanticパフォーマンス型安全バリデーション
Pydantic v2 performance optimization: use the Rust core to the fullest and speed up hot-path validation
Faithful to the Pydantic v2 official documentation, this explains in real code the practical techniques to speed up the validation hot path — reusing TypeAdapter, model_validate_json's fused parsing, discriminated unions, concretizing type hints (list/TypedDict), avoiding wrap validators, model_construct, and defer_build/cache_strings.
13 min read - PythonPydanticバリデーション型安全FastAPI
Practical Pydantic error-handling guide: turn ValidationError into usable, safe API errors
Faithful to the Pydantic v2 official documentation, with real code from the viewpoints of UX, a11y, and security it explains the structure of ValidationError.errors() and ErrorDetails, the use of ValueError/AssertionError/PydanticCustomError, templated custom messages, localization keyed on error['type'], preventing confidentiality leaks with hide_input_in_errors, and converting to an API error envelope in FastAPI.
10 min read - PythonPydantic型安全データモデリングパフォーマンス
Pydantic vs dataclasses vs TypedDict vs attrs vs msgspec: a Python data-modeling selection guide (2026)
A fair comparison of Python's five data-modeling choices based on official information. dataclasses/TypedDict have no runtime validation, attrs is opt-in validation with no serialization, msgspec is speed-specialized, and Pydantic balances validation + schema + ecosystem. With axes of runtime validation, serialization, JSON Schema, performance, and ecosystem, plus a decision flow, it shows the optimal choice for your project.
10 min read