Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 42 ยท Building Real APIs

OpenAPI and Swagger Docs

Document a NestJS API with @nestjs/swagger: DocumentBuilder, ApiProperty, the CLI schema plugin, versioned docs, client generation, and how the spec is built.

An API is only useful if other people can learn how to call it. OpenAPI is a standard, machine-readable description of an HTTP API: its paths, methods, parameters, request bodies, responses and security. Swagger UI is a web page that reads such a description and turns it into interactive documentation with a "Try it out" button.

Nest has an official package, @nestjs/swagger, that builds the OpenAPI document from the code you already wrote: your controllers, your route decorators and your DTO classes. You add a few decorators (or a build plugin that adds them for you), and the docs stay in sync with the code instead of drifting away from it.

The real package needs Node and npm, so the Nest snippets below are read-only. The runnable parts are stand-ins that show what the package does at its core: collect metadata from routes and turn it into an OpenAPI JSON document, then turn that document into something useful.

One spec, many uses

Docs Swagger UI for humans.
Clients Generate typed SDKs.
Tests Check responses against it.
Tools Gateways and mocks read it.

The OpenAPI document is JSON or YAML.

1 / 2

Setting it up

Install @nestjs/swagger, then build and serve the document in main.ts after the app is created:

TypeScript
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const config = new DocumentBuilder()
    .setTitle('Todo API')
    .setDescription('Create and manage todos')
    .setVersion('1.0')
    .addBearerAuth()
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('docs', app, document);

  await app.listen(3000);
}
bootstrap();

DocumentBuilder sets the global parts: title, version, servers, security schemes. createDocument walks every controller in the app and produces the paths. setup('docs', ...) serves Swagger UI at /docs and the raw JSON at /docs-json, which is the file other tools consume.

Describing routes with decorators

Out of the box Nest knows the path, the HTTP method and the parameters. Decorators add the human parts:

TypeScript
@ApiTags('todos')
@ApiBearerAuth()
@Controller('todos')
export class TodosController {
  @Post()
  @ApiOperation({ summary: 'Create a todo' })
  @ApiCreatedResponse({ type: TodoDto, description: 'The created todo' })
  @ApiBadRequestResponse({ description: 'Validation failed' })
  create(@Body() dto: CreateTodoDto): TodoDto {
    return this.todos.create(dto);
  }

  @Get(':id')
  @ApiOkResponse({ type: TodoDto })
  @ApiNotFoundResponse({ description: 'No todo with that id' })
  @ApiParam({ name: 'id', type: Number })
  findOne(@Param('id', ParseIntPipe) id: number): TodoDto {
    return this.todos.findOne(id);
  }
}

@ApiTags groups operations in the UI, @ApiOperation gives each a summary, and the @Api...Response decorators list the status codes a client can expect. Document the error responses too: they are half of what a client developer needs. @ApiBearerAuth() marks the routes as requiring the scheme you registered with addBearerAuth(), matching the JWT guard.

Describing DTOs

Request and response bodies are classes, and TypeScript types disappear at runtime, so Swagger cannot see your fields unless something records them. @ApiProperty does that:

TypeScript
export class CreateTodoDto {
  @ApiProperty({ example: 'Buy milk', maxLength: 100 })
  @IsString()
  @MaxLength(100)
  title: string;

  @ApiPropertyOptional({ default: false })
  @IsOptional()
  @IsBoolean()
  done?: boolean;
}

The class-validator decorators from Pipes and Validation and the @ApiProperty decorators describe the same fields twice, which is noisy. That is what the plugin is for.

The CLI plugin

Add the Swagger plugin to nest-cli.json and the compiler inspects your classes at build time:

JSON
{
  "compilerOptions": {
    "plugins": ["@nestjs/swagger"]
  }
}

With the plugin on, you no longer need @ApiProperty() on every field. It reads the property types, optionality (done?), enums, defaults and many class-validator decorators (such as @MaxLength(100)) and fills in the schema. It can also turn doc comments above a property into descriptions. You keep explicit @ApiProperty only for what types cannot express, such as an example or a tricky union. The plugin works through the Nest CLI build, so a custom build setup needs extra configuration.

One practical rule: use separate classes for input and output. CreateTodoDto (what a client may send) and TodoDto (what the API returns) have different fields, and documenting them separately keeps secrets such as passwordHash out of the response schema. Helpers like PartialType and OmitType from @nestjs/swagger (not from @nestjs/mapped-types) derive variants such as UpdateTodoDto while keeping the Swagger metadata.

Versioned documentation

If you use URI versioning, you probably want one document per version, so v1 clients are not confused by v2 routes. createDocument accepts an include list of modules, so you can build two documents and mount each at its own path:

TypeScript
const v1 = SwaggerModule.createDocument(app, v1Config, { include: [TodosV1Module] });
SwaggerModule.setup('docs/v1', app, v1);

const v2 = SwaggerModule.createDocument(app, v2Config, { include: [TodosV2Module] });
SwaggerModule.setup('docs/v2', app, v2);

Each setup call serves its own UI and JSON. You can also keep the generated JSON in your repository and diff it in code review: an unexpected change in the spec is often a breaking change in the API.

Generating clients

Because the spec is machine-readable, other tools can generate code from it. Typical options are openapi-generator, openapi-typescript and orval, which produce typed SDKs, fetch wrappers or React Query hooks. A common workflow is to export docs-json during CI, run the generator, and publish the client as a package, so frontend teams never hand-write request code.

Generated clients are only as good as the spec. Missing response types or undocumented error cases show up as any or missing branches in the client, which is a good reason to be thorough with the decorators.

Stand-in: from route metadata to an OpenAPI document

@nestjs/swagger works because decorators record metadata on classes, and createDocument later reads that metadata and builds JSON. The stand-in below does the same thing with plain objects: a route list with metadata in, an OpenAPI 3.0 document out. It is not the real package, but the structure of the output (paths, operations, components.schemas, $ref) is the real OpenAPI shape.

JS Build an OpenAPI document from metadata

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the conversion :id to : Nest routes use colon parameters, while OpenAPI uses curly braces, and the real package performs this translation for you. Notice too that DTO classes become entries under components.schemas and the operations point at them with $ref, so one schema is defined once and reused by every route that mentions it.

Stand-in: a client generated from the document

The last step of the chain is to turn the spec into code. This stand-in reads the document and creates a small client object with one function per operation. A fake fetch records the request so the output is deterministic; no network is involved. Real generators produce typed code, but the idea is the same.

JS Generate a tiny client from the spec

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The URL for "a b" shows why generators encode path parameters. The takeaway is that a good spec removes hand-written request code on the client side entirely.

Practical advice

  • Protect the docs in production if the API is private. Serve Swagger UI only in non-production environments, or put it behind authentication.
  • Document errors, not only successes. @ApiBadRequestResponse, @ApiUnauthorizedResponse and friends cost one line each.
  • Add examples. A realistic example on a property is the fastest way for a reader to understand a field.
  • Keep the spec honest. If the code and decorators disagree (a decorator says 200, the handler returns 201), the docs are wrong. Treat spec changes like code: review them and, for public APIs, diff them in CI.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does @nestjs/swagger need @ApiProperty (or the CLI plugin) for DTO fields?

    Classes keep their property names only if something records them. The decorators, or the plugin at compile time, store the field types and options that createDocument reads later.
  2. 2. What does the SwaggerModule.setup('docs', app, document) call do?

    setup mounts the interactive UI and exposes the JSON that other tools can download. It does not validate requests or generate clients.
  3. 3. How do you publish separate documentation for API v1 and v2?

    createDocument accepts include with the modules of a version, so you can build and serve a document for each.
  4. 4. Which is a good reason to use separate input and output DTO classes in the docs?

    Requests and responses usually differ. Separate classes document each accurately and avoid leaking internal fields.

Summary

  • OpenAPI describes an HTTP API in JSON; Swagger UI renders it, and @nestjs/swagger builds it from your controllers and DTOs.
  • DocumentBuilder sets title, version and security; createDocument collects routes; SwaggerModule.setup serves the UI and the JSON.
  • Use @ApiTags, @ApiOperation and @Api...Response decorators for routes, and @ApiProperty for DTO fields; the CLI plugin infers most of them.
  • Use separate input and output DTOs, and PartialType and OmitType from @nestjs/swagger to derive variants.
  • Build one document per API version with include, and generate typed clients from the exported JSON.
  • Document error responses and keep the spec reviewed like code.

Continue with Caching, Throttling and Scheduling to make your API faster and safer.