Dated API Versioning in FastAPI: Stripe-Style Backwards Compatibility

API Design

Give FastAPI dated contracts without duplicating domain logic. Add version selection, adapters, webhook pins, deprecation headers, and tests for upgrades.

TL;DR

  • Pin an API contract to the caller or accept an explicit version header. An omitted header should have a documented, stable default.
  • Validate the historical request shape at the edge, adapt it into current domain inputs, and project the resulting domain object into the caller's response contract.
  • Keep representations, webhook payloads, cursors, error contracts, and idempotent replays within the versioning plan.
  • Retire obsolete versions using documented timelines, migration guides, telemetry, and the standard Deprecation and Sunset headers.

Keep older clients working while the core changes

A billing API returns an integer amount in minor units. The next contract names it amount_minor. The new name makes the unit clear, but clients generated from the previous schema still expect amount. Two routes with copied billing logic might initially fix the response mismatch. Once authorization, rounding, and billing state transitions diverge across the copies, every release requires verification against multiple payment implementations.

Separate the representations from billing behavior. Older requests can be translated at the boundary and then sent through the same domain services as new requests. On the way out, explicitly build the fields each version promises. A new property in the database or internal model should not become a public property solely because a serializer included it.

Stripe's historical engineering description discusses versioned changes at the API boundary. Its current public versioning documentation describes a different release cadence with dated releases inside named major versions and breaking changes associated with major releases. It also documents account-level defaults and the Stripe-Version request header. The FastAPI example here uses those ideas and a smaller date-only allowlist. Its version names and adaptation rules belong to the example service. Stripe's engineering article on API versioning · Stripe public API versioning

Define version selection before adding adapters

Use an explicit version, account pin, and stable fallback

Pick a clear selection order. A common sequence is a permitted explicit header, then the authenticated integration's persisted pin, then a legacy default for accounts created before pinning was available. Set the latest version when creating new integrations if that is the onboarding policy. Persist version changes as deliberate actions so an unrelated deployment leaves existing clients on their established contract.

Use an allowlist of supported version identifiers. A date falling between two releases could be a typo, an unknown release from an SDK, or an attempted guess. Returning a machine-readable error prevents clients from thinking they verified compatibility when they actually reached another contract. Treat a retired date as a known historical value with a clear upgrade path. Clients and support tools benefit when unknown and retired versions have distinguishable error codes.

Resolve version after authenticating the caller, but independently of grants on the requested object. A version header is a representation choice and cannot change which tenant or action the caller may access. If you expose versions to beta integrations only, enforce that allowlist as integration metadata. Keep a stable, minimal error envelope for negotiation itself, since a failed negotiation has no selected contract.

Keep request changes distinct from response changes

Each version has a request decoder and a response presenter. Validate the old request as the old contract before translating it. Otherwise a modern required field may reject a request that old clients were entitled to omit. For responses, explicit projection protects clients relying on old nullability, field types, and status values. When one change has no reverse translation, represent it as an adapter in the direction you can preserve and consider a dedicated operation for behavior the old contract cannot express.

Compose migrations only when each step preserves the information needed by the next. Older request upgrade steps run from that version toward current semantics. Response downgrade steps start at current and walk in the opposite order. For a handful of supported contracts, direct adapters are often easier to read. A chain becomes attractive when many endpoints share a small set of recurring representation changes and test coverage can catch step-order interactions.

Implement a dated FastAPI contract

Define wire models and a version-independent command

This minimal demo exposes one quote endpoint under two contracts. It has no writes or account data. In a real authenticated service, pass the integration's stored pin into select_version and run the resulting command through the normal authorization and domain paths. The quote models use Pydantic 2 and accept integer quantities in both contracts.

from dataclasses import dataclass
from typing import Literal

from pydantic import BaseModel, ConfigDict, Field

Version = Literal["2025-07-01", "2026-07-01"]
LEGACY = "2025-07-01"
CURRENT = "2026-07-01"

class Quote2025(BaseModel):
    model_config = ConfigDict(extra="forbid")
    seats: int = Field(ge=1, le=100, strict=True)

class Quote2026(BaseModel):
    model_config = ConfigDict(extra="forbid")
    quantity: int = Field(ge=1, le=100, strict=True)

@dataclass(frozen=True)
class QuoteCommand:
    quantity: int

@dataclass(frozen=True)
class QuoteResult:
    amount_minor: int
    currency: str

def decode_quote(version: Version, body: object) -> QuoteCommand:
    if version == LEGACY:
        return QuoteCommand(Quote2025.model_validate(body).seats)
    return QuoteCommand(Quote2026.model_validate(body).quantity)

def calculate_quote(command: QuoteCommand) -> QuoteResult:
    return QuoteResult(amount_minor=1200 * command.quantity, currency="USD")

def present_quote(version: Version, result: QuoteResult) -> dict:
    if version == LEGACY:
        return {"amount": result.amount_minor, "currency": result.currency}
    return {"amount_minor": result.amount_minor, "currency": result.currency}

The unit price is a toy input, not a recommendation or current pricing. The important property is that both wire contracts share the same computation and return explicitly chosen fields. Pydantic's strict integer validation rejects a string representing an integer, a choice that must match each historical contract. Changing that policy today could break callers that were previously allowed to send numeric strings. Pydantic strict mode

Select the contract once on the FastAPI edge

from datetime import datetime, timezone
from email.utils import format_datetime
from typing import Annotated

from fastapi import Body, FastAPI, Header, HTTPException
from fastapi.responses import JSONResponse
from pydantic import ValidationError

app = FastAPI()
DEPRECATED_AT = datetime(2026, 10, 1, tzinfo=timezone.utc)
SUNSET_AT = datetime(2027, 7, 1, tzinfo=timezone.utc)

def select_version(header: str | None, pin: Version | None) -> Version:
    candidate = header if header is not None else (pin or LEGACY)
    if candidate == LEGACY:
        return LEGACY
    if candidate == CURRENT:
        return CURRENT
    raise HTTPException(400, detail={"code": "unsupported_api_version"})

def quote_headers(version: Version) -> dict[str, str]:
    headers = {"API-Version": version, "Cache-Control": "no-store"}
    if version == LEGACY:
        headers["Deprecation"] = f"@{int(DEPRECATED_AT.timestamp())}"
        headers["Sunset"] = format_datetime(SUNSET_AT, usegmt=True)
        headers["Link"] = '</docs/api/quote-migration>; rel="deprecation"'
    return headers

@app.post("/quote")
def post_quote(
    body: Annotated[object, Body()],
    versions: Annotated[list[str] | None, Header(alias="API-Version")] = None,
):
    if versions is not None and len(versions) != 1:
        raise HTTPException(400, detail={"code": "ambiguous_api_version"})
    version = select_version(versions[0] if versions else None, pin=None)
    headers = quote_headers(version)
    try:
        command = decode_quote(version, body)
    except ValidationError:
        raise HTTPException(422, detail={"code": "invalid_quote"}, headers=headers)

    return JSONResponse(present_quote(version, calculate_quote(command)), headers=headers)

FastAPI can receive duplicate header values as a list. Rejecting ambiguity lets gateways, SDKs, and HTTP integrations send one clear value. A proxy that coalesces duplicates into a comma-delimited header produces a value outside the allowlist, which is also rejected. Document what happens when intermediaries strip or rewrite the header and include a proxy-path test. The illustrative migration link points to a path your service would need to publish. FastAPI header parameters

Because the route manually selects the wire model and returns JSONResponse, the automatic schema cannot infer the two versioned contracts from this signature. Publish versioned OpenAPI documents with the appropriate request and response models, or describe the model alternatives explicitly and associate them with the header values in documentation. An SDK pinned to one version should generate types from that version's schema. FastAPI custom responses · FastAPI OpenAPI customization

Version caching, asynchronous payloads, and replays

If a cacheable public route changes representation based on the request's version header, include it in Vary and verify the CDN honors that distinction. Updating Vary alone cannot make an account-level default safely shareable across customers. Keep tenant-specific responses out of shared caches unless a deliberately designed cache key, authorization model, and cache policy cover all dimensions. The example explicitly disables caching. RFC 9111 cache key selection

Track event versions independently of request headers. A webhook can arrive long after a user's API request or after an integration upgrades. Store enough version information with the event to replay the correct contract. For existing Stripe integrations, check the event format and endpoint settings applicable to your event destination. Stripe's Event object includes version information for how its event data was rendered. Stripe Event object · Stripe webhook behavior

Define what happens when a previously accepted mutation is retried under another contract. Including the API version in the normalized idempotency fingerprint is one way to reject a cross-version retry. Accepting it may require persisting the original representation and explaining why a response carries an earlier version. Apply similar rules to cursor formats if a version changes sorting, default filters, or serialization. Idempotency keys and stored payment responses · Designing versioned cursor tokens

Deprecate a version only after clients can move

Offer a test environment and a migration guide with sample requests, response diffs, and known changes in defaults. Give consumers time to migrate webhook deliveries and generated clients separately. Count traffic by selected version and operation, with errors and adoption reported by integration where access policies permit. Measuring aggregate requests alone can hide a quiet integration whose quarterly workflow still relies on the older version.

Deprecation describes when a resource is or will be deprecated and uses a structured date of the form @<epoch-seconds>. Sunset gives the future date when the URI is expected to stop serving under the indicated policy and uses an HTTP-date. These headers apply to resources, so explain the version-specific scope at the migration link when an identical URI continues to serve another representation. Use a retirement date only after you have made an operational commitment. RFC 9745 Deprecation · RFC 8594 Sunset

Use a CI matrix that calls each supported contract with old and current request fixtures. Include validation failures, combinations of explicit and default version, and a representative webhook replay. Verify the old request still exercises current permission checks and current domain invariants. Make the old OpenAPI document an independently testable artifact until the version retires. For the database side of a staged cutover, see expand-and-contract migrations with Alembic.

When a versioned URL is the simpler option

URL versioning works well when clients, caches, policy gateways, and tooling need contract identity in the path. Routes can still call a shared service and common authorization code. Header negotiation is useful when resource URIs are long-lived and clients can reliably pin one representation, at the cost of more explicit cache, proxy, and SDK configuration. If the old operation has materially different semantics or access rules, a separate route or resource can be easier to document than a long adapter chain.

Frequently asked questions

Should a FastAPI server default to the latest API version?

Give each new integration an intentional default and persist that selection. Existing integrations should retain their selected contract until they upgrade. If an old client never sent a version, document a stable fallback and measure its use. A deployment that adds a version should leave earlier callers' defaults intact.

Should request and response transformers use the same mapping?

Some changes, such as renaming a field, can share a simple mapping. Other changes affect defaults, validation, or allowed transitions and only translate in one direction. Make each boundary explicit and test it separately. Domain services can still use a single current command and result model.

What versions should be included in API contract tests?

Test every active contract with representative successful requests and failures, including explicit and implicit version selection. Cover at least one replay of a pinned webhook or idempotent request when those features exist. Also check that unsupported versions fail predictably and that old representations continue to enforce current authorization.

What is the difference between Deprecation and Sunset?

Deprecation advises clients that the applicable resource is or will be deprecated. Sunset communicates when the resource is expected to become unavailable under the stated policy. Link to the migration instructions and explain which version is affected when multiple contracts share a URI.

Further reading

Planning to evolve an API with long-lived integrations? Talk to Dumb Potato about version selection, compatibility testing, and migration.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with web applications

Discuss your project