Back to the academy

Polyglot contracts between TypeScript and Python without breaking production

How to keep a Node.js/TypeScript backend and a Python/FastAPI engine in sync with shared schemas (contracts/ + Pydantic) validated by automated tests.

Advanced · TypeScript · Python · Pydantic · FastAPI

A single source of truth for the schema

When a Node.js backend consumes a Python engine, the JSON that crosses the boundary is a contract. If each side defines its own types, sooner or later they drift apart, and the failure shows up in production as an untraceable `undefined`. In Elevation, the `contracts/` folder holds the shared TypeScript types: they are copied into the backend before every build, type-check or test run, and the Python engine mirrors them with Pydantic models.

❌ Antipattern

// backend: types written from memory
interface Signal {
  symbol: string;
  score: number; // Python renamed it to "confidence"
}

✅ Stoic pattern

// contracts/signals.ts (simplified): the one schema both sides follow
export interface SignalContract {
  symbol: string;
  confidence: number;
  direction: 'BULLISH' | 'BEARISH';
}

Key takeaways

  • JSON that crosses languages is a public API: treat it as a versioned contract.
  • One contracts folder; every other side copies or mirrors it, never reinvents it.
  • Edit the contract, never the generated copy.

The Pydantic mirror on the Python side

The Python engine declares the same contract with Pydantic models: it validates every signal before sending it and rejects, at the source, a field with the wrong type or a value outside the enum. A validation error in the sender is far cheaper than corrupt data discovered hours later in the consumer's database.

❌ Antipattern

payload = {
    "symbol": symbol,
    "confidence": str(score),  # a string where a number is expected
    "direction": "LONG",       # not in the enum
}
requests.post(url, json=payload)

✅ Stoic pattern

from typing import Literal
from pydantic import BaseModel, Field

class SignalContract(BaseModel):
    symbol: str
    confidence: float = Field(ge=0, le=100)
    direction: Literal["BULLISH", "BEARISH"]

payload = SignalContract(symbol=symbol, confidence=score, direction=direction)
requests.post(url, json=payload.model_dump())

Key takeaways

  • Validate in the sender: invalid data must not leave the process that created it.
  • `Literal` and `Field` turn business rules into explicit errors.
  • The Pydantic model documents the contract in Python just as the TypeScript type does on the other side.

A test that fails when both sides drift apart

Types do not travel between languages, so consistency is guaranteed by a test. In Elevation, a sync test compares the TypeScript contract with the Pydantic models and fails if a field exists on one side but not on the other. A schema change becomes atomic: either both sides are updated in the same change, or the pipeline does not pass.

Example

def test_contract_fields_match():
    ts_fields = interface_fields("contracts/signals.ts", "SignalContract")
    py_fields = set(SignalContract.model_fields)
    assert ts_fields == py_fields, f"out of sync: {ts_fields ^ py_fields}"

Key takeaways

  • If types cannot cross the language boundary, let a test cross it.
  • The sync test makes a schema change atomic: both sides or neither.
  • The pipeline is the reviewer that never forgets to update the other side.