Skip to content

15 min read

OpenAPI vs Swagger: how to document an API

In one sentence: OpenAPI is a standard format for describing an API in a JSON or YAML document: every route, what it receives and what it answers, including when it fails. Swagger is its old name, and today the name of some tools that read it. If the document comes from the same schemas that validate, it doesn't go out of date.

What you will learn

  • Explain what OpenAPI is, what Swagger is and why people mix them up.
  • Read an OpenAPI document and search it with jq.
  • Generate the contract from the Zod schemas with @hono/zod-openapi and publish it, with its page at /docs.
  • Tell code-first from contract-first, and know what the contract checks and what it doesn't.

Before you start, read: 04-versioning.md

The delivery company that is going to use the shop’s API writes to Ana: “What fields does an order have? What do you answer if it doesn’t exist? Is the price in euros?” Ana answers by email. A week later, whoever is building the mobile app asks the same thing.

Imagine that, to avoid repeating herself, Ana writes a README (the text file that explains a project) with every route, back in the days of version 1, with price in euros. In lesson 4, “Versioning,” version 2 switched to priceCents, and nobody touched the README. Now it lies, and nobody notices: nothing checks that a text written by hand says the same as the code.

Besides, a README is only read by people: no program can use it to check that the API does what it promises. You need a description that both people and programs read, and that comes from the code itself.

The analogy

Think of the blueprints of a building. They use symbols that any architect, electrician or plumber understands, and with them the plumber knows where the pipes go without calling the architect.

An OpenAPI document is the blueprint of an API: in a format everyone knows, it says which routes there are, what data goes in and what comes out. Like a blueprint, it can be drawn before building or taken from what is already built.

Where the analogy breaks down

  • A blueprint drawn by hand may not match the building. The one in this lesson is generated from the code: what it says about the requests is always true; about the responses, not entirely.
  • You can’t turn on a tap with a blueprint. With the documentation page you can: it sends real requests to the API.

This is what the shop’s API will say, by the end of the lesson, about GET /v2/products/{id}. jq, from lesson 8 of Phase 3, pulls that part out of the document:

Ventana de terminal
curl -s localhost:3000/v2/openapi.json | jq '.paths["/products/{id}"].get'
{
"tags": [
"Products"
],
"summary": "A product",
"parameters": [
{
"schema": {
"type": "integer",
"example": 2
},
"required": true,
"name": "id",
"in": "path"
}
],
"responses": {
"200": {
"description": "The product",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Product"
}
}
}
},
"404": {
"description": "No such product",
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
}
},
"422": {
"description": "The data is not valid: \"errors\" says what is wrong",
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
}
}
}
}

Without reading the code, you know what the delivery company was asking:

  • parameters: the route takes an id ("in": "path"), a whole number and required.
  • responses: every Status codeA three-digit number at the start of every HTTP response that sums up what happened. 200 means “all good,” 404 “that doesn’t exist” and 400 “your request is malformed.”Go to definition that can come out: a 200 with a Product, or a 404 and a 422 with a Problem, the error format from lesson 2.
  • $ref: “the shape is somewhere else in the document.” Product is described once, in components, and every route uses it.

This document follows OpenAPIA standard format for describing an API in a JSON or YAML document: each route, the data it receives and what it answers, including when it fails. People read it, and so do programs such as documentation pages and code generators. It used to be called Swagger.Go to definition, a standard format for describing HTTPHTTP stands for HyperText Transfer Protocol.The protocol of the web. It defines how a client asks a server for pages, images and other files, and how the server answers.Go to definition APIs. It’s written in JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition or in YAML (another text format, with indentation instead of braces). The version the project uses is 3.1, from 2021; 3.2 came out in September 2025.

That document is the API’s API contractAPI stands for Application Programming Interface.What an API promises to whoever uses it: which routes it has, which data each one accepts and what it answers, including when something goes wrong. When it’s written in a format like OpenAPI, programs can read it too and check whether it’s kept.Go to definition: what it promises to whoever uses it.

OpenAPI and Swagger: one format, two names

Section titled “OpenAPI and Swagger: one format, two names”

You’ll see “Swagger” everywhere, sometimes as if it were the same as OpenAPI. It was:

  1. 2010: Tony Tam, at the online dictionary Wordnik, creates Swagger: a format for describing its API and tools that read it.
  2. 2015: SmartBear buys Swagger and donates the format to the new OpenAPI Initiative, part of the Linux Foundation.
  3. 2016: the format is renamed the OpenAPI Specification. Swagger 2.0 was the last version with the old name.

Since then, OpenAPI is the format and Swagger is a brand of tools from SmartBear: Swagger UI (a page that shows the document), Swagger Editor and Swagger Codegen.

If you read… It means…
A swagger.json with "swagger": "2.0" A document in the old version of the format
An openapi.json with "openapi": "3.1.0" A document in today’s format (3.0, 3.1 or 3.2)
“We have Swagger at /swagger” A Swagger UI page, which reads an OpenAPI document

Code-first: the contract comes from the schemas

Section titled “Code-first: the contract comes from the schemas”

The document can be written by hand or generated from the code. The shop generates it, and that’s called code-first: it comes from the same Zod SchemaThe description of what some data must look like: which fields it has, whether each one is a number or text, and which values are accepted. A program compares the incoming data with it and says whether it matches or what’s wrong.Go to definition that have been validating since lesson 7 of Phase 3, thanks to @hono/zod-openapi. This is how src/schemas.ts starts:

src/schemas.ts
// What arrives in the body. .openapi('Name') gives it a name in the documentation, and example is
// a sample value that the /docs page fills in when trying a route.
export const newOrderSchema = z
.object({
productId: z
.number({ error: 'Must be a number' })
.int('Must be a whole number')
.openapi({ example: 1 }),
quantity: z
.number({ error: 'Must be a number' })
.int('Must be a whole number')
.min(1, 'At least 1')
.max(10, 'At most 10 per order')
.openapi({ example: 2 }),
})
.openapi('NewOrder');
  • import { z } from '@hono/zod-openapi', at the top of the file: Zod’s usual z, with one more method, .openapi().
  • .openapi({ example: 2 }) adds something that is only for the document: a sample value.
  • .openapi('NewOrder') gives the schema a name, the one that shows up in components and in the $refs.

The schema used to be called orderSchema; now it’s newOrderSchema, because the contract also describes what goes out:

src/schemas.ts
// What the API answers. Zod doesn't check the responses: these schemas are for the contract, so
// that whoever uses the API knows what they're going to get.
export const productSchema = z
.object({
id: z.number().int().openapi({ example: 2 }),
name: z.string().openapi({ example: 'Mug' }),
priceCents: z.number().int().openapi({ example: 850 }),
})
.openapi('Product');
export const orderSchema = z
.object({
id: z.number().int().openapi({ example: 7 }),
productId: z.number().int().openapi({ example: 1 }),
quantity: z.number().int().openapi({ example: 2 }),
status: z.enum(['pending', 'paid', 'shipped', 'cancelled']),
})
.openapi('Order');

z.enum([…]) means “one of these texts.” Look at the comment: these schemas don’t check anything while the program runs.

Every route, with what it receives and what it answers

Section titled “Every route, with what it receives and what it answers”

Each route is described in a new file, src/contract.ts. This is the one for getting a product:

src/contract.ts
export const getProduct = createRoute({
method: 'get',
path: '/products/{id}',
tags: ['Products'],
summary: 'A product',
request: { params: idSchema },
responses: {
200: asJson(productSchema, 'The product'),
404: withProblem('No such product'),
422: invalidData,
},
});
  • createRoute describes a route without the code that handles it: what it receives (request) and what it answers (responses).
  • path: '/products/{id}' writes the parameter with braces, the OpenAPI way, not with :id.
  • tags groups the routes on the documentation page; summary is the route’s name there.
  • request: { params: idSchema }: the id is validated with idSchema, the one from Phase 3.

asJson and withProblem are two helper FunctionA named piece of code that takes some data, does something with it and returns a result. It’s written once and used as many times as needed.Go to definition, from the top of the file:

src/contract.ts
// Pieces that repeat: a response in JSON and an error response (Problem Details).
function asJson<Schema extends z.ZodType>(schema: Schema, description: string) {
return { description, content: { 'application/json': { schema } } };
}
function withProblem(description: string) {
return { description, content: { 'application/problem+json': { schema: problemSchema } } };
}
// A required JSON body: without required, a request without a body wouldn't be validated.
function jsonBody<Schema extends z.ZodType>(schema: Schema) {
return { required: true, content: { 'application/json': { schema } } };
}
const invalidData = withProblem('The data is not valid: "errors" says what is wrong');
const noToken = withProblem('The admin token is missing, or it is not valid');
const withLocation = {
Location: { description: 'The URL of the new resource', schema: { type: 'string' as const } },
};

withProblem says the error goes as application/problem+json. jsonBody describes a required JSON Body (of a request or response)The data an HTTP message carries after the blank line that ends the headers, such as the fields of a form, some JSON or an image. The Content-Type header says what format it’s in, and Content-Length how many bytes it takes up.Go to definition. This is how the route that creates a product uses it:

src/contract.ts
// security says in the documentation that a token is needed; middleware checks it before
// validating the body, as before.
export const createProduct = createRoute({
method: 'post',
path: '/products',
tags: ['Products'],
summary: 'Creates a product',
security: [{ Bearer: [] }],
middleware: [adminOnly] as const,
request: { body: jsonBody(newProductSchema) },
responses: {
201: { ...asJson(productSchema, 'The created product'), headers: withLocation },
401: noToken,
422: invalidData,
},
});
  • security announces in the document that the route asks for a token. adminOnly checks it, and middleware puts it in front, before the body is validated.
  • headers: withLocation: the 201 carries the Location header, and the contract says so.

OpenAPIHono validates every route and writes it down

Section titled “OpenAPIHono validates every route and writes it down”

In src/v2.ts, version 2 stops being a Hono and becomes an OpenAPIHono:

src/v2.ts
// defaultHook: what's answered if the request doesn't match the schema. The same 422 as always.
export const v2 = new OpenAPIHono({ defaultHook: ifInvalid });
// How the token is sent, for the documentation: Authorization: Bearer <token>.
v2.openAPIRegistry.registerComponent('securitySchemes', 'Bearer', {
type: 'http',
scheme: 'bearer',
});
  • OpenAPIHono is a Hono that also writes every route down in the document.
  • defaultHook is what answers if the request doesn’t match the schema. ifInvalid is the function that used to live inside validate, now with a name, in src/middleware/validate.ts. Without it, OpenAPIHono would answer a 400 with the whole Zod error; with it, the usual 422.
  • registerComponent(…) says how the token is sent, Authorization: Bearer <token> (lesson 4 of Phase 2): it’s the Bearer in the security from before.

And every route goes from v2.get(…) to v2.openapi(…):

src/v2.ts
// TypeScript checks each response against the contract: a 404 that wasn't in it, or a c.json
// without the status code, wouldn't compile.
v2.openapi(contract.getProduct, (c) => {
const product = findProduct(c.req.valid('param').id);
if (!product) return httpProblem(c, 404, 'No such product');
return c.json(product, 200);
});

v2.openapi(contract.getProduct, …) registers the route, validates the request with the contract and writes it down in the document. The function is the same as before, except that c.json(product, 200) carries the status code. That’s needed for what comes next.

TypeScript checks that the code keeps the contract

Section titled “TypeScript checks that the code keeps the contract”

@hono/zod-openapi gives TypeScript the contract of every route. If the function returns a status code that isn’t in responses, npm run check fails. You’ll cause it in “Try it,” by removing the 404 from getProduct’s contract. The last line of the error:

Type '404' is not assignable to type '422'.

TypeScript looks in the contract for a status code that matches the 404 from httpProblem, and there isn’t one. A c.json(product) without a status code fails too, and a product without priceCents doesn’t compile. What the contract promises, the code can’t forget.

There are two holes:

  • Zod doesn’t validate the responses, only what comes in. What goes out is only reviewed by TypeScript, before running.
  • TypeScript doesn’t mind an extra field. A product with an extra field, like what it cost the shop, compiles, and reaches the ClientThe program that starts the conversation by asking another program, the server, for something. Your browser is a client.Go to definition without the contract saying so.

They’re closed by tests that look at the real responses, like the project’s, which compare the whole product.

The document and its page: /v2/openapi.json and /docs

Section titled “The document and its page: /v2/openapi.json and /docs”

The document is published on one more route, in src/app.ts:

src/app.ts
// Version 2's contract, in OpenAPI 3.1: OpenAPIHono writes it from v2's routes and schemas.
// servers says that the document's routes (/products) hang from /v2.
app.get('/v2/openapi.json', (c) =>
c.json(
v2.getOpenAPI31Document({
openapi: '3.1.0',
info: {
title: "API for Ana and Luis's shop",
version: '2.0.0',
description: "The shop's products and orders. Prices are in cents.",
},
servers: [{ url: '/v2' }],
}),
),
);
  • getOpenAPI31Document writes the document with v2’s routes every time someone asks for it: it’s always the one from the running code.
  • info is the API’s ID card, and servers says that its routes, like /products, hang from /v2.

For people, below it, a page:

src/app.ts
// A page that reads that contract and shows it: each route, its data and a button to try it.
// The browser loads its code from a CDN: with the exact version, like the npm packages.
app.get(
'/docs',
Scalar({
url: '/v2/openapi.json',
pageTitle: 'Shop API',
cdn: 'https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.73.0',
}),
);

Scalar answers at /docs with an HTML page that, in the browser, downloads /v2/openapi.json and shows it, with a button to try every route. The classic alternative is Swagger UI.

The browser downloads the page’s code from jsDelivr, a CDNCDN stands for Content Delivery Network.A network of servers spread around the world that serves a website from the one closest to each user, so the round trip is short. example.com sits behind Cloudflare’s.Go to definition. That’s why cdn carries the exact version, like the npm packages: without it, every visit would load the latest one, code nobody has reviewed. Besides, jsDelivr serves an exact version with Cache-Control: immutable, the cache that never asks.

The other way is contract-first: the document is written, agreed with whoever is going to use the API, and then the code is written.

Code-first Contract-first
What’s written first The code; the contract comes from it The contract; the code keeps it
For A single source: what comes in can’t drift Clients start earlier, and the design is discussed without code
Against The design is decided while coding Contract and code can drift apart if nothing compares them
Fits when The API already exists and a single team builds it Several teams start at the same time

The shop already had its API: code-first fits.

Since programs read it, the contract is good for more than a page:

  • Clients: openapi-typescript takes its TypeScript types from it, and OpenAPI Generator writes clients in dozens of languages.
  • Fake servers (mocks): Prism answers what the contract says before the API exists.
  • Contract tests: Schemathesis sends hundreds of generated requests and warns you if a response doesn’t match its schema. It closes the first of the two holes from before.

The goal: that the delivery company can use the API without writing to you. You’ll publish the contract and its page, place an order from it and break the contract to see who warns you.

You’re still in ~/backend-course/phase-3/shop-api, with the API from lesson 4. This lesson touches almost every v2 route, so download its folder next to your project: from ~/backend-course/phase-3, curl -O https://backenddesdecero.com/practicas/shop-api/14-openapi.tar.gz and tar -xzf 14-openapi.tar.gz.

1. Install the two packages

Ventana de terminal
npm install @hono/zod-openapi@1.6.3 @scalar/hono-api-reference@0.12.10

What you will see:

added 13 packages, and audited 35 packages in 4s
6 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities

With the exact version, as always. This lesson’s outputs are from Node 26; your timings, ids and dates will be different.

Then, in your project:

  1. Copy from the folder src/schemas.ts, src/contract.ts and src/problems.ts, and read them: the routes you haven’t seen follow the same pattern. In problems.ts, problem and httpProblem now receive the exact status code (Code), so that TypeScript can compare it with the contract.
  2. src/middleware/validate.ts: move the function out of validate into ifInvalid, as in the folder.
  3. src/v2.ts: copy the folder’s imports and replace new Hono() with the code above. Every v2.get(…), v2.post(…)… becomes v2.openapi(contract.…, …), without validate or adminOnly, and every c.json(…) carries its status code.
  4. src/app.ts: import Scalar from @scalar/hono-api-reference and add the two routes, after app.route('/v2', v2).
  5. test/openapi.test.ts: copy it; these are this lesson’s tests.

2. Check the types and the tests

Ventana de terminal
npm run check
npm test | tail -8

What you will see:

> shop-api@1.0.0 check
> tsc --noEmit
ℹ tests 51
ℹ suites 0
ℹ pass 51
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 953.2379

npm run check says nothing but its name: no errors. tail -8 keeps the summary of npm test: 51 tests, none fails. If npm run check fails in v2.ts, look for a c.json without its status code or a route that still uses validate.

Start the server in one terminal with npm run dev and open another.

3. The pieces of the document

Ventana de terminal
curl -s localhost:3000/v2/openapi.json | jq 'keys'
curl -s localhost:3000/v2/openapi.json | jq -c '{openapi, info, servers}'

What you will see:

[
"components",
"info",
"openapi",
"paths",
"servers",
"webhooks"
]
{"openapi":"3.1.0","info":{"title":"API for Ana and Luis's shop","version":"2.0.0","description":"The shop's products and orders. Prices are in cents."},"servers":[{"url":"/v2"}]}

keys lists the pieces of the document, in alphabetical order:

  • openapi, info and servers: the format’s version and what you wrote in app.ts.
  • paths: the routes.
  • components: what the $refs use.
  • webhooks: the requests the API would send to others, empty until lesson 7.

If curl prints nothing, the server isn’t running. If keys gives "detail", "status", "title" and "type", you got an error, not the document: most likely a 404, because the route is missing in app.ts.

4. Zod's rules, in the document

Ventana de terminal
curl -s localhost:3000/v2/openapi.json | jq '.components.schemas.NewOrder'

What you will see:

{
"type": "object",
"properties": {
"productId": {
"type": "integer",
"example": 1
},
"quantity": {
"type": "integer",
"minimum": 1,
"maximum": 10,
"example": 2
}
},
"required": [
"productId",
"quantity"
]
}

Look at quantity: integer, minimum: 1 and maximum: 10 are your .int(), .min(1) and .max(10). And required comes from no field being .optional(). Nobody has written it twice.

5. The page, inside

Ventana de terminal
curl -s localhost:3000/docs | tail -14

What you will see:

<body>
<div id="app"></div>
<!-- Load the Script -->
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.73.0"></script>
<!-- Initialize the Scalar API Reference -->
<script type="text/javascript">
Scalar.createApiReference('#app', {
"_integration": "hono",
"url": "/v2/openapi.json"
})
</script>
</body>
</html>

tail -14 keeps the last 14 lines. The page is almost empty: a div and two scripts, one that downloads Scalar and another that tells it where the contract is. The browser draws the rest.

Open http://localhost:3000/docs in the browser. It needs the internet: it downloads its code from jsDelivr and its fonts from Scalar. This is what you see in Chrome with Scalar 1.73.0:

  • On the left, a search box and the groups from your tags, “Products” and “Orders”, with their routes. “Models” are your named schemas.
  • In the center, v2.0.0, OpenAPI 3.1.0, “API for Ana and Luis’s shop” and your description. “Download OpenAPI Document” downloads the contract.
  • On the right, “Server” says http://localhost:3000/v2, the document’s servers.

Go to “Orders” and to “Creates an order”: you’ll see the body, “NewOrder”, with each field, its type and its limits. Press Test Request: a window opens with the POST, the URL and the body filled in with your examples, {"productId": 1, "quantity": 2}. Press Send: on the right, 201 Created and the new order.

Change quantity to 11 and send it again: 422 Unprocessable Content and your Problem Details, with “At most 10 per order”. The page sends real requests.

In src/contract.ts, in getProduct, delete the 404 line and save. The route, in v2.ts, still returns a 404 when the product doesn’t exist.

6. A status code the contract doesn't have

Ventana de terminal
npx tsc --noEmit

What you will see:

src/v2.ts:43:33 - error TS2345: Argument of type '(c: Context<any, "/products/:id", { in: { param: { id: unknown; }; }; out: { param: { id: number; }; }; }>) => JSONRespondReturn<...> | JSONRespondReturn<...>' is not assignable to parameter of type 'Handler<any, "/products/:id", { in: { param: { id: unknown; }; }; out: { param: { id: number; }; }; }, MaybePromise<RouteConfigToTypedResponse<{ method: "get"; path: "/products/{id}"; tags: string[]; summary: string; request: { params: ZodObject<{ id: ZodCoercedNumber<unknown>; }, $strip>; }; responses: { ...; }; } ...'.
Type 'JSONRespondReturn<Product, 200> | JSONRespondReturn<...>' is not assignable to type 'MaybePromise<RouteConfigToTypedResponse<{ method: "get"; path: "/products/{id}"; tags: string[]; summary: string; request: { params: ZodObject<{ id: ZodCoercedNumber<unknown>; }, $strip>; }; responses: { ...; }; } & { ...; }>>'.
Type 'JSONRespondReturn<Problem & { status: 404; }, 404>' is not assignable to type 'MaybePromise<RouteConfigToTypedResponse<{ method: "get"; path: "/products/{id}"; tags: string[]; summary: string; request: { params: ZodObject<{ id: ZodCoercedNumber<unknown>; }, $strip>; }; responses: { ...; }; } & { ...; }>>'.
Type 'JSONRespondReturn<Problem & { status: 404; }, 404>' is not assignable to type 'TypedResponse<{ type: string; title: string; status: number; detail?: string | undefined; instance?: string | undefined; errors?: { field: string; problem: string; }[] | undefined; }, 422, "json">'.
Types of property '_status' are incompatible.
Type '404' is not assignable to type '422'.
43 v2.openapi(contract.getProduct, (c) => {
~~~~~~~~
Found 1 error in src/v2.ts:43

It’s long, and it’s read from the bottom up. The last line is the cause: the route returns a 404, and the contract only allows the 200 and the 422.

npx tsc --noEmit is what npm run check does. 43:33 is the line and the column in src/v2.ts; in your file they may be different. npm run dev wouldn’t have complained: Node doesn’t look at the types. Put the 404 back.

Challenge: the delivery company wants to know which status codes cancelling an order can answer, and what each one means. Find out without opening the code, only with the contract and jq.Show answer

The responses of POST /orders/{id}/cancellation are in paths, under post. keys gives their status codes, and .description, what one of them means:

Ventana de terminal
curl -s localhost:3000/v2/openapi.json | jq '.paths["/orders/{id}/cancellation"].post.responses | keys'
curl -s localhost:3000/v2/openapi.json | jq -r '.paths["/orders/{id}/cancellation"].post.responses["409"].description'
[
"200",
"404",
"409",
"422"
]
The order is already shipped

200 if it’s cancelled, 404 if the order doesn’t exist, 422 if the id isn’t a number and 409 if it has already left. -r prints the text without quotes.

  • Big APIs publish their contract. GitHub, in github/rest-api-description, and Stripe, in stripe/openapi.
  • A /swagger or /api-docs address with a page full of colored routes: Swagger UI reading an OpenAPI document.
  • Postman, Insomnia and Bruno, programs for trying out APIs, import an OpenAPI document and create all its requests at once.
  • Writing the documentation apart from the code. It goes out of date without anyone noticing, like the README at the start.
  • Forgetting required: true on the body. Without it, a request without a body isn’t validated: removing it from the shop, a PATCH /v2/orders/25 without a body answers {"id":25,"productId":2,"status":"pending"}. The order has lost its quantity.
  • A parameter with z.coerce without its .openapi(). z.coerce accepts anything, and the document doesn’t know what type it is. Without .openapi({ type: 'integer', param: { required: true } }), the id comes out as "type": ["integer", "null"] and "required": false.
  • Mixing up the versions. A swagger.json with "swagger": "2.0" is in the old format: check which version a tool accepts before handing it over.
  • OpenAPI is a standard format for describing an API: routes, parameters, bodies and responses, the error ones too. Swagger was its name until 2016, and today it’s a brand of tools.
  • The document is the API’s contract: people read it, on pages like /docs, and so do programs, which generate clients, fake servers and tests.
  • Code-first generates the contract from the code; contract-first writes it first. The shop generates it from the schemas that validate, so it doesn’t go out of date.
  • npm run check fails if a route answers a status code or a shape that its contract doesn’t have. What goes out isn’t checked while running, and neither is an extra field: that’s what tests are for.
A teammate tells you: “Our API doesn’t use OpenAPI, it uses Swagger: look, we have Swagger UI at /swagger.” What do you answer?

The mobile app wants to know what the API answers if it changes the quantity of an order that’s already paid. Where can it look without asking you?

You change newOrderSchema so that the quantity allows up to 20. What do you have to do for the documentation to say so?

In the route for getting a product, a teammate adds a return with a 403 that isn’t in the contract’s responses. What happens?

By mistake, the route for getting a product also returns what it cost the shop. The output schema doesn’t have that field. Who stops it?

You’re going to build a new API for another company’s app, and they want to start coding right away, at the same time as you. Which approach fits best?

phase-4 · lesson 5/9