Contract-first design for FastAPI backends - define domain ports (Protocol), command/query dataclasses, views, DTOs with to_command/from_entity, error codes, event payloads, status machines and typed IDs BEFORE writing logic. Use whenever the user prepares interfaces, schemas, Pydantic models, dataclasses, "contracts", ports, types, enums, status values, event payloads, Redis stream messages, API shape, versioning, or asks what the request/response should look like before implementation.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Fastapi Contracts Types?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/amralhorimy-fastapi-contracts-types)
---
name: fastapi-contracts-types
description: Contract-first design for FastAPI backends - define domain ports (Protocol), command/query dataclasses, views, DTOs with to_command/from_entity, error codes, event payloads, status machines and typed IDs BEFORE writing logic. Use whenever the user prepares interfaces, schemas, Pydantic models, dataclasses, "contracts", ports, types, enums, status values, event payloads, Redis stream messages, API shape, versioning, or asks what the request/response should look like before implementation.
---
# Contracts and Types
A contract is anything two parts agree on. Write it, review it, freeze it, then build. In the hexagonal layout the
contracts have fixed homes:
| Contract | Where | Form |
|---|---|---|
| What a module needs from outside | `domain/ports.py` | `Protocol` classes owned by the **consumer** |
| Rules and invariants | `domain/entities.py`, `value_objects.py` | frozen `@dataclass(slots=True)` with `create(...)` factories |
| Business failures | `domain/errors.py` | `DomainError` subclasses: unique `code`, `default_detail` |
| Input of a use case | `application/commands/<x>.py` | `@dataclass(frozen=True, slots=True)` command |
| Output of a read | `application/queries/views.py` | frozen dataclasses (what is returned) |
| Where reads come from | `application/queries/readers.py` | `Protocol` readers (read side of ports) |
| HTTP shape | `adapters/http/schemas.py` | Pydantic DTOs: `to_command()` / `from_entity()` / `from_view()` |
| Facts others react to | `shared/events.py` | `EventType` StrEnum + frozen `InteractionEvent` with `version` |
| Queue messages | `platform/jobs/models.py` | job envelope, small payload (ids) |
## Rules
1. **Domain/application contain no Pydantic.** Validation of *business* rules (length, blank, limits) lives in the
entity (`Comment.create` raises `InvalidComment`); Pydantic DTOs only check wire shape. One rule, one place.
2. **Explicit conversion at the boundary.** DTO -> command via `to_command()`; never `**model_dump()`. Renaming an
API field must fail loudly, not silently change what the use case receives.
3. **Entities are immutable** (`frozen=True`); state changes return new instances or go through a port method that
is atomic in the store.
4. **Ports are narrow and named after intent** (`add_reply` returning an outcome enum, not generic `update`).
Document atomicity in the docstring ("atomically append unless missing or full").
5. **Each module has its own read model of others.** `comments.PostRef(post_id, author_id)` instead of importing
`posts.Post`. The bridge in `entrypoints/` fills it.
6. **Closed sets are `StrEnum`.** Event types, statuses, roles, outcomes. No free-text statuses.
7. **Bound everything**: content max length, max items per page (`Query(ge=1, le=100)`), max array size inside a
document (`MAX_REPLIES_PER_COMMENT`) - an unbounded embedded array eventually hits Mongo's 16 MB limit.
8. **Time is tz-aware UTC** from an injected `Clock`; IDs from an injected `IdGenerator`.
9. **Version every cross-process contract**: events carry `version`; cursors and snapshots carry a generation; jobs
carry `schema_version`. Consumers ignore unknown fields and reject unknown versions loudly.
10. **Cursors are opaque and signed** (HMAC with a secret) so clients cannot forge or tamper; invalid ones return
`INVALID_*_CURSOR` (422) and count as a security signal.
11. **Error codes are API**: `UPPER_SNAKE`, globally unique (a test enforces it), listed in `docs/errors.md`.
## Status machines
Declare allowed transitions in the domain, assert them in the entity, and persist with a conditional update
(`{"_id": id, "status": current}`); `matched_count == 0` means someone else moved it - treat as conflict/duplicate
delivery. That is your concurrency control; no locks.
```python
class MediaStatus(StrEnum):
PENDING = "pending"; UPLOADED = "uploaded"; FAILED = "failed"
_ALLOWED = {MediaStatus.PENDING: {MediaStatus.UPLOADED, MediaStatus.FAILED},
MediaStatus.UPLOADED: set(), MediaStatus.FAILED: {MediaStatus.PENDING}}
def can_move(cur: MediaStatus, new: MediaStatus) -> bool:
return new in _ALLOWED[cur]
```
## Port example (consumer-owned)
```python
class CommentRepository(Protocol):
async def add(self, comment: Comment) -> None: ...
async def get(self, comment_id: str) -> Comment | None: ...
async def add_reply(self, reply: Reply) -> ReplyOutcome:
"""Atomically append the reply unless the comment is missing or already full."""
...
class PostLookup(Protocol):
"""Owned by comments; fulfilled in the composition root from the posts module."""
async def find(self, post_id: str) -> PostRef | None:
"""The post if it is published, otherwise None."""
...
```
## Review questions before freezing
- Can a client branch on `code` alone for every failure it must handle?
- Which fields can race (two writers)? Is the update atomic or conditional?
- What bounds each list/array/string? What happens at the bound (error code, not silent truncation)?
- What does a consumer do with a newer `version`? A duplicate delivery? An out-of-order one?
- Does any contract leak a storage detail (ObjectId type, collection name, driver error)?