# Writing an API That Doesn't Break Your Consumers

An API is a contract. The moment a consumer depends on it, every change you make to it is either safe or a breaking change — and the difference matters more than most engineers think about when they're moving fast.

Breaking changes don't just cause outages. They erode trust. A consumer team that gets burned by an undocumented breaking change starts building defensive wrappers and avoiding upgrades. The cost compounds. The right habits at the start are much cheaper than recovering the trust later.

---

## Breaking vs Non-Breaking: The Taxonomy

The most useful thing you can internalise is a clear mental model of which changes are safe and which aren't.

**Non-breaking (safe to ship at any time):**

- Adding a new optional field to a response
- Adding a new optional query parameter
- Adding a new endpoint
- Expanding an enum with new values (with caveats — see below)
- Relaxing a validation constraint (accepting more inputs than before)

**Breaking (require a versioning strategy):**

- Removing a field from a response
- Renaming a field
- Changing a field's type (string → integer, even if the values are compatible)
- Making an optional field required
- Changing the meaning of an existing field
- Removing an endpoint
- Changing an endpoint's URL structure
- Tightening a validation constraint (rejecting inputs that were previously accepted)
- Changing error response shapes

The enum caveat: adding a new value is technically non-breaking on the server side, but it breaks consumers that use exhaustive matching (a `switch` statement that throws on unexpected values). Document new enum values clearly and give consumers time to handle them.

---

## Versioning Strategy

There are three common approaches. Pick one and be consistent.

**URL versioning** (`/v1/orders`, `/v2/orders`) is the most visible and easiest to route. Consumers know exactly which version they're on. Old versions can run alongside new ones. The downside is URL proliferation and the temptation to create a v2 for every minor change.

**Header versioning** (`Accept: application/vnd.api.v2+json`) keeps URLs clean but makes the version implicit. Tooling support is weaker and it's harder for consumers to see at a glance which version a request targets.

**Query parameter versioning** (`/orders?version=2`) is the most flexible but the least consistent — easy to forget, easy to misconfigure.

URL versioning is the pragmatic default for most backend APIs. It's explicit, cacheable, and requires no special client configuration.

```python
# FastAPI — versioned routers
from fastapi import APIRouter

v1_router = APIRouter(prefix="/v1")
v2_router = APIRouter(prefix="/v2")

@v1_router.get("/orders/{order_id}")
async def get_order_v1(order_id: str) -> OrderResponseV1:
    ...

@v2_router.get("/orders/{order_id}")
async def get_order_v2(order_id: str) -> OrderResponseV2:
    ...

app.include_router(v1_router)
app.include_router(v2_router)
```

---

## Pydantic for Explicit Contracts

Response models double as documentation and as a forcing function. When you define a Pydantic response model, you're making an explicit commitment about what the contract is.

```python
from pydantic import BaseModel
from datetime import datetime
from enum import Enum

class OrderStatus(str, Enum):
    pending = "pending"
    confirmed = "confirmed"
    shipped = "shipped"
    delivered = "delivered"

class OrderResponseV1(BaseModel):
    order_id: str
    status: OrderStatus
    created_at: datetime
    total_amount: float

    model_config = {"extra": "ignore"}  # internal fields don't leak into the response
```

The `extra = "ignore"` config is important: it means adding new fields to your internal data model doesn't automatically expose them in the response. The response is explicit — only the fields you declared.

When you need to add a field, add it as optional with a default:

```python
class OrderResponseV1(BaseModel):
    order_id: str
    status: OrderStatus
    created_at: datetime
    total_amount: float
    # Added in v1.2 — optional, consumers that don't use it are unaffected
    estimated_delivery: datetime | None = None
```

When you need to change a field's shape — rename it, change its type, restructure it — that's a new version:

```python
class OrderResponseV2(BaseModel):
    order_id: str
    status: OrderStatus
    created_at: datetime
    # v2: amount broken into subtotal + tax, total removed
    subtotal: float
    tax: float
    currency: str  # also added in v2
    estimated_delivery: datetime | None = None
```

---

## Deprecation Over Deletion

Never delete without deprecating first. The deprecation window gives consumers time to migrate.

```python
from fastapi import APIRouter, Response

v1_router = APIRouter(prefix="/v1")

@v1_router.get("/orders/{order_id}", deprecated=True)
async def get_order_v1(order_id: str, response: Response) -> OrderResponseV1:
    # Signal to consumers via response header
    response.headers["Deprecation"] = "true"
    response.headers["Sunset"] = "Sat, 01 Aug 2026 00:00:00 GMT"
    response.headers["Link"] = '</v2/orders/{order_id}>; rel="successor-version"'
    ...
```

A reasonable deprecation timeline:

- **Internal consumers** (services you own): 4–6 weeks
- **External consumers** (third parties or clients): 6–12 months minimum, with advance notice via email or developer changelog
- **Never**: no deletion without a deprecation period, even if you believe no one is using the endpoint

Log requests to deprecated endpoints so you can see usage dropping off before you remove them.

---

## Changelog and Communication

A contract only works if consumers know about changes. Maintain a `CHANGELOG.md` or a developer-facing changelog that distinguishes breaking changes from additions:

```markdown
## v2.0.0 — 2025-10-01 [BREAKING]

### Breaking changes
- `GET /v1/orders/{id}`: `total_amount` field removed; replaced by `subtotal` + `tax` + `currency`
- `GET /v1/orders/{id}`: deprecated; sunset date 2026-08-01

### Added
- `GET /v2/orders/{id}`: new endpoint with restructured amount fields
- `currency` field (ISO 4217 code) on all order responses
```

The discipline of maintaining a changelog also forces you to think carefully before shipping a breaking change — if you're about to write "\[BREAKING\]" in the changelog, it prompts you to ask whether the change is really necessary or whether it can be done in a backward-compatible way.

---

## The One Rule

When in doubt: add, don't change. A new optional field is almost always backward-compatible. Changing or removing an existing field almost always isn't. If the shape needs to change fundamentally, that's what version numbers are for.

Consumers trust APIs that don't surprise them. That trust is earned by the unglamorous discipline of treating every response field as a commitment from the moment anyone depends on it.
