What is OpenAPI-first development and who should use it?

In OpenAPI-first development, the API contract is written before any handler code. A change to an endpoint starts as a pull request against the OpenAPI document. That document lives in the same repository as the service, and reviewers approve the shape of the request and response before anyone implements it. Server stubs, client SDKs, type definitions, validators and reference docs all come from the spec. When the contract changes, you edit the spec and regenerate. Nobody patches generated files by hand, because the next regeneration would silently overwrite the patch.

That last rule matters more than the others. A spec that exists only as documentation will drift from the code, usually within a few releases, and then consumers stop trusting it. The approach pays off only when CI enforces the spec as the single source of truth. A build that changes behavior without changing the contract should fail.

Several reasons lead teams to adopt it:

  • Shared contracts. Frontend, mobile and partner teams review the same artifact the server is built from. They don't have to rely on a wiki page or a Slack thread.
  • Parallel development. Once the spec is merged, consumers can build against generated clients or mock servers while the backend is still unimplemented.
  • Fewer integration bugs. Mismatched field names, wrong nullability and missing enum values surface at review or compile time, before staging.

The teams that benefit most are those whose APIs have several consumers. These include platform teams serving internal product teams, services exposed across team boundaries, and public APIs, where a breaking change cannot be fixed by a coordinated deploy.

 +-------------------+     +------------------+     +---------------------+
 | Pull request edits|---->| Review: approve  |---->| openapi.yaml merged |
 | the OpenAPI spec  |     | request/response |     | in the service repo |
 +-------------------+     +------------------+     +----------+----------+
                                                               |
                                                               v
                                                    +---------------------+
                                                    | CI: regenerate all  |
                                                    | artifacts; fail on  |
                                                    | contract drift      |
                                                    +----------+----------+
                                                               |
          +-------------------+------------------+------------+----+
          |                   |                  |                 |
          v                   v                  v                 v
 +-----------------+ +-----------------+ +---------------+ +---------------+
 | Server stubs    | | Client SDKs and | | Types and     | | Reference     |
 | for handlers    | | mock servers    | | validators    | | docs          |
 +--------+--------+ +--------+--------+ +---------------+ +---------------+
          |                   |
          v                   v
   Backend implements   Frontend, mobile and partner teams build
   handlers on stubs    in parallel against generated clients

   Generated artifacts are never hand-edited: change the spec, regenerate.

In OpenAPI-first development, a reviewed spec in the service repo is the single source of truth, and CI regenerates every derived artifact from it and fails the build when code and contract drift apart.

How does OpenAPI codegen turn a spec into types and handlers?

A generator does not interpret your intent. It names output after the structure of your spec. Take an operation with operationId: createInvoice whose request body references #/components/schemas/InvoiceCreate and whose 201 response references Invoice. Most generators turn this into types named InvoiceCreate and Invoice, plus a handler or client method named createInvoice. If you define the same request body inline, the generator has to invent a name, such as CreateInvoiceRequest or InlineObject3. That name can change when someone reorders the file. If you omit operationId, the method name is derived from the path and verb, so renaming a path breaks every caller. Put each schema under components and give it a name. Treat operationId as a public identifier. Pick one naming convention, for example ThingCreate and ThingUpdate, and use it across all resources.

Some constructs map unevenly to target languages:

Construct Typical output Write it as
oneOf without discriminator Loose union or untyped value Add a discriminator with an explicit propertyName
anyOf Often treated like oneOf Use oneOf unless overlap is intended
additionalProperties: true Map type or dropped fields Use a typed additionalProperties schema, or set it to false
Nullable vs. optional Collapsed into one concept Keep required and nullability as separate decisions
format (date-time, uuid) Native type or plain string, depending on the tool Check the output and configure type mappings

Recursive schemas, deep polymorphism and nested allOf chains are the weak spot. Generators often flatten them incorrectly, duplicate their fields, or fall back to untyped values. Keep these structures shallow. Read the generated output for them instead of assuming it is correct.

openapi: 3.1.0
info: { title: Billing API, version: 1.0.0 }
paths:
  /invoices:
    post:
      operationId: createInvoice        # -> method/handler name: createInvoice
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/InvoiceCreate' }  # -> type InvoiceCreate
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Invoice' }      # -> type Invoice
components:
  schemas:
    InvoiceCreate:
      type: object
      required: [customerId, payment]
      additionalProperties: false       # closed object: no catch-all map in the output
      properties:
        customerId: { type: string, format: uuid }  # string or UUID type, depending on tool mapping
        note: { type: [string, 'null'] }            # optional AND nullable: two separate decisions
        metadata:                                    # typed map instead of additionalProperties: true
          type: object
          additionalProperties: { type: string }
        payment:
          oneOf:                                     # discriminator lets generators emit a tagged union
            - $ref: '#/components/schemas/CardPayment'
            - $ref: '#/components/schemas/BankPayment'
          discriminator: { propertyName: kind }
    Invoice:
      allOf:                                         # one shallow allOf level, not a chain
        - $ref: '#/components/schemas/InvoiceCreate'
        - type: object
          required: [id, createdAt]
          properties:
            id: { type: string, format: uuid }
            createdAt: { type: string, format: date-time }

An OpenAPI 3.1 fragment that uses named component schemas, a stable operationId, a discriminated oneOf, a typed additionalProperties map, and separate optional and nullable fields, with comments showing the names generators typically derive from each part.

Why aren't generated types enough without runtime request validation?

A generated CreateOrderRequest type describes what the handler expects, not what the client sent. In TypeScript, types are erased at compile time. In Python, type hints are not enforced at runtime. Deserializing JSON into a typed struct in Go or Java will often zero-fill missing fields or ignore unknown ones. In each case the compiler trusts the data that arrives over the network. Malformed input reaches business logic looking valid.

Runtime request validation closes that gap. Put validation middleware at the HTTP boundary, before routing hands control to a handler. Check path parameters, query strings, headers and body against the spec. Reject failures with one consistent, machine-readable error shape so clients can parse it programmatically: a status code, an error code, and the JSON path of each offending field. Handlers can then assume their inputs are structurally sound.

Validate responses in development and CI. This catches handlers that return data the spec doesn't describe. In production, response validation usually costs more than it is worth, so log or sample it instead of rejecting.

Schema validation is structural only. It cannot check that endDate follows startDate, that the caller owns the resource, or that a referenced ID exists. Treating a passing schema check as complete input validation is a security mistake, because authorization and invariant checks still need hand-written code.

Validation also has costs. Walking large payloads on hot paths adds CPU time and latency. Validators also differ in which keywords, format values and JSON Schema dialects they support. A spec can declare constraints that your runtime silently ignores, so test the constraints you depend on.

import express, { Request, Response, NextFunction } from "express";
import Ajv, { ValidateFunction } from "ajv";
import addFormats from "ajv-formats";

// Mirrors components.schemas.CreateOrderRequest in the OpenAPI spec
const createOrderSchema = {
  type: "object",
  required: ["customerId", "startDate", "endDate", "quantity"],
  additionalProperties: false,
  properties: {
    customerId: { type: "string", format: "uuid" },
    startDate: { type: "string", format: "date" },
    endDate: { type: "string", format: "date" },
    quantity: { type: "integer", minimum: 1 },
  },
};

const ajv = new Ajv({ allErrors: true });
addFormats(ajv); // "format" checks come from a plugin; confirm the ones you rely on are enforced
const validateCreateOrder = ajv.compile(createOrderSchema); // compile once, not per request

// Runs at the HTTP boundary, before the handler sees req.body
const validateBody = (validate: ValidateFunction) =>
  (req: Request, res: Response, next: NextFunction) => {
    if (validate(req.body)) return next();
    res.status(400).json({
      code: "VALIDATION_FAILED", // one machine-readable shape for every endpoint
      errors: (validate.errors ?? []).map((e) => ({ path: e.instancePath || "/", message: e.message })),
    });
  };

const app = express();
app.use(express.json({ limit: "100kb" })); // bound payload size, and so validation cost

app.post("/orders", validateBody(validateCreateOrder), (req, res) => {
  // The schema cannot express this cross-field rule; ISO dates compare correctly as strings
  if (req.body.endDate < req.body.startDate) {
    return res.status(422).json({ code: "INVALID_DATE_RANGE", errors: [{ path: "/endDate", message: "must not precede startDate" }] });
  }
  // Still hand-written: does the caller own customerId, and does that customer exist?
  res.status(201).json({ status: "accepted" });
});

Express middleware compiles the request schema once with Ajv and rejects structurally invalid bodies with a consistent error shape, while the date-range invariant and ownership checks stay in hand-written handler code.

How do you keep the spec and code from drifting in CI?

Enforcement starts with deciding where generated code lives.

Commit generated code Generate at build time
Review visibility Spec changes show their effect on types in the same PR Reviewers see only the spec diff
Build dependencies Generator not needed to compile Every build and IDE setup needs the generator
Drift risk Someone can edit generated files or forget to regenerate None, but stale local copies can confuse editors
Repo noise Larger diffs, merge conflicts in generated files Clean history

Whichever you choose, put generated output in its own directory or package that nobody edits by hand. Mark it as generated in your repository attributes so diffs collapse in review. Hand-written handlers should import from it, never sit beside it.

If you commit generated code, add a CI job that runs the generator and fails if the working tree changes. This catches both forgotten regeneration and manual edits, because the spec is the only input that can produce passing output.

Next, lint the spec for style and correctness, such as missing descriptions, inconsistent naming, or undeclared error responses. Then diff it against the version on the main branch to detect breaking changes. Changes that typically break existing clients include:

  • Removing or renaming a response field
  • Tightening constraints, such as a shorter maxLength, a narrower enum, or a new pattern
  • Adding a required request field or parameter
  • Changing a field's type

Pin the generator and linter versions. A generator upgrade can rewrite thousands of lines. Make each upgrade its own PR so the diff contains only tool changes and stays reviewable.

#!/usr/bin/env bash
# ci/check-spec.sh: run in CI on every pull request.
# Tool versions are pinned in package.json and package-lock.json, so
# 'npm ci' installs exactly the versions the committed output was built with.
set -euo pipefail

SPEC=openapi.yaml
GEN_DIR=src/generated   # generated output only; hand-written code imports from here

npm ci

# 1. Regenerate types from the spec and fail if anything changed.
#    This catches forgotten regeneration and manual edits to generated files.
npx openapi-typescript "$SPEC" -o "$GEN_DIR/api.ts"
if ! git diff --exit-code -- "$GEN_DIR"; then
  echo "Generated code is out of date. Run the generator and commit the result." >&2
  exit 1
fi
# Also fail on new generated files that were never committed.
if [ -n "$(git status --porcelain -- "$GEN_DIR")" ]; then
  echo "Untracked files in $GEN_DIR. Commit them." >&2
  exit 1
fi

# 2. Lint the spec (style and correctness rules live in the linter config).
npm run lint:spec

# 3. Compare against the spec on main to flag breaking changes:
#    removed fields, tightened constraints, new required inputs, type changes.
git fetch --quiet origin main
git show origin/main:"$SPEC" > /tmp/base-openapi.yaml
npm run diff:spec -- /tmp/base-openapi.yaml "$SPEC"

A CI script that regenerates types from the spec and fails on any diff or untracked file, lints the spec, and checks it against main for breaking changes. The lint and diff commands are package.json scripts that wrap whichever pinned tools you choose.

How can one spec save engineering time beyond the server?

The same spec that drives your server can also drive three consumer-facing artifacts:

  • Client SDKs. Generate typed clients for each language your consumers use. A renamed field then breaks their build at compile time instead of failing silently in production.
  • Contract tests. Run a schema-driven test tool against a deployed staging service. It sends requests derived from the spec and checks that status codes, headers and response bodies match. This catches cases where the server compiles but returns something the spec doesn't promise, such as an undocumented null or an extra error code.
  • Mock servers. Serve example responses straight from the spec. Frontend and partner teams can build against an agreed contract while the backend is still being written, so integration stops being a serial dependency.

This has a cost. The first iteration is slower, because you design and review the schema before writing any handler. Spec PRs also add a review step that some teams find tedious. The return shows up later: less hand-written client glue, fewer integration bugs found late, and reference docs that regenerate instead of going stale.

Illustrative estimate (assumed numbers, not a benchmark)

Net hours saved per quarter = (C × G) + (B × F) + D − (E × R)

Assumed inputs:

  • C = 3 consumer clients
  • G = 10 hours of glue code avoided per client
  • B = 4 integration bugs avoided
  • F = 6 hours to fix each bug
  • D = 8 hours of documentation upkeep avoided
  • E = 12 endpoint changes
  • R = 2 extra hours of spec design and review per change

Result: 30 + 24 + 8 − 24 = 38 hours.

Replace these with your own figures. If you have one consumer and the API changes rarely, the result can be negative.

When should you avoid OpenAPI-first, and what are the alternatives?

Spec-first earns its cost when an interface has several consumers and a long life. Outside that, it can become overhead.

Exploratory and short-lived endpoints. For an internal endpoint whose shape you are still discovering, writing YAML before any code means you iterate on the spec, regenerate, and rebuild on every guess. If the endpoint may be deleted next sprint, a lighter process is usually the better trade.

Monolithic specs. A single file of several thousand lines produces diffs nobody can review well. Split it into per-resource files joined by $ref, and bundle in CI. If you skip that step, reviewers start approving spec changes they never read.

Lock-in. Generated handler signatures tie you to one framework's request and response model, and some generators ship a runtime library your code then depends on. Watch for workarounds: hand-edited generated files, wrapper layers that ignore the generated types, or custom templates only one person understands. These mean the team is fighting the generator rather than benefiting from it.

Approach Source of truth Drift risk Tooling effort
OpenAPI-first Spec file Low, if CI enforces it High up front
Code-first, spec generated from annotations Code Medium: annotations can fall out of step with real behaviour Low to medium
Schema-first with another IDL IDL file Low Medium to high, often requires a non-HTTP/JSON stack
Hand-maintained docs Nobody High Low to start, then ongoing manual work

Code-first is often the pragmatic middle ground for a single team. The spec stays useful as long as you test that the generated document matches what the service actually returns.

How do you migrate an existing code-first service to OpenAPI-first?

Migrating works best as a sequence where each step surfaces disagreements before anything can break in production.

1. Get an initial spec

If your framework can emit an OpenAPI document from annotations or route definitions, export it and commit that file. Otherwise, write the spec by hand for your most-used endpoints. Treat this first version as a hypothesis about how the service behaves.

2. Validate responses in tests

Add a step to your existing integration tests that checks every response against the spec. This exposes real mismatches: undocumented nullable fields, inconsistent status codes, enums that gained values nobody recorded. Fix the spec or the code each time, depending on which one is wrong. Test-time checks carry no production risk, so this is the cheapest point to find these problems.

3. Add request validation in log-only mode

Strict request validation can reject traffic that has worked for years. Clients send extra properties, numbers as strings, or slightly malformed dates. Log each violation with the endpoint and client identifier, then review the logs. Some findings mean the spec is too narrow. Others mean a client needs to change before you enforce anything.

4. Make the spec authoritative one endpoint at a time

For each endpoint, move from generating the spec out of code to generating code from the spec. Then switch on strict validation and enable the CI regeneration and contract checks for that endpoint. Going endpoint by endpoint keeps each rollback small.

Do not skip the CI checks. Without them, the spec drifts away from the code again, and you end up with documentation that no longer describes the service.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to openapi first development, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.