# API documentation with OpenAPI and contract-first design

> What is OpenAPI and how does it improve API development? Contract-first versus code-first?

Canonical: https://www.internhack.in/learn/interview/api-design-interview/api-openapi-documentation
Last updated: 2026-11-28

Difficulty: Beginner

## Question

What is OpenAPI and how does it improve API development? Contract-first versus code-first?

## Answer

OpenAPI (formerly Swagger) is a machine readable description of an HTTP API, written in YAML or JSON. It states the servers, paths, methods, parameters, request bodies, response schemas, status codes, authentication schemes and examples. The analogy is an architect's blueprint. Builders, inspectors and interior designers all work from the same document, and disagreements are settled by the drawing, rather than by verbal memory.

Why it matters. Because the spec is structured, tools can consume it. Documentation portals like Swagger UI, Redoc and Stoplight render interactive docs. Code generators produce typed client SDKs in TypeScript, Java, Python and Go, and server stubs. Mock servers let frontend teams build against the contract before the backend exists. Validators like express-openapi-validator reject requests and responses that violate the schema at runtime. Postman can import a spec into a collection with tests. Linters such as Spectral enforce your style guide, catching inconsistent naming or missing descriptions in CI. Contract tests and breaking-change detectors (openapi-diff, oasdiff) run in pull requests to block accidental incompatibilities.

Structure at a glance: openapi version, info with title and version, servers, paths containing operations (get, post) each with operationId, summary, parameters, requestBody, responses; and a components section holding reusable schemas, parameters, responses and securitySchemes, referenced by $ref. Reuse is essential: define Error once (ideally as problem details) and reference it from every operation. Use schema constraints such as required, format, enum, minimum and maxLength; these are validation rules as well as documentation. Provide realistic examples, since examples are what developers read first.

Contract-first versus code-first. Contract-first (design-first): write the OpenAPI document before implementation, review it as a team including frontend and partner consumers, then generate stubs and mocks. Advantages: early feedback on ergonomics, parallel frontend and backend work, the spec is the source of truth. Code-first: annotate code (decorators in NestJS or tsoa, Springdoc in Java, FastAPI in Python) and generate the spec from it. Advantages: always in sync with actual behaviour, less duplication, easy adoption. Risks: the API shape emerges accidentally from implementation details, and generated specs can be sparse without descriptions. Many teams go design-first for public APIs and code-first for internal ones; either works if the spec is validated in CI so docs never drift.

Documentation is more than a reference. Good docs also include getting-started guides, authentication instructions, error catalogue, rate limits, pagination conventions, changelog and migration guides, plus copy-pasteable examples in several languages. Stripe's docs are the benchmark, with live keys inserted into examples.

Version 3.1 aligns schemas with JSON Schema 2020-12, so nullable becomes type arrays, and it adds webhooks as a top-level construct. AsyncAPI is the sibling standard for event-driven APIs.

In the interview, mention the workflow: propose a spec, lint it, mock it, generate SDKs, validate at runtime, diff for breaking changes, publish docs automatically on merge.

## Code examples

### OpenAPI 3.1 snippet

```
openapi: 3.1.0
info:
  title: Orders API
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
paths:
  /orders/{id}:
    get:
      operationId: getOrder
      summary: Retrieve an order
      security: [{ bearerAuth: [] }]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      responses:
        '200':
          description: The order
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '404':
          description: Not found
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
components:
  securitySchemes:
    bearerAuth: { type: http, scheme: bearer, bearerFormat: JWT }
  schemas:
    Order:
      type: object
      required: [id, status, amount, currency]
      properties:
        id: { type: string }
        status: { type: string, enum: [pending, paid, shipped] }
        amount: { type: integer, description: Minor units }
        currency: { type: string, examples: [INR] }
    Problem:
      type: object
      properties:
        type: { type: string }
        title: { type: string }
        status: { type: integer }
```

An operation with security, path parameter and success and error responses that share reusable component schemas.

## Key points

- OpenAPI is a machine readable contract that drives docs, SDKs, mocks and validation.
- Reuse schemas through components and $ref.
- Design-first gives early feedback; code-first keeps docs in sync.
- Lint and diff specs in CI to catch breaking changes.
- Examples and guides matter as much as the reference.

## Common follow-up questions

- How do you stop the spec drifting from the implementation?
- What is the difference between Swagger and OpenAPI?
- How would you document webhooks?

## Interview tips

- Show the tooling pipeline, not just the definition.
- Take a side on contract-first versus code-first, with justification.

## Concepts covered

OpenAPI, Swagger, contract-first, API documentation

Previous: [Bulk and batch endpoints: partial failure handling](https://www.internhack.in/learn/interview/api-design-interview/api-bulk-batch-endpoints) · Next: [Backward compatibility and deprecating an API safely](https://www.internhack.in/learn/interview/api-design-interview/api-backward-compat-deprecation) · [All of API Design](https://www.internhack.in/learn/interview/api-design-interview)

## More API Design questions

- [API gateway: responsibilities and trade-offs](https://www.internhack.in/learn/interview/api-design-interview/api-gateway)
- [Design the API for a URL shortener](https://www.internhack.in/learn/interview/api-design-interview/api-design-url-shortener)
- [Design the order API for a food delivery app](https://www.internhack.in/learn/interview/api-design-interview/api-design-food-delivery-order)
- [Design a payment API: intents, refunds and reliability](https://www.internhack.in/learn/interview/api-design-interview/api-design-payment-api)
- [REST API security checklist: OWASP API Top 10 essentials](https://www.internhack.in/learn/interview/api-design-interview/api-security-hardening)
- [What makes an API good? Principles of API design](https://www.internhack.in/learn/interview/api-design-interview/api-what-makes-good-api)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [API Design](https://www.internhack.in/learn/interview/api-design-interview)
