Tutorial · Swagger / OpenAPI · NestJS
Swagger and OpenAPI in practice – docs from code in NestJS and Express, a typed client and contract hygiene
We document the pierogi shop API with OpenAPI – in NestJS with @nestjs/swagger (CLI plugin, response DTOs, an API key in Swagger UI, URI versioning, export without a database), in Express from Zod schemas with zod-to-openapi and swagger-ui-express. From the same spec we generate a typed client and guard it in CI.
"The docs are in Confluence, but probably out of date" – everyone who has integrated with someone else's API has heard that. OpenAPI solves the problem only when the spec is generated from code or guarded by it. In this tutorial you document the pierogi shop's order API in two ways – in NestJS and in Express – and then put the spec to work: you generate a typed client and block changes in CI that would break integrations.
Prerequisites: the projects from the Express and NestJS tutorials (or your own API in one of them), HTTP basics and JSON Schema at the level of "type, required fields, enum".
- 2011 Swagger – Tony Tam creates the specification and Swagger UI for the Wordnik API
- 2015 OpenAPI Initiative – SmartBear donates the specification to a foundation under the Linux Foundation
- 2017 OpenAPI 3.0 – a new structure: `components`, `requestBody`, multiple servers
- 2021 OpenAPI 3.1 – full JSON Schema 2020-12 alignment, `type: [string, "null"]` instead of `nullable`
- 2025 OpenAPI 3.2 – streams (`itemSchema`), the `QUERY` method, response summaries
Part 1. NestJS: @nestjs/swagger
Step 1. Installation, the CLI plugin and document configuration
npm install @nestjs/swagger@11
Plugin, document configuration and bootstrap
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true,
"plugins": [
{
"name": "@nestjs/swagger",
"options": {
"introspectComments": true,
"dtoFileNameSuffix": [".dto.ts", ".query.ts", ".response.ts"]
}
}
]
}
}import { INestApplication, ValidationPipe, VersioningType } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
// Shared by main.ts and the export script, so the exported spec matches the real routes.
export function configureApp(app: INestApplication): void {
app.setGlobalPrefix('api');
app.enableVersioning({ type: VersioningType.URI, defaultVersion: '1' }); // -> /api/v1/orders
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
}
export function createOpenApiDocument(app: INestApplication) {
const config = new DocumentBuilder()
.setTitle('Pierogi API')
.setDescription("Orders for Halina's pierogi shop")
.setVersion('1.0.0')
.setLicense('Proprietary', 'https://example.org/terms')
.addApiKey({ type: 'apiKey', in: 'header', name: 'x-api-key' }, 'kitchen-key')
.addServer('http://localhost:3000', 'local')
.build();
return SwaggerModule.createDocument(app, config, {
// Stable, readable operationIds -> nice method names in generated clients.
operationIdFactory: (controllerKey, methodKey) => `${controllerKey.replace(/Controller$/, '').toLowerCase()}_${methodKey}`,
});
}import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { SwaggerModule } from '@nestjs/swagger';
import helmet from 'helmet';
import { AppModule } from './app.module';
import { configureApp, createOpenApiDocument } from './app.setup';
import type { Env } from './config/env';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = app.get<ConfigService<Env, true>>(ConfigService);
app.use(helmet());
app.enableCors({ origin: config.get('CORS_ORIGINS', { infer: true }).split(','), credentials: true });
configureApp(app);
app.enableShutdownHooks();
if (config.get('NODE_ENV', { infer: true }) !== 'production') {
SwaggerModule.setup('docs', app, () => createOpenApiDocument(app), {
jsonDocumentUrl: 'docs/openapi.json',
swaggerOptions: { persistAuthorization: true, displayOperationId: true },
});
}
await app.listen(config.get('PORT', { infer: true }));
}
void bootstrap();The key pieces:
- The CLI plugin (
pluginsinnest-cli.json) analyzes the code at compile time and adds@ApiPropertyfor you: property types, optionality (?),class-validatorconstraints (@Length→minLength/maxLength,@Matches→pattern), and withintrospectCommentsalso descriptions and examples from JSDoc comments. By default it only processes*.dto.tsand*.entity.tsfiles – that is why we add.query.tsand.response.ts. configureApp()keeps the prefix, versioning and validation in one place, used bymain.tsand by the export script. Without it the exported spec would have different paths than the running API.addApiKey(..., 'kitchen-key')registers a security scheme. The name (kitchen-key) links it with the@ApiSecurity('kitchen-key')decorator on endpoints.operationIdFactory– the default ids look likeOrdersController_place. Shorterorders_placegives readable method names in generated clients.persistAuthorization– Swagger UI keeps the entered key after a page refresh. We expose the docs only outside production (or behind authentication).
Step 2. Input and output DTOs
Swagger cannot see TypeScript interfaces at runtime, so responses are described with classes too. The domain Order stays an interface – OrderResponse has the same shape, so the controller can return it without mapping.
DTOs with documentation
import { Type } from 'class-transformer';
import {
ArrayMaxSize,
ArrayMinSize,
IsIn,
IsInt,
IsOptional,
IsString,
Length,
Matches,
Max,
MaxLength,
Min,
ValidateNested,
} from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
import { DISHES, type Dish } from '../../domain/order';
export class OrderItemDto {
@ApiProperty({ enum: DISHES, enumName: 'Dish' }) // named enum = one reusable schema
@IsIn(DISHES)
dish: Dish;
/** @example 20 */
@IsInt()
@Min(1)
@Max(100)
quantity: number;
}
export class CreateOrderDto {
/** @example "Zdzisław" */
@IsString()
@Length(2, 80)
customerName: string;
/** Called when the order is ready. @example "600 100 200" */
@Matches(/^\+?[0-9 ]{9,15}$/, { message: 'phone must be a valid phone number' })
phone: string;
@ValidateNested({ each: true })
@Type(() => OrderItemDto) // without it nested objects stay plain and are NOT validated
@ArrayMinSize(1)
@ArrayMaxSize(10)
items: OrderItemDto[];
/** Allergies, gate code, anything the kitchen should know. */
@IsOptional()
@IsString()
@MaxLength(500)
note?: string;
}import { Type } from 'class-transformer';
import { IsIn, IsInt, IsOptional, Max, Min } from 'class-validator';
import { ApiPropertyOptional } from '@nestjs/swagger';
import { ORDER_STATUSES, type OrderStatus } from '../../domain/order';
export class ListOrdersQuery {
@ApiPropertyOptional({ enum: ORDER_STATUSES, enumName: 'OrderStatus' })
@IsOptional()
@IsIn(ORDER_STATUSES)
status?: OrderStatus;
/** Page size. */
@IsOptional()
@Type(() => Number) // query params arrive as strings
@IsInt()
@Min(1)
@Max(100)
limit: number = 20;
}import { ApiProperty } from '@nestjs/swagger';
import { IsIn } from 'class-validator';
import { ORDER_STATUSES, type OrderStatus } from '../../domain/order';
export class UpdateStatusDto {
@ApiProperty({ enum: ORDER_STATUSES, enumName: 'OrderStatus' })
@IsIn(ORDER_STATUSES)
status: OrderStatus;
}import { ApiProperty } from '@nestjs/swagger';
import { DISHES, type Dish, ORDER_STATUSES, type OrderStatus } from '../../domain/order';
// Response shapes need classes too – Swagger cannot read TypeScript interfaces at runtime.
export class OrderItemResponse {
@ApiProperty({ enum: DISHES, enumName: 'Dish' })
dish: Dish;
/** @example 20 */
quantity: number;
}
export class OrderResponse {
/** @example "6b08c0da0e1dd661e68c6b93" */
id: string;
/** @example "Zdzisław" */
customerName: string;
/** Called when the order is ready. @example "600 100 200" */
phone: string;
items: OrderItemResponse[];
note?: string;
@ApiProperty({ enum: ORDER_STATUSES, enumName: 'OrderStatus' })
status: OrderStatus;
createdAt: Date;
}
export class OrderListResponse {
items: OrderResponse[];
}
export class PageMeta {
/** @example 20 */
limit: number;
}
export class OrderPageResponse {
data: OrderResponse[];
meta: PageMeta;
}
export class ApiErrorResponse {
/** @example 422 */
statusCode: number;
/** Machine-readable error code. @example "TOO_MANY_PIEROGI" */
code?: string;
@ApiProperty({ oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }] })
message: string | string[];
}enumNameturns a repeated list of values into one component (Dish,OrderStatus). Client generators produce a single type instead of five copies of a union./** ... @example ... */comments end up in the spec thanks tointrospectComments– documentation lives next to the field it describes.ApiErrorResponsedescribes Nest's error format (messageis either a string or an array of validation messages) and domain errors (code).
The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Step 3. The controller: responses, security and versions
- Step 4. Exporting the spec without a database
- Part 2. Express: OpenAPI from Zod schemas
- Step 5. The path registry and Swagger UI
- Step 6. Export, lint and change control in CI
- Part 3. A typed client from the contract
- Step 7. openapi-typescript and openapi-fetch
- Documentation hygiene – a checklist
- Common mistakes
- Check yourself
- What's next