SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • What is an API?
  • API Styles
  • Idempotency
  • Data Formats
  • REST, GraphQL, gRPC
  • Pagination, Filtering and Sorting
  • API Versioning
  • Error Handling and Status Codes
  • OpenAPI / Swagger
  • Bulk APIs and File Upload
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Design

OpenAPI / Swagger

A written contract for your API that people, docs and tools can all read.

⏱ 11 min readBeginnerHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

OpenAPI is a standard way to write down what your API does in one file (YAML or JSON): the paths, the inputs, the outputs, the errors and how to log in. Swagger is the older name for it, and today it mostly names the family of tools (like Swagger UI) built around it.

  • The file is a contract. People can read it, and so can programs.
  • From one contract you can get documentation, client libraries, server stubs, mock servers and automatic checks.
  • Comparing two versions of the file tells you if a change would break existing clients.

02Concept: What is it?

Imagine every team describing its API in an email, a wiki page, or just the code. Docs go out of date, two teams read the same page two different ways, and nobody knows if a change is safe. The fix is to write the API down once, in a format that machines can read.

That format is the OpenAPI Specification (OAS). A file says things like: "there is a POST /orders. It needs an item and a quantity. It answers 201 with an order, or 400 with an error. You must send an API key." The request and response shapes are written with JSON Schema.

You may hear three names. OpenAPI is the specification. Swagger was the original name of the specification, and now it is the brand for a set of tools, such as Swagger UI (a page where you can read the docs and try calls) and Swagger Editor. Many other tools read OpenAPI files too.

A small OpenAPI file (illustrative, shortened)
openapi: 3.0.3
info:
  title: Shop API
  version: 1.0.0
paths:
  /orders:
    post:
      summary: Create an order
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [item, quantity]
              properties:
                item: { type: string }
                quantity: { type: integer, minimum: 1 }
      responses:
        "201": { description: Order created }
        "400": { description: Invalid request }
One file, many uses
πŸ“„DocsSwagger UI
πŸ“¦Client librariesgenerated
←
πŸ“œOpenAPI filethe contract
→↓
πŸ§ͺContract testsdoes the server match?
🎭Mock serverfake API for the front end
The contract sits in the middle. Everything else is made from it, or checked against it.
🧠Specification vs tools
OpenAPI is the file format. Swagger UI, Redoc, code generators and linters are tools that read it. You can change tools and keep the contract.

03Real-Life Example

🍡The Restaurant Menu
A restaurant prints a menu. It lists every dish, the options ("steak: rare, medium or well done"), what is required ("choose one side") and the price. Customers, waiters and the kitchen all work from the same page. If the chef changes a dish without updating the menu, orders fail. If the owner wants to remove a dish, they check the menu to see who might still ask for it.
Restaurant menu
OpenAPI file
The dishes on the menu
Paths and operations (GET, POST...)
Options and required choices
Parameters and required fields
What arrives on the plate
Response shapes and status codes
β€œPlease show your reservation”
Security schemes (API key, OAuth)
A printed menu for guests
Generated documentation
A pretend dish for staff training
A mock server
Checking the kitchen cooks what the menu says
Contract tests
Two ways to start
Design-first
✍️Write the file
→↓review
πŸ‘₯Teams agree
↓
πŸ’»Build the serverand the clients, in parallel
Code-first
πŸ’»Write the server
→↓generate
πŸ“œGet the file
↓
πŸ“„Publish the docs

04Why Do We Need It?

πŸ“–Docs that stay true
Documentation is built from the same file the tools use, so it does not drift away from the real API.
🀝Teams work in parallel
A front-end team can start from the contract and a mock server while the back end is still being built.
βš™οΈGenerated code
Client libraries and server stubs come from the file, so nobody types the same request by hand in five languages.
πŸ›‘οΈSafe changes
A diff tool compares two versions of the file and warns if a change would break clients.
πŸ§ͺAutomatic tests
Tools can send requests and check the answers against the contract, in CI, on every change.
πŸ€–Easier for tools and AI
A clear, structured description is easier for other programs, including AI agents, to understand than a prose page.
Write the API down once, in a form that humans and programs can both read. Then docs, code and tests come from the same truth.

05Where Do We Use It?

🏒Public APIs
Companies publish an OpenAPI file so that partners can read the docs and generate a client.
🧩Between internal teams
The file is the agreement between the team that builds an API and the teams that call it.
πŸšͺAPI gateways
Many gateways import the file to set up routes, request validation and security rules.
πŸ”CI pipelines
A build step lints the file, checks for breaking changes and runs contract tests.
🎭Mocking and testing
Mock servers answer from the examples in the file, so front ends and tests do not need the real server.
πŸ› οΈDeveloper portals
A portal shows the docs, the try-it console and the SDK downloads, all from the spec.

06Types / Parts / How It Works

The parts of an OpenAPI file

PartWhat it describesExample
infoThe name, version and description of the APItitle: Shop API, version: 1.0.0
serversWhere the API liveshttps://api.example.com
pathsEach URL and the methods it supports/orders with GET and POST
parametersInputs in the path, the query, a header or a cookie?page=2, or the id in /orders/{id}
requestBodyThe shape of the data you sendA JSON order with item and quantity
responsesEach status code and the shape that comes back201 order created, 400 error
componentsShared pieces that you reuse in many placesAn Order schema, a standard Error schema
securityHow callers prove who they areAPI key in a header, OAuth2

The tools around the file

Kind of toolWhat it doesExamples (names only)
Doc viewersTurn the file into a readable site, often with a try-it buttonSwagger UI, Redoc
EditorsHelp you write and check the fileSwagger Editor, IDE plugins
Code generatorsMake clients and server stubs in many languagesOpenAPI Generator
LintersCheck style and rules (every operation has a description...)Spectral
Diff toolsFind breaking changes between two versionsopenapi-diff and similar
Mock serversAnswer fake requests from the examplesPrism and similar
Contract testersSend real requests and compare with the fileSchemathesis, Dredd and similar
πŸ“Note
Version 2.0 of the format was called the Swagger specification. Versions 3.x are called OpenAPI. Tool support differs between 3.0 and 3.1, so check what your tools can read.
VisualizerChange the contract and see who breaksSwitch rules in the spec on and off. Watch the YAML change, the six sample requests pass or fail, and see which ones worked before but are now broken for old clients.
coupon is required
quantity minimum 1
reject unknown fields
API key required
add optional field giftNote
Six sample requests (click one). Amber means it worked under version 1 and is now rejected.
openapi.yaml (excerpt, changes as you switch rules)
paths:
  /orders:
    post:
      summary: Create an order
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [item, quantity]
              properties:
                item: { type: string }
                quantity: { type: integer }
                coupon: { type: string }
      responses:
        "201": { description: Order created }
        "400": { description: Invalid request }
Selected request
POST /orders
X-API-Key: demo-key-123

{"item":"book","quantity":2,"coupon":"SAVE5"}
201 Created
The request matches the contract, so the server accepts it.
Changes compared with version 1
None yet.
Accepted now
5 of 6
sample requests
Rejected now
1
sample requests
Broken for old clients
0
worked in version 1
Breaking changes
0
tightened rules
This is version 1 of the contract. Change a rule on the left and watch the sample requests and the YAML react.

A simplified model: a real validator follows the whole JSON Schema vocabulary. The order, the key and the six requests are made-up examples for teaching.

07How to Use It / Steps / Implementation

Using OpenAPI well

  1. 1
    Pick design-first or code-first
    Design-first means you write and review the file before the code. It suits public APIs and many teams. Code-first generates the file from the code. It is quicker to start, but the contract is shaped by the code.
  2. 2
    Describe everything a caller needs
    Paths, inputs, every response (the errors too), the security scheme, and examples. A contract with only the happy path is a half contract.
  3. 3
    Reuse with components
    Define shared shapes like Order and Error once, and refer to them. Fewer copies means fewer places that can disagree.
  4. 4
    Lint it
    Run a linter in CI to enforce rules, like naming, descriptions and consistent error shapes.
  5. 5
    Check for breaking changes
    On every pull request compare the new file with the one in production. Removing a field or making an optional one required is breaking.
  6. 6
    Test the server against it
    Run contract tests so the real server and the file cannot drift apart without the build failing.
  7. 7
    Publish and version
    Publish the docs, keep old versions available, and tell clients before you retire one.
πŸ’‘Which changes are safe?
Usually safe: adding a new endpoint, adding an optional field, adding a new response field that clients can ignore. Usually breaking: removing or renaming a field, making an optional field required, tightening a limit, changing a type, or requiring a new header.
⚠️A contract nobody checks is a rumour
If the file is not tested against the server, it will slowly stop matching. Docs that lie are worse than no docs.

08Key Terms to Know

TermMeaning in easy words
OpenAPI Specification (OAS)The standard format for describing an HTTP API in a YAML or JSON file
SwaggerThe older name of the specification, and today the name of a family of tools around it
Swagger UIA web page made from the file, where you can read the docs and try calls
Path / operationA URL, and one method on it (like POST /orders)
SchemaA description of the shape of some data, using JSON Schema
ComponentsA place for shared, reusable pieces like schemas and security schemes
Security schemeHow a caller proves who they are (API key, OAuth2, HTTP bearer)
Design-firstWrite and agree the contract before writing the code
Code-firstWrite the code, then generate the contract from it
Breaking changeA change that makes requests that used to work fail
Contract testingChecking that the real server behaves as the contract says

09Pros, Cons and Trade-offs

βœ… Pros
  • One source of truth for docs, code and tests
  • Teams can work in parallel using the contract
  • Generated clients and servers save time
  • Breaking changes can be caught automatically
  • A huge ecosystem of tools
⚠️ Cons
  • The file can drift away from the server if nobody tests it
  • Large files get long and hard to read
  • Generated code can be clumsy
  • Not every behaviour fits in the format (long workflows, some rules)
  • Tool support differs between versions of the spec

Trade-offs

ChoiceWe gainWe lose
Design-firstAgreement early, parallel work, cleaner APIsSlower start and more meetings
Code-firstFast start, the file always matches the codeThe API is shaped by the code, and is reviewed late
Strict schemasBad input is caught at the edgeOld clients may break when rules tighten
Loose schemasEasy for clients to adoptMore bad data reaches your code
Generated clientsLess hand-written code, fewer typosHarder to customise, generator quirks
One big fileEverything in one placeHard to review. Split into files and merge in the build

10Common Problems and Mistakes

Common mistakes

  1. Docs that drift. The file is written once and never checked, so it slowly stops matching the server.
  2. Only the happy path. Errors, status codes and edge cases are missing, so clients guess.
  3. Making fields required by accident. Tightening a rule silently breaks old clients. Always diff before you ship.
  4. No examples. A schema alone is hard to understand. Examples also power mock servers.
  5. Copy and paste schemas. The same shape in ten places will soon be ten slightly different shapes.
  6. Treating the generator as magic. Generated code still needs review and tests.
  7. Confusing the spec with security. Describing an API key in the file does not make the server check it.

Things to watch

πŸ”€Version mismatch
Tools that read 3.0 may not understand every part of 3.1. Check your tool versions.
πŸ“Huge files
Split by area, and bundle in the build, so pull requests stay reviewable.
🧯Secrets in examples
Never put real keys or customer data in example values.
πŸ•³οΈUndocumented behaviour
If the server does something the file does not say, clients will start to depend on it.

11Real-World Examples

πŸ’³Payment and cloud APIs
Many public APIs publish an OpenAPI file so that anyone can generate a client in their own language.
πŸ—οΈPlatform teams
Internal platforms often require a spec for every service, and check it in the build.
πŸšͺGateways
Several API gateways can import a spec to create routes and validate requests.
πŸ“±Mobile apps
A mock server from the spec lets app developers build screens before the back end exists.
πŸ§ͺFuzz and property tests
Test tools read the spec and generate many odd requests to find crashes.
πŸ€–AI and automation
A clear spec helps programs and AI agents discover what an API can do and how to call it.
πŸ“Note
Product features change often. Check the current docs of the tool you use before you rely on a feature.
Mini case: a safe change in the pipeline
✍️Edit the filemake coupon required
→↓
πŸ”ŽLint + diffbreaking change found
→↓blocked
🏷️New versionor make it optional
Change Check Safe path
The new file is compared with the old one before it reaches production.

12Related Topics to Read Next

What is an API?β†’

The big picture that a contract describes.

REST, GraphQL, gRPC→

OpenAPI describes REST-style APIs. The others use their own schemas.

Error Handling and Status Codes→

Every response and error belongs in the contract.

API Versioning→

What to do when the contract has to change in a breaking way.

API Keys→

One of the security schemes you can describe in the file.

Data Formats→

JSON and its schemas are the language of the contract.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: a YAML or JSON file that describes your HTTP API: paths, inputs, outputs, errors, security.
  • βœ”Names: OpenAPI = the specification. Swagger = the old name, now the tool family (Swagger UI).
  • βœ”Gives you: docs, client libraries, server stubs, mocks, lint, diff and contract tests.
  • βœ”Design-first: write and agree the file, then code. Code-first: code, then generate the file.
  • βœ”Breaking: remove or rename a field, change a type, make something required, tighten a limit.
  • βœ”Safe: add an endpoint or an optional field.
  • βœ”Always: test the server against the file in CI, and diff the file on every pull request.
  • βœ”One line: β€œWrite the API down once, in a form that both people and programs can use.”
← Previous
Error Handling and Status Codes
Next β†’
Bulk APIs and File Upload