What is the difference between OpenAPI-first and code-first?
In spec-first development, a hand-written OpenAPI document is the source of truth. A generator reads it and produces server interfaces, request and response models, and client SDKs. Engineers then write handlers that implement those generated interfaces. Changing the API means editing the spec and regenerating the code.
In code-first development, the handlers, types and annotations are the source of truth. The spec is emitted from the code, either at build time or by a running service that exposes its own document. Clients are generated from that emitted spec. Changing the API means changing the code.
SPEC-FIRST
openapi.yaml ──► generator ──► interfaces / models / clients ──► hand-written impl
▲ ▲ ▲
[CI: lint + [CI: regenerate, [CI: compiles against
breaking-change diff] fail if output differs] interfaces, contract tests]
CODE-FIRST
code + annotations ──► build ──► emitted spec ──► clients
▲
[CI: diff against committed spec,
lint + breaking-change diff]
Treating this as a choice about which file you write first misses the point. Teams using spec-first often prototype a handler before they touch YAML. Code-first teams often sketch a spec on a whiteboard before they write code. The decision that matters is which artifact is authoritative when the two disagree, and where drift gets caught.
In spec-first, the compiler enforces some alignment, because handlers must satisfy the generated interfaces. Code-first has no equivalent check unless CI compares the emitted spec with a committed copy. Without that comparison, an annotation change can silently alter the public contract.
SPEC-FIRST (source of truth: openapi.yaml)
+--------------+ +-----------+ +------------------+ +--------------+
| openapi.yaml |-->| generator |-->| interfaces, |-->| hand-written |
| (authority) | +-----------+ | models, clients | | handlers |
+--------------+ +------------------+ +--------------+
^ ^ ^
[CI-1] [CI-2] [CI-3]
CODE-FIRST (source of truth: code)
+--------------+ +-----------+ +------------------+ +--------------+
| handlers, |-->| build |-->| emitted spec |-->| clients |
| annotations | +-----------+ +------------------+ +--------------+
| (authority) | ^
+--------------+ [CI-4]
[CI-1] lint + breaking-change diff of the hand-written spec
[CI-2] regenerate; fail if output differs from committed code
[CI-3] handlers compile against interfaces; contract tests
[CI-4] diff emitted spec vs committed copy; lint + breaking-change diff
In spec-first the hand-written spec is authoritative and drift is caught at three points, while in code-first the code is authoritative and drift is caught only if CI diffs the emitted spec against a committed copy.
How does each approach work under the hood?
Spec-first. A generator parses the OpenAPI document, resolves $ref pointers (including references into other files), and builds an in-memory model of paths, operations, parameters and schemas. It then walks that model and renders language-specific output through templates. Each operation becomes a method on an interface or abstract class. Each schema under components/schemas becomes a model type, and constraints such as required, enum and nullable are mapped onto the target language's type system as far as it allows. Anything the language can't express directly, such as minimum/maximum or a pattern, becomes validation annotations or runtime checks, or is dropped, depending on the generator and its options. Because the templates decide the shape of the output, two generators fed the same spec can produce very different code.
Code-first. The framework or a plugin inspects the application's routes and their types. Depending on the stack, this happens through runtime reflection, type hints, annotations, or a build-time step. For each route it records the HTTP method and path, path and query parameters, the request body type, and the declared response type. It converts those types into JSON Schema and assembles an OpenAPI document. Some frameworks build this document when the application starts and serve it from an endpoint. Others write it to a file during the build. Either way, the document contains only what the framework can see in signatures and annotations. Behavior inside the handler body or in middleware is invisible to it unless you declare it explicitly, which is the root of the drift problem covered below.
In both cases the OpenAPI document is the hand-off point. Mock servers, client generators, linters and breaking-change diff tools consume the same document regardless of how it was produced.
How does spec-first change API design reviews?
Spec-first moves API design review earlier. The pull request contains only YAML, so reviewers argue about the contract itself: resource names, status codes, error shapes and pagination. Nobody is defending handler code they already wrote, and changing a field name costs one line instead of a refactor. Consumers can start building against a mock server generated from the same file while the backend team implements it.
The example below defines GET /orders with limit and cursor query parameters and a 200 response containing items and next_cursor. Its 400 and 404 responses use $ref to point at a shared Error schema under components. Reviewers should check:
- Naming: whether resources are plural nouns and field casing (
next_cursorvsnextCursor) matches the rest of the API. - Pagination: whether
limithas amaximumand a default, and whether cursor pagination is used consistently instead of offset on some endpoints. - Status codes: whether
404makes sense for a collection endpoint, or whether an emptyitemsarray is the honest answer. - Errors: whether every error response references the shared
Errorschema rather than defining its own shape. One-off error objects force clients to write per-endpoint parsing.
The cost is that hand-written specs grow quickly. A single several-thousand-line file is hard to review because diffs lose context. It also causes constant merge conflicts when several teams edit paths and components in parallel. To keep reviews workable, split the spec into per-resource files, put shared schemas and parameters in their own files referenced with $ref, and bundle them into one document only at build time.
openapi: 3.0.3
info: {title: Orders API, version: 1.0.0}
paths:
/orders:
get:
summary: List orders (cursor pagination)
parameters:
- {name: limit, in: query, schema: {type: integer, minimum: 1, maximum: 100, default: 20}}
- {name: cursor, in: query, schema: {type: string}} # opaque; taken from next_cursor
responses:
'200':
description: A page of orders
content:
application/json:
schema:
type: object
required: [items]
properties:
items: {type: array, items: {$ref: '#/components/schemas/Order'}}
next_cursor: {type: string, nullable: true} # null on the last page
'400': {$ref: '#/components/responses/Error'}
'404': {$ref: '#/components/responses/Error'} # review: empty items instead?
components:
responses:
Error: # one error shape reused by every endpoint
description: Error response
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
schemas:
Error:
type: object
required: [code, message]
properties:
code: {type: string, example: invalid_cursor}
message: {type: string}
Order:
type: object
properties:
id: {type: string}
status: {type: string, enum: [pending, paid, shipped]}
An OpenAPI fragment for GET /orders with bounded cursor pagination and a shared Error response referenced via $ref, giving reviewers concrete naming, pagination, status-code and error-shape decisions to check.
How do you generate server stubs that age well?
The pattern that holds up is a strict split between generated and hand-written code. Configure your OpenAPI generator to emit only interfaces or abstract handlers plus request and response models, and put all behavior in classes you own. Never edit generated files. The next regeneration silently overwrites the change, and reviewers can no longer tell intended logic from tool output.
Keep generated output out of version control, or isolate it in its own directory or package and exclude it from linters and code review. Regenerate it during the build from the bundled spec, using a pinned generator version, so every machine and CI run produces identical output. An unpinned generator can turn an unrelated upgrade into a diff across hundreds of files.
For example, a build task runs the generator before compilation and writes into a generated package. A hand-written OrdersController then implements the generated OrdersApi interface. When the spec adds an operation, the build fails until you implement it, which is the main payoff of this setup.
Trade-offs
- Output quality varies by language and framework. Generated code can be verbose or non-idiomatic.
- Some schema constructs are often awkward. Watch
oneOf/anyOf, discriminators, nullable fields and file uploads. - Custom templates add maintenance. Once you customize templates, you have to maintain them across generator upgrades.
- Tools can lag the specification. Support for newer OpenAPI and JSON Schema features may be incomplete.
Before you commit to a generator, test your own spec's hardest schemas against it. Don't assume support.
// Build step (runs before compile; output goes to build/, never committed):
// docker run --rm -v "$PWD:/work" \
// openapitools/openapi-generator-cli:${GENERATOR_VERSION} generate \
// -i /work/api/openapi.bundled.yaml -g spring -o /work/build/generated \
// --additional-properties interfaceOnly=true
// GENERATOR_VERSION is an exact pinned tag kept in the repo, never "latest".
// Also configure the generator so interface methods have no default bodies.
// Check your generator's docs for that option. Without it, a new operation
// compiles silently instead of failing the build.
package com.example.orders.web;
import com.example.orders.generated.api.OrdersApi; // generated, read-only
import com.example.orders.generated.model.CreateOrderRequest;
import com.example.orders.generated.model.Order;
import com.example.orders.service.OrderService; // hand-written domain code
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
// Hand-written: all behavior lives here, never in the generated package.
@RestController
public class OrdersController implements OrdersApi {
private final OrderService orders;
public OrdersController(OrderService orders) {
this.orders = orders;
}
@Override
public ResponseEntity<Order> createOrder(CreateOrderRequest request) {
return ResponseEntity.status(HttpStatus.CREATED).body(orders.create(request));
}
@Override
public ResponseEntity<Order> getOrder(String orderId) {
return orders.find(orderId).map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
}
A pinned generator regenerates a Spring interface and models from the bundled spec at build time, and a hand-written controller implements that interface without touching the generated code.
When is code-first the better choice?
Code-first is strongest when one team owns both the API and its main consumers, such as a backend serving its own web or mobile client. The spec is generated from handler signatures and types, so the compiler keeps it close to the implementation. You don't need a separate codegen toolchain, and IDE refactoring works across the whole API surface. You also never fight generator templates to get idiomatic code. Adding a field is a single change in one language, instead of the spec-first loop of editing YAML, regenerating, and then implementing against new interfaces.
Code-first's weakness is that the emitted spec documents only what the framework can infer. Several gaps follow from that:
- Missing detail. Error responses, examples, auth requirements and constraints such as string length or numeric ranges are often absent unless something enforces them.
- Leaked internals. Internal type names, framework conventions or accidental fields (an ORM's
createdAt, a debug flag) can leak into the public contract. - Silent breaks. Renaming a class or property is a safe refactor inside the codebase but a breaking change for anyone generating a client from the spec.
Take an order lookup handler annotated to return 200 with an OrderResponse. In practice it also returns a 404 with a framework-default error body when the order doesn't exist, and a 403 from an authorization check in middleware. Neither appears in the generated spec, because the annotations describe only the success path while the handler and its middleware decide the actual responses.
from fastapi import Depends, FastAPI, Header, HTTPException
from pydantic import BaseModel
app = FastAPI()
class OrderResponse(BaseModel):
id: str
status: str
total_cents: int
ORDERS = {"ord_123": {"id": "ord_123", "status": "shipped",
"total_cents": 4599, "owner": "user_42"}}
def require_user(x_user_id: str = Header(...)) -> str:
# Stand-in for real auth. The spec records the header, not the auth rules.
return x_user_id
@app.get("/orders/{order_id}", response_model=OrderResponse)
def get_order(order_id: str, user: str = Depends(require_user)):
order = ORDERS.get(order_id)
if order is None:
# Real response: 404 with the default {"detail": ...} body. Not in the spec.
raise HTTPException(status_code=404, detail="Order not found")
if order["owner"] != user:
# Real response: 403 from the authorization check. Also not in the spec.
raise HTTPException(status_code=403, detail="Forbidden")
return order
A FastAPI handler whose generated spec lists only the 200 and automatic 422 responses, while the handler also returns 404 and 403 bodies that consumers never see documented unless they are declared by hand.
How do you catch spec drift in CI?
That gap is code-first drift. The spec describes the annotations, not the behavior, so undocumented error responses and fields that serialize as null slip through without warning. Spec-first drifts differently. A handler can return a hand-built map instead of the generated response type, which bypasses the compiler's checks. Some behavior, such as a field that appears only when another field is set, may not be expressible in the schema at all. The spec then looks complete while describing a simpler API than the one running. Neither approach proves runtime conformance on its own.
Three countermeasures close the gap:
- Validate requests and responses against the spec in integration tests or middleware. Fail on any undeclared status code or schema mismatch.
- Run contract tests that exercise real handlers, including error paths, not only the success path.
- Check that committed artifacts match a fresh regeneration, so nobody hand-edits generated output or forgets to regenerate.
Under both approaches, treat the OpenAPI document as a reviewed artifact: commit it, lint it, and diff it. A pull-request job might run these steps:
make regeneraterebuilds the spec (code-first) or the stubs (spec-first).git diff --exit-codefails if the output differs from what was committed.<spec-linter> openapi.yamlapplies your style ruleset.<breaking-change-diff> base/openapi.yaml openapi.yamlcompares the spec against the target branch.
The payoff is engineering time. If review catches a removed field or a newly required parameter, the fix costs one comment. If a consumer finds it first, the cost is an incident, a rollback, and coordination across teams.
Who should use spec-first, and who should use code-first?
Roles matter as much as team size here.
- API platform or architecture groups that set conventions across many services benefit most from spec-first. The spec is something they can review, lint and approve without reading every service's code.
- Teams publishing public or partner APIs should use spec-first, or at least gate code-first output on a reviewed spec. Their consumers rely only on the documented contract and can't read the source.
- Frontend, mobile and integration engineers who consume an API benefit from spec-first because they can work against mocks and generated clients before the backend ships.
- Product backend teams that own an internal API and its only client usually move faster with code-first. The contract and its consumer change in the same pull request, often by the same people.
- Polyglot organizations, where producers and consumers use different languages, get more from a language-neutral spec as the source of truth than from one framework's view of the API.
- Technical writers and QA engineers benefit from either approach as long as the spec is committed and reviewed. Spec-first gives them a place to contribute descriptions and examples directly.
When should each approach be used?
The right choice can change over an API's lifecycle.
- Early prototyping: code-first, or no formal spec at all. The shape of the API is still unknown, and regenerating stubs for every experiment slows you down.
- Before the first external consumer: this is the cheapest point to decide which artifact is authoritative. At minimum, commit the spec and start diffing it.
- Designing a new API that several teams will consume: spec-first, so the design review happens before anyone writes handlers and consumers can build against mocks in parallel.
- Adding endpoints to an existing code-first service: stay code-first, but declare error responses and constraints explicitly and gate merges on the spec diff.
- Preparing a public launch or a new major version: spec-first for the new surface, because breaking changes become expensive to undo once external clients exist.
- Migrating a legacy service: follow the incremental path described in the hybrid section below rather than switching everything at once.
Should your team use OpenAPI-first or code-first?
The decision comes down to who pays for a contract mistake and how many places it lands.
| Criterion | Spec-first | Code-first |
|---|---|---|
| Source of truth | The OpenAPI document | Annotations and types in the service |
| Design review timing | Before implementation | After code exists, often in the same PR |
| Toolchain cost | Generator config, templates, version pinning | Mostly framework plugins |
| Edit loop speed | Slower: edit spec, regenerate, implement | Fast: change handler, spec follows |
| Idiomatic code | Depends on generator quality | Native to the framework |
| Documentation completeness | High, since review forces descriptions and examples | Uneven, limited to what annotations capture |
| Risk of leaking internals | Low | Higher, because ORM fields and internal enums slip into schemas |
| Drift risk | Implementation drifts from spec | Spec drifts from intent |
Lean spec-first when several teams or languages consume the API, when it is public or partner-facing, or when a platform or architecture group owns API design separately from the implementers. In each case one contract has to hold across codebases you don't control.
Avoid spec-first for a single team iterating quickly on an internal API with weak generator support for its framework. You would pay for regeneration and generated code you have to work around, and get little in return.
Avoid code-first when the contract is shared across teams or languages, or is public. Every refactor becomes a possible breaking change that nobody reviewed as one.
On cost, spec-first front-loads it: setup plus a slower edit loop on every change. Code-first defers it to whenever a consumer breaks. More consumers and slower-moving APIs both make the up-front cost easier to justify.
What are the alternatives to both approaches?
OpenAPI-first and code-first are not the only ways to manage an HTTP API contract.
- A different interface definition language. For service-to-service calls you control on both ends, Protocol Buffers with gRPC is the IDL-first model applied to RPC. The
.protofile is the source of truth, and the toolchain generates code for both sides. Field numbering and its compatibility rules make some breaking changes harder to introduce by accident. The trade-off is weaker support from browsers and generic HTTP tooling than plain JSON over HTTP. - GraphQL. The schema is the contract, and clients choose which fields they request. It can be written schema-first or derived from code, so the same authority question applies. Evolution usually means adding fields and deprecating old ones rather than versioning endpoints.
- AsyncAPI for event-driven interfaces. For message brokers and event streams, AsyncAPI fills the role OpenAPI fills for request/response HTTP. The same spec-first versus code-first choice applies to it.
- Consumer-driven contract testing. Instead of one central spec, each consumer records the requests it makes and the responses it relies on. The provider's CI verifies it still satisfies every recorded contract. This catches breaks that matter to real consumers, including behavior a schema can't express. It doesn't give you a single document describing the whole API, and it is often used alongside OpenAPI rather than instead of it.
- JSON Schema without OpenAPI. Some teams version only the payload schemas and document endpoints separately. This works for a small number of message types but loses the operation-level information (paths, parameters, status codes) that client generators and diff tools need.
- Hand-written documentation with no machine-readable contract. This is the lowest setup cost and the highest drift risk. Nothing can be linted, diffed or generated from it.
- Hybrids of spec-first and code-first, covered in the next section, are often the practical answer for existing services.
What are the hybrid and migration paths between the two approaches?
Most teams don't need to pick one approach and convert everything at once. Two middle grounds are common.
Extract, clean, then flip authority. Emit the spec from the existing code-first service, clean it up, and declare it the source of truth. The catch is the cleanup. Extracted specs tend to carry framework-generated operation IDs, inline schemas duplicated across endpoints, missing error responses, and descriptions that are empty or copied from docstrings. Until a human fixes those, the spec documents what the code does, not what the API should promise.
Stay code-first, gate on the spec. Keep writing handlers first, but treat the emitted spec as a reviewed artifact. Merges are blocked by lint failures and unapproved breaking changes. You get most of the contract discipline without regenerating anything.
Switching a mature codebase to generated stubs is expensive. Every handler has to be rewritten to implement a generated interface, and it's easy to underestimate how much framework-specific behavior lives in decorators and annotations. A change that touches every handler is hard to review and risky to ship as a single change.
A safer order of steps, where each one is useful even if you stop there:
- Commit the emitted spec so changes show up in diffs.
- Add lint and breaking-change diff checks to CI.
- Validate real responses against the spec in tests, so drift fails a build instead of a consumer.
- Move one service or route group at a time to generated interfaces, starting with the one that has the most external consumers.
How does a contract-driven workflow save engineering time?
The savings come from moving work earlier, when changes are cheap, and from removing hand-written code that a machine can produce.
- Parallel work. With spec-first, consumers build against a mock server and generated client while the backend is still being implemented, instead of waiting for a deployed endpoint.
- Less hand-written glue. Generated clients and models replace hand-written HTTP calls, serialization code and DTOs, which otherwise have to be written once per consumer and per language.
- Cheaper design changes. Renaming a field or reshaping an error during spec review is a one-line edit. After implementation, it touches handlers, tests and every client.
- Fewer integration incidents. The breaking-change diff and response validation in CI catch contract breaks before release, which avoids rollbacks and cross-team debugging.
- Shorter reviews. Reviewers read a focused spec diff to see what changed in the contract, instead of inferring it from handler code.
- Documentation that stays current. Reference docs rendered from a checked spec don't need a separate update step that people forget.
An illustrative estimate, using assumed inputs rather than measured results: assume an API with four consumer teams, and a field rename that ships unreviewed. Assume each consumer team spends half a day noticing the failure, tracing it to the API, and patching or waiting for a rollback. Assume the provider team spends another day on the rollback, the fix and coordination. Under those assumptions, one escaped break costs about three engineer-days. Under the same assumptions, catching it with a failed breaking-change check in CI costs one review comment and a few minutes of rework. Your own inputs will differ. The general pattern holds: the cost of an escaped contract break grows with the number of consumers, while the cost of the CI check stays roughly flat.
The time isn't free. Spec-first adds generator setup, template maintenance and a slower edit loop, and any approach needs someone to own the lint rules and approve breaking changes. The investment pays off when the number of consumers, or the cost of breaking them, is high enough to outweigh that overhead.
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 vs code first, 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.