karawaci.kode

2026-09-07 · 11 min

OpenAPI Spec-First Development Workflow in 2026: From YAML to Production Without Drift

Somewhere between Bumi Serpong Damai’s tech offices and the average startup’s CI pipeline, there’s a graveyard of Swagger files that nobody believes anymore. The spec says the endpoint returns { user_id, name, email }. The actual response has userId, fullName, and three undocumented fields. Nobody updated the spec after the last refactor. Now it’s decorative.

OpenAPI spec-first development solves this at the architectural level, not with more documentation discipline.

The premise is simple but requires real commitment: the OpenAPI YAML file is written before the implementation, and every other artifact — TypeScript types, server stubs, mock servers, contract tests — is generated from it. The spec is not documentation. It is the source of truth that code must conform to.

This article walks through a complete workflow that actually holds together in production.

Why “spec-first” fails when you half-commit

Most teams that try spec-first end up with spec-after. The backend engineer writes the handler, then writes the spec to match what they built. That’s code-first with extra steps.

Real spec-first means the spec constrains the implementation, not the other way. That requires two things: the spec exists before the code, and something enforces that the code stays aligned with the spec over time. Without enforcement, you’re just writing YAML before YAML becomes wrong.

The workflow below focuses on the enforcement half — that’s where most tutorials stop short.

Directory structure for a monorepo

Keep the spec outside any individual service directory. It belongs at the top level, shared:

project/
├── openapi/
│   ├── openapi.yaml           # primary spec
│   └── schemas/               # $ref targets — one file per domain entity
│       ├── user.yaml
│       ├── order.yaml
│       └── errors.yaml
├── apps/
│   ├── api/                   # backend (Node, Go, whatever)
│   └── web/                   # frontend consumer
└── package.json               # monorepo root scripts

One spec file, two consumers, zero ambiguity about which version is authoritative.

Writing the spec: decisions that matter early

The OpenAPI YAML is where API design happens. Field names, required vs optional, error shapes — all of this is visible and reviewable before a single handler is written.

A realistic order endpoint:

# openapi/openapi.yaml
openapi: "3.1.0"
info:
  title: Order API
  version: "2.1.0"

paths:
  /orders:
    post:
      operationId: createOrder
      summary: Place a new order
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateOrderRequest"
      responses:
        "201":
          description: Order accepted
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Order"
        "422":
          description: Validation failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ValidationError"
        "409":
          description: Duplicate order (idempotency key reused)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ConflictError"

components:
  schemas:
    CreateOrderRequest:
      type: object
      required: [idempotencyKey, items, shippingAddressId]
      properties:
        idempotencyKey:
          type: string
          format: uuid
          description: Client-generated key; resubmitting the same key returns the original order
        items:
          type: array
          minItems: 1
          items:
            $ref: "#/components/schemas/OrderItem"
        shippingAddressId:
          type: string
          format: uuid

    OrderItem:
      type: object
      required: [productId, quantity]
      properties:
        productId:
          type: string
          format: uuid
        quantity:
          type: integer
          minimum: 1
          maximum: 100

    Order:
      type: object
      required: [id, status, createdAt]
      properties:
        id:
          type: string
          format: uuid
        status:
          type: string
          enum: [PENDING, CONFIRMED, SHIPPED, CANCELLED]
        createdAt:
          type: string
          format: date-time
        estimatedDelivery:
          type: ["string", "null"]   # nullable in OpenAPI 3.1 syntax
          format: date

    ValidationError:
      type: object
      required: [code, message, fields]
      properties:
        code:
          type: string
          enum: [VALIDATION_FAILED]
        message:
          type: string
        fields:
          type: array
          items:
            type: object
            required: [field, message]
            properties:
              field:
                type: string
              message:
                type: string

    ConflictError:
      type: object
      required: [code, existingOrderId]
      properties:
        code:
          type: string
          enum: [DUPLICATE_ORDER]
        existingOrderId:
          type: string
          format: uuid

A few deliberate choices here worth noticing: the idempotency key is in the request body rather than a header (debatable, but explicit), the 409 response has its own schema with existingOrderId so the client knows what to do with it, and estimatedDelivery uses the OpenAPI 3.1 type: ["string", "null"] union rather than the deprecated nullable: true. These are design decisions, not implementation details.

Generating the TypeScript client

With hey-api/openapi-ts:

npm install -D @hey-api/openapi-ts @hey-api/client-fetch
// openapi-ts.config.ts
import { defineConfig } from "@hey-api/openapi-ts";

export default defineConfig({
  input: "./openapi/openapi.yaml",
  output: {
    path: "./apps/web/src/lib/api",
    format: "prettier",
  },
  plugins: [
    "@hey-api/client-fetch",
    {
      name: "@hey-api/transformers",
      dates: true,  // converts ISO strings to Date objects automatically
    },
  ],
});
// package.json (monorepo root)
{
  "scripts": {
    "generate:api": "openapi-ts",
    "prebuild": "npm run generate:api"
  }
}

Running npm run generate:api outputs:

apps/web/src/lib/api/
├── index.ts
├── types.gen.ts      # TypeScript interfaces from the spec
└── services.gen.ts   # one function per operationId

Usage in a Next.js component:

import { createOrder } from "@/lib/api";

const result = await createOrder({
  body: {
    idempotencyKey: crypto.randomUUID(),
    items: [{ productId: "abc-123", quantity: 2 }],
    shippingAddressId: "def-456",
  },
});

if (result.error) {
  // result.error is typed as ValidationError | ConflictError
  if (result.error.code === "DUPLICATE_ORDER") {
    redirect(`/orders/${result.error.existingOrderId}`);
  }
  return;
}

// result.data is typed as Order — no manual interface needed
console.log(result.data.status);

The ConflictError type came from the spec’s 409 schema. If the backend changes what the 409 response looks like without updating the spec, the TypeScript types won’t reflect it — and the tests will catch it. That’s the point.

Enforcing the spec on the backend

Generating client types is the easy half. The backend also needs to be validated against the same spec — from the inside.

For Express/Node:

npm install express-openapi-validator
import OpenApiValidator from "express-openapi-validator";
import path from "path";

app.use(
  OpenApiValidator.middleware({
    apiSpec: path.resolve(__dirname, "../../../openapi/openapi.yaml"),
    validateRequests: true,
    validateResponses: {
      // throw in dev/staging; log in production to avoid cascading 500s
      onError: process.env.NODE_ENV === "production" ? "log" : "throw",
    },
  })
);

With validateRequests: true, any request that doesn’t match the spec schema is rejected with a 422 before it reaches your handler. You don’t write your own input validation for fields that are already described in the spec.

With validateResponses active in non-production, if your handler accidentally returns a response that doesn’t match the spec — wrong field name, missing required field, wrong type — the middleware will catch it during development. In production, it logs rather than throws, because a response validation bug shouldn’t turn a 200 into a 500.

Contract testing in CI

Runtime validation catches drift within a single running environment. CI contract testing catches it before merge.

schemathesis is the right tool for this. It reads your OpenAPI spec and generates property-based tests: valid inputs from the schema, boundary values, malformed inputs — and verifies that every response matches what the spec describes.

# .github/workflows/contract.yml
name: Contract Tests

on: [pull_request]

jobs:
  contract:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Start API server
        run: docker compose up -d api
        env:
          DATABASE_URL: ${{ secrets.TEST_DATABASE_URL }}

      - name: Wait for server
        run: |
          timeout 30 bash -c 'until curl -sf http://localhost:3000/health; do sleep 1; done'

      - name: Run contract tests
        run: |
          pip install schemathesis
          schemathesis run \
            ./openapi/openapi.yaml \
            --base-url http://localhost:3000 \
            --checks all \
            --stateful=links \
            --junit-xml=contract-results.xml

      - name: Upload results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: contract-results
          path: contract-results.xml

--stateful=links is worth calling out: it follows links defined in the spec to chain API calls together. If your spec defines that a POST /orders response links to GET /orders/{id}, schemathesis will test that chain end-to-end. Most teams don’t write those links — which is a missed opportunity, because stateful testing catches entire classes of bugs that single-endpoint tests miss.

The spec change review process

The most important cultural shift: all API changes start with a PR that modifies the OpenAPI YAML. Not a PR that modifies a handler with the spec as an afterthought.

This surfaces design disagreements early. When a backend engineer proposes adding a field, the frontend team sees it in the spec PR before implementation. They can push back on field naming, argue for a different error structure, or request an extra endpoint — while the cost of change is still low.

To enforce this automatically, add a spec lint step:

npm install -D @redocly/cli
{
  "scripts": {
    "lint:spec": "redocly lint openapi/openapi.yaml"
  }
}
# redocly.yaml
rules:
  operation-operationId: error          # every operation must have an operationId
  operation-summary: error              # required for generated documentation
  no-unused-components: warn
  path-kebab-case: error
  tag-description: warn

A spec PR that doesn’t pass lint doesn’t merge. That’s the floor.

What this workflow costs

The tradeoff is real. Writing YAML before writing code adds friction. Engineers who are used to running a server and seeing what it does in Postman will find this slower at first.

The spec also creates a coordination point. When backend and frontend are blocked on a spec decision — what should the error shape look like, should pagination be cursor-based or offset — someone has to make a call. That’s not friction the spec creates; it’s friction that was always there, now made visible instead of deferred.

Two things that help: a good editor setup (Redocly VS Code extension gives inline validation and autocomplete in the YAML file), and a team norm that spec PRs should be small. A spec PR that adds one endpoint is fast to review. A spec PR that adds twelve endpoints takes a day to get through.

Where to go from here

Once this foundation is in place — spec linting, client generation, runtime validation, CI contract tests — the next layer is API versioning strategy. How do you introduce breaking changes? Do you version by URL path or by Accept header? What does your deprecation timeline look like? Those decisions belong in the spec too, as extensions or as separate spec files per major version.

The short version: start with one endpoint, run the full pipeline for it, and see whether the friction is manageable before committing the entire team. It usually is.

Ditulis oleh Reza Pradipta