Unit 1 of 8 · about 4 hours · explain, implement

Typed interfaces, runtime validation and configuration

Every later service in this section stands on this boundary. Untyped inputs and untyped configuration turn typos into silent corruption. Typed contracts with explicit validation move those failures to the edge where they are loud.

You'll be able to

  • Compare nominal and structural typing, generics with bounded TypeVars and variance, and justify where dynamic values are quarantined at the boundary.
  • Define a typed public API with protocols and generics that keeps persistence and transport types out of domain logic.
  • Build validated input models and typed settings with explicit unknown-field and precedence behavior, and diagnose one silent-corruption path.

Covers

Nominal and structural typing, generics and protocolsRuntime validation and trusted versus untrusted boundariesTyped configuration, precedence, secrets and unknown fields
1

Read

In this order, only the parts listed

0 of 7 done

  1. Pydantic Models: basic usage, data conversion and extra dataOfficial docs typed-service build path

    Basic model usage including Model methods and properties (model_validate, model_dump); Data conversion; Extra data (ignore, forbid, allow); Validating data, including Creating models without validation

  2. Pydantic ValidatorsOfficial docs typed-service build path

    Field validators (after, before, plain and wrap, in the annotated and decorator patterns); Model validators; Raising validation errors

  3. Pydantic Fields: constraints and strict fieldsOfficial docs typed-service build path

    Field constraints; Strict fields

  4. Pydantic Strict ModeOfficial docs typed-service build path

    As a validation parameter; At the field level, including the Strict() metadata class; As a configuration value

  5. Pydantic Settings Management: names, dotenv and priorityOfficial docs typed-service build path

    Usage (env_prefix, validation_alias); Environment variable names with Unknown environment variables; Parsing environment variable values; Dotenv (.env) support, including undefined dotenv keys raising under the default extra forbid; Field value priority

  6. Interfaces and ProtocolsAlgoMaster Python - interfaces, generics and data files

    Structural vs Nominal Typing; Defining a Protocol; @runtime_checkable: Adding isinstance Support; Generic Protocols; Dependency Injection Contracts

  7. Generic TypesAlgoMaster Python - interfaces, generics and data files

    TypeVar Basics; Generic Classes with Generic[T]; Bounded TypeVars; Variance: Why list[Product] Isn't list[Item]; Putting It Together: A Generic Service Layer

2

Focus on

  • Protocol defines a static duck-typing boundary. Nominal inheritance is checked by name, structural compatibility by shape. Use Protocol for dependencies the domain calls but does not own.
  • Validate at the trust boundary with model_validate and model_validate_json. model_construct skips validation and is only for already-trusted data.
  • The default extra behavior ignores unknown fields, which silently drops data. Boundary models that must reject drift use extra forbid, and strict mode rejects coercions such as '3' to 3.
  • Settings precedence is init kwargs, then environment, then dotenv, then defaults. Unknown environment names are ignored, so a misspelled variable silently keeps the default, but an undefined key in the dotenv file raises under the default extra forbid.
Common mistakes · 3
  • runtime_checkable isinstance checks method presence only, not signatures. A sender with the wrong signature passes isinstance and fails later; keep static checking as the real gate.
  • parse_obj, .dict, .json and @validator still run, so old tutorials look current. In Pydantic 2.14 they are deprecated shims whose DeprecationWarning stays hidden outside __main__, and some v1 calls now fail: .json(indent=2) raises TypeError. Use model_validate, model_dump, model_dump_json and field_validator.
  • Expecting extra forbid to catch a misspelled environment variable. Unmatched environment names never reach validation (only undefined dotenv keys raise), so test precedence with a wrong-name variable and watch the default survive.
3

Try it yourself

Closed-book, before checking anything

Closed-book, define a Protocol plus a generic service, a boundary model with extra forbid and a StrictInt field, and settings with a prefix. Show that model_validate coerces '3' in lax mode but strict rejects it with int_type, that an extra field raises extra_forbidden, and that init beats env beats default.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.A field x: int receives '123' in lax mode and under strict True. What happens in each?Answer

    Lax coerces to 123. Strict raises with type int_type. Verified on Pydantic 2.14 with CPython 3.14.

  2. 2.A payload carries an extra key y. How do default and extra forbid models differ?Answer

    Default ignores y and dumps without it. Forbid raises extra_forbidden at ('y',).

  3. 3.What are the v2 replacements for parse_obj and .dict, and why do the old names matter?Answer

    model_validate and model_dump. The old names still run as deprecated shims that forward to the v2 methods, so legacy code looks current until v3 removes them, and some v1 signatures already fail: .json(indent=2) raises TypeError. Verified on Pydantic 2.14.1.

  4. 4.Init passes port 9000, env sets 8080, default is 8000. Which wins, and what if the env name is misspelled?Answer

    Init wins with 9000. A misspelled name is ignored and the default 8000 applies. Verified with pydantic-settings on CPython 3.14.

5

Practice

  • AlgoMaster Exercise: Interfaces and Protocols

    Exercises 1 to 5 on the exercise page, with the lesson sections Structural vs Nominal Typing and Dependency Injection Contracts

    Complete the set for recall, then add a self-built check: a strict boundary model with forbid-extra rejects extra fields and wrong types, and settings precedence init beats env beats default holds.

You're done when

You define a Protocol plus generic service without transport imports, validate good, malformed and extra-field payloads with v2 calls only, and demonstrate init beats env beats default with a misspelled variable keeping the default.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 9 more in the section
  • Official docs typed-service build pathPython typing, Pydantic, FastAPI and PostgreSQL · primary

    Build one record service in this order: structural protocols and generics; Pydantic models, validators, strict mode, serialization and settings; FastAPI request bodies, dependencies, errors and tests; then PostgreSQL transactions and EXPLAIN. Replay valid, malformed, duplicate and previous-schema requests through CLI and HTTP.

  • AlgoMaster Python - interfaces, generics and data filesAlgoMaster · support

    Use Interfaces and Protocols plus Generic Types for structural typing, and Working with JSON plus Working with CSV for JSONL, error handling, newline and DictReader behavior. Lesson quizzes check recall; implementation is verified with your own scripts.

Also in this section

  • AlgoMaster SQL - selected routeAlgoMaster · required

    Study SQL Foundations, Querying Data, Joins, Subqueries and CTEs, Window Functions, DDL, DML and Views, Performance Optimization, Transactions and Concurrency, and Data Modeling. Stop when the service queries and transaction tests pass.

  • PostgreSQL transactions and EXPLAINPostgreSQL · required

    Use the transaction tutorial and EXPLAIN guide to demonstrate commit, rollback, one isolation anomaly or prevented anomaly, and a measured plan improvement on the database actually used.

  • FastAPI tutorialFastAPI · support

    Use Request Body, Dependencies, Handling Errors and Testing to expose the same service layer through HTTP. Keep framework models outside the domain core and preserve the same error semantics as the CLI.

  • AlgoMaster Low-Level Design - one rehearsalAlgoMaster · support

    Use one fitting design prompt to rehearse interface contracts, dependency direction and failure ownership. Treat the review as feedback, then verify behavior with your own tests.

  • Stas' Python Cookbook - data and interfacesStas Bekman · support

    Use Serialization and Deserialization plus Environment and Arguments for focused implementation help. Compare JSON, JSONL, CSV and compressed data, and never use pickle for untrusted interchange.

  • SQLAlchemy 2.1 documentation - select, Session and eager loadingSQLAlchemy · reference

    Use the select() tutorial for 2.x query style, Session basics for the transaction boundary and identity map, and relationship loading for lazy versus selectinload versus joinedload plus raiseload. Use select() style and Session.execute or Session.scalars only, never the legacy Query API.

  • Alembic tutorial - migration scripts and downgradingSQLAlchemy · support

    Use Create a Migration Script, Running our First and Second Migration, Getting Information and Downgrading to run a paired upgrade and downgrade round trip on a scratch database.

  • PyArrow Parquet read and write docsApache Arrow · support

    Use Reading and Writing Single Files plus Table from_pydict and from_pylist to convert normalized records to Parquet and test types, nulls, column projection and schema.

  • Stripe idempotent requestsStripe · support

    Use the Idempotency-Key header contract, stored-response replay, parameter-mismatch errors and POST-only scope to implement keyed replay for one endpoint.