REST API with Pydantic Validation in FastAPI
The work-orders API in Python: Pydantic models, dependency-injected sessions and the shared acceptance suite.
- Runs out of the box: yes
- Tests: yes
- CI: yes
- Docs: yes
- Used in production: no
Purpose#
The Python implementation of the shared "work orders" API. Pydantic models describe requests and responses, a dependency provides one database session per request, and exception handlers translate domain errors into the common error body.
Compare it with the Node.js and C# versions to see how each language expresses validation and error mapping for the same contract.
What you will learn#
- Model requests and responses with Pydantic and let FastAPI generate the OpenAPI document
- Provide a transaction-scoped database session through dependency injection
- Map domain exceptions to the shared error body in one place
Technologies & features#
- Technologies
- PythonFastAPISQLAlchemyPostgreSQL
- Features
- REST API Design
- Topics
- Application Architectureprimary
Lessons learned#
- Worked
Dependency-injected sessions made tests simple: the suite swaps in a transaction that rolls back after each test.
- Note
Response models must be set explicitly, otherwise internal fields leak into responses. A contract test now diffs the schema against the shared description.
Try it#
git clone https://git.example.internal/mission-software/rest-work-orders-py.git
cd rest-work-orders-py
uv sync
uv run fastapi dev app/main.py # http://localhost:8000
uv run pytest tests/contractCommands come from the owner’s README. Credentials are never stored here.


