Skip to content
Systems··7 min read·1309 words (~200 wpm)·en

Part 1: The API Contract Suite — Stop Guessing What the Backend Returns

Stop Guessing What the Backend Returns: The API Contract Suite

Part 1 of the series "Beyond the Code: The Standards That Power Modern Software"

Reading Time: ~8 minutes | Focus: OpenAPI 3.1, JSON Schema, RFC 9457 Problem Details, JSON:API


😱 The Friday 4:55 PM Horror Story

It’s late Friday afternoon. Your backend team merges a quick PR to "clean up database fields." They renamed a database column from user_id to userId to match JavaScript camelCase conventions. The backend automated tests all passed. The service deployed smoothly.

Twenty minutes later, customer support gets flooded with frantic calls: "The mobile app crashes the second I tap my profile!"

The frontend and mobile teams had no idea the field changed. Their code was expecting data.user_id. When it received undefined, an unhandled TypeError crashed the app on iOS and Android.

Worse, reverting a mobile app release isn’t instant—it requires an emergency App Store submission that can take 24 to 48 hours for Apple review.

Every experienced software engineer has lived through a version of this disaster. The tragedy is that this crash was 100% preventable. It didn't happen because of poor coding skills; it happened because the team treated their API as an ad-hoc handshake instead of a legally binding, machine-readable contract.

In this article, we’ll look at the four open standards that eliminate this entire category of bugs forever.


📜 Standard 1: OpenAPI 3.1 (OAS) — The Universal API Blueprint

Official Website: https://www.openapis.org
Governing Body: OpenAPI Initiative (Linux Foundation)

What it is

The OpenAPI Specification (formerly known as Swagger) is the vendor-neutral standard for describing RESTful HTTP APIs in machine-readable YAML or JSON.

Instead of writing outdated Confluence wikis or PDF documentation that drifts away from reality after two weeks, OpenAPI makes your contract the Single Source of Truth.

                   ┌──────────────────────────────┐
                   │    openapi.yaml Contract     │
                   └──────────────┬───────────────┘
          ┌───────────────────────┼───────────────────────┐
          ▼                       ▼                       ▼
┌──────────────────┐    ┌──────────────────┐    ┌──────────────────┐
│   Swagger UI     │    │   Prism Mock     │    │ Auto-Generated   │
│   (Live Docs)    │    │   (Instant Fake  │    │ TypeScript &     │
│                  │    │    API Server)   │    │ Kotlin Types     │
└──────────────────┘    └──────────────────┘    └──────────────────┘

The Game Changer: Contract-First Development

Instead of having backend engineers write code first and "document it later" (which never happens), high-performing teams practice Contract-First design:

  1. Frontend and backend engineers collaborate on an openapi.yaml file during sprint planning:
openapi: 3.1.0
info:
  title: User Profile Service
  version: 1.0.0
paths:
  /api/v1/users/{id}:
    get:
      summary: Fetch user profile
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Successful profile response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserResponse'
components:
  schemas:
    UserResponse:
      type: object
      required: [id, email, tier]
      properties:
        id: { type: string, format: uuid }
        email: { type: string, format: email }
        tier: { type: string, enum: [free, pro, enterprise] }
  1. The frontend team runs a mock server (npx prism mock openapi.yaml) and starts coding immediately with realistic mock data—before backend implementation even begins.
  2. A code generator (like openapi-typescript or orval) automatically generates TypeScript interfaces from the spec:
// Auto-generated from openapi.yaml — NOT written by hand!
export interface UserResponse {
  id: string; // UUID
  email: string;
  tier: "free" | "pro" | "enterprise";
}

If the backend ever renames a field in the contract, the frontend build fails immediately at compile time before any code ever touches a staging or production server.


🛡️ Standard 2: JSON Schema (Draft 2020-12) — The Data Gatekeeper

Official Website: https://json-schema.org
Governing Body: IETF Draft / Open Community

What it is

JSON is naturally flexible, but flexibility in production is dangerous. JSON Schema is a declarative standard for annotating and validating JSON data structures.

Since OpenAPI 3.1, OpenAPI is 100% dialect-compatible with JSON Schema (Draft 2020-12). You define your data constraints once, and they work everywhere:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["username", "email", "age"],
  "properties": {
    "username": { "type": "string", "minLength": 3, "maxLength": 20 },
    "email": { "type": "string", "format": "email" },
    "age": { "type": "integer", "minimum": 18 }
  },
  "additionalProperties": false
}

Why Senior Engineers Put This at the Gateway

High-performance validators like Ajv compile these schemas into native, optimized JavaScript just-in-time (JIT) functions.

By placing JSON Schema validation at your API Gateway or Express/Fastify middleware layer, invalid requests (like malformed emails or malicious extra fields) are rejected in 0.2 milliseconds before they consume database connections or controller compute.


🚨 Standard 3: RFC 9457 — Standardizing API Errors

Official Specification: RFC 9457 (Problem Details for HTTP APIs)
Governing Body: IETF

The Problem

Have you ever consumed an API where three different endpoints returned three completely different error formats?

// Service A returns:
{ "error": "Insufficient funds" }

// Service B returns:
{ "message": "Transaction failed", "err_code": 4001 }

// Service C returns:
{ "errors": ["Balance cannot be negative"] }

Your frontend client is forced to write brittle spaghetti code full of if (res.error) ... else if (res.message) ... just to display an alert to the user.

The Standard: application/problem+json

RFC 9457 (which obsoletes RFC 7807) standardizes error reporting across the entire web into a consistent MIME type: application/problem+json.

HTTP/1.1 403 Forbidden
Content-Type: application/problem+json

{
  "type": "https://api.mystore.com/errors/insufficient-credit",
  "title": "You do not have enough credit.",
  "status": 403,
  "detail": "Your current balance is $30.00, but checkout requires $50.00.",
  "instance": "/orders/ord_98741/checkout",
  "current_balance": 30.00
}

The 5 Standard Keys:

  1. type (URI): A link identifying the problem type and documentation.
  2. title: Short, human-readable summary (consistent across all occurrences).
  3. status (int): The HTTP status code.
  4. detail: Human-readable explanation specific to this specific occurrence.
  5. instance (URI): Identifies the exact resource or transaction that failed.

With RFC 9457, your client applications only need one single error-handling interceptor to handle every error gracefully across all microservices.


📦 Standard 4: JSON:API — Solving the $N+1$ Query Problem in REST

Official Website: https://jsonapi.org
Governing Body: Open Community

Many teams adopt GraphQL solely to solve the "over-fetching and under-fetching" problem of REST. But you might not need the operational complexity of a GraphQL server if you use the JSON:API standard.

How JSON:API Solves REST Inefficiencies:

  1. Compound Documents (?include=): Fetch an article and all its related comments and authors in one single HTTP request:
    GET /articles/1?include=author,comments
    
    The response returns the primary resource plus the related resources in a single, deduplicated included array:
    {
      "data": {
        "type": "articles",
        "id": "1",
        "attributes": { "title": "Understanding Modern API Standards" },
        "relationships": {
          "author": { "data": { "type": "people", "id": "9" } }
        }
      },
      "included": [
        {
          "type": "people",
          "id": "9",
          "attributes": { "name": "Alice Developer", "twitter": "@alice_dev" }
        }
      ]
    }
    
  2. Sparse Fieldsets (?fields=): Tell the server to return only the specific fields your mobile UI needs to save cellular bandwidth:
    GET /users?fields[users]=name,avatarUrl
    
  3. Standard Pagination & Sorting: Eliminates debates over whether to use limit/offset or page/size:
    GET /articles?page[number]=2&page[size]=20&sort=-created_at
    

⚖️ Senior Engineer Rules of Thumb

Scenario Recommendation
New REST API service starting today Mandatory: Write an OpenAPI 3.1 spec and enforce RFC 9457 for errors.
Frontend & Backend in separate teams Adopt Contract-First development; generate types automatically with CI validation.
Internal quick script / POC Keep it simple; code-first generation is acceptable.
Overwhelmed by multiple error formats Implement an RFC 9457 middleware in your framework; it takes 30 minutes and pays dividends forever.

🧠 Key Takeaways

  1. Code is temporary; contracts are permanent. Never let database column names dictate your public API contract.
  2. Auto-generate your types. If developers are manually typing TypeScript interfaces to match backend JSON responses, you are one typo away from an outage.
  3. Standardize your errors. Adopting application/problem+json (RFC 9457) turns chaotic error parsing into a solved problem.

Enjoyed this article? This is Part 1 of the 8-part series "Beyond the Code: The Standards That Power Modern Software."

In Part 2, we will dive into The Modern Transport & Real-Time Web, comparing HTTP/3 (QUIC), WebSockets vs. SSE, and why gRPC dominates internal microservices. Follow to catch it as soon as it drops!

Esc
Pages & Surfaces
Field Notes & Articles (0)
No articles match ""
↑↓Navigate↵Select
Part 1: The API Contract Suite — Stop Guessing What the Backend Returns | Top Kananek