Bird
Raised Fist0
NestJSframework~15 mins

Swagger API documentation in NestJS - Deep Dive

Choose your learning style10 modes available
Overview - Swagger API documentation
What is it?
Swagger API documentation is a way to describe and visualize your web API so that anyone can understand how to use it. It automatically generates a user-friendly webpage showing all the API endpoints, what data they expect, and what they return. In NestJS, Swagger helps you create this documentation easily by using decorators and configuration. This makes it simple for developers and clients to explore and test your API without guessing.
Why it matters
Without Swagger API documentation, developers must read code or guess how to use an API, which wastes time and causes errors. Swagger solves this by providing clear, interactive documentation that updates automatically as the API changes. This improves communication, speeds up development, and reduces bugs in real projects. It also helps teams onboard new members faster and supports automated testing and client generation.
Where it fits
Before learning Swagger API documentation, you should understand basic NestJS concepts like controllers, routes, and decorators. After mastering Swagger, you can explore advanced API design, security with OAuth or JWT, and automated client SDK generation. Swagger fits into the API development workflow as the bridge between backend code and frontend or external users.
Mental Model
Core Idea
Swagger API documentation is a live, interactive map of your API that shows what it does and how to use it, generated directly from your code.
Think of it like...
Imagine your API is a restaurant kitchen, and Swagger is the menu that lists all dishes (endpoints), ingredients (parameters), and how they are served (responses), so customers know exactly what to order and expect.
┌─────────────────────────────┐
│        Your NestJS API       │
│  ┌───────────────┐          │
│  │ Controllers   │          │
│  │ & Endpoints   │          │
│  └──────┬────────┘          │
│         │ Decorators        │
│         ▼                   │
│  ┌───────────────┐          │
│  │ Swagger Module│          │
│  │ Generates     │          │
│  │ Documentation │          │
│  └──────┬────────┘          │
│         │                   │
│         ▼                   │
│  ┌───────────────┐          │
│  │ Interactive   │          │
│  │ API Docs UI   │          │
│  └───────────────┘          │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat is Swagger and OpenAPI
🤔
Concept: Introduce Swagger as a tool and OpenAPI as the standard format for API documentation.
Swagger is a set of tools that help describe REST APIs in a standard way called OpenAPI. OpenAPI is like a language that explains what endpoints exist, what data they accept, and what they return. Swagger uses this to create interactive web pages where you can try the API live.
Result
You understand that Swagger is not just a document but a live interface for APIs, based on the OpenAPI standard.
Knowing Swagger is built on OpenAPI helps you realize it’s a universal way to describe APIs, not just a NestJS feature.
2
FoundationSetting up Swagger in NestJS
🤔
Concept: Learn how to add Swagger to a NestJS project using the official module.
In your NestJS app, install @nestjs/swagger and swagger-ui-express packages. Then, in your main.ts file, import SwaggerModule and DocumentBuilder. Use DocumentBuilder to define your API title, description, and version. Create a document from your app and setup Swagger UI at a route like '/api'. This shows a web page with your API docs.
Result
Your NestJS app now serves a live Swagger UI page showing your API endpoints.
Understanding the setup process shows how Swagger integrates tightly with NestJS lifecycle and routing.
3
IntermediateUsing Decorators to Document Endpoints
🤔Before reading on: do you think Swagger requires separate files for documentation or uses code annotations? Commit to your answer.
Concept: Learn how to use decorators like @ApiTags, @ApiOperation, and @ApiResponse to add metadata to controllers and routes.
NestJS Swagger uses decorators to add descriptions and details directly in your code. For example, @ApiTags groups endpoints, @ApiOperation describes what a route does, and @ApiResponse shows possible responses. These decorators enrich the Swagger docs automatically.
Result
Your Swagger UI now shows detailed descriptions, grouped endpoints, and response info, making docs clearer.
Knowing that documentation lives with code keeps docs accurate and reduces duplication or outdated info.
4
IntermediateDocumenting Request and Response Models
🤔Before reading on: do you think Swagger guesses data shapes automatically or needs explicit model definitions? Commit to your answer.
Concept: Learn to define and use DTO classes with decorators to describe the shape of data sent and received by your API.
Create classes called DTOs (Data Transfer Objects) with properties decorated by @ApiProperty to describe fields. Use these DTOs in your controller methods as input or output types. Swagger reads these to show detailed schemas for requests and responses.
Result
Swagger UI displays clear data models with field names, types, and descriptions, helping users understand data structure.
Explicit models prevent confusion and errors by making data contracts clear and enforceable.
5
IntermediateAdding Security and Authentication Details
🤔Before reading on: do you think Swagger automatically knows your API’s security or needs explicit setup? Commit to your answer.
Concept: Learn how to document API security schemes like JWT or API keys so users know how to authenticate.
Use DocumentBuilder to add security schemes like bearerAuth. Decorate controllers or routes with @ApiBearerAuth to indicate they require authentication. Swagger UI then shows a lock icon and lets users enter tokens to try secured endpoints.
Result
Your Swagger docs clearly show which endpoints need authentication and allow testing with tokens.
Documenting security helps prevent misuse and guides users on how to access protected resources.
6
AdvancedCustomizing Swagger UI and Extending Docs
🤔Before reading on: do you think Swagger UI is fixed or can be customized in NestJS? Commit to your answer.
Concept: Learn how to customize the Swagger UI appearance and add extra metadata or tags for better organization.
You can customize Swagger UI by passing options to setup method, like changing the site title or adding custom CSS. You can also add extra tags, external docs links, or servers in DocumentBuilder. This makes your docs more user-friendly and tailored to your project.
Result
Swagger UI looks and feels unique to your API, improving user experience and clarity.
Customization helps your API stand out and better communicate its purpose and usage.
7
ExpertAutomating Client Generation and Testing
🤔Before reading on: do you think Swagger docs are only for humans or can be used by tools? Commit to your answer.
Concept: Understand how Swagger/OpenAPI specs can be used to generate client code and automated tests.
The OpenAPI JSON generated by Swagger can be fed into tools that create client libraries in many languages, saving manual coding. It can also be used by testing tools to automatically verify API behavior matches the docs. This bridges backend and frontend development and improves reliability.
Result
Your API ecosystem becomes more efficient with less manual work and fewer bugs.
Knowing Swagger docs are machine-readable unlocks powerful automation beyond just documentation.
Under the Hood
Swagger in NestJS works by reading metadata added by decorators at runtime. When the app starts, SwaggerModule scans controllers and their methods for these decorators, building a JSON OpenAPI document describing all endpoints, parameters, request bodies, responses, and security. This JSON is then served to Swagger UI, which renders it as an interactive webpage. The decorators use TypeScript reflection to gather type info, making the docs accurate and up-to-date.
Why designed this way?
This design keeps documentation close to code, avoiding separate manual docs that get outdated. Using decorators leverages NestJS’s existing metadata system, making integration seamless. The OpenAPI standard ensures compatibility with many tools and languages. Alternatives like manual docs or separate files were error-prone and hard to maintain, so this approach balances automation, accuracy, and developer experience.
┌───────────────────────────────┐
│ NestJS Application Startup     │
│ ┌───────────────────────────┐ │
│ │ Controllers with Decorators│ │
│ └─────────────┬─────────────┘ │
│               │ Reflect Metadata│
│               ▼               │
│ ┌───────────────────────────┐ │
│ │ SwaggerModule Scans Code  │ │
│ │ Builds OpenAPI JSON       │ │
│ └─────────────┬─────────────┘ │
│               │ Serve JSON     │
│               ▼               │
│ ┌───────────────────────────┐ │
│ │ Swagger UI (Webpage)      │ │
│ │ Renders Interactive Docs   │ │
│ └───────────────────────────┘ │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does Swagger automatically document all your API code without any decorators? Commit to yes or no.
Common Belief:Swagger automatically documents every endpoint without extra work once installed.
Tap to reveal reality
Reality:Swagger only documents endpoints and details where you add specific decorators; without them, docs are minimal or missing.
Why it matters:Assuming automatic docs leads to incomplete or confusing API documentation, frustrating users and causing errors.
Quick: Do you think Swagger UI is only for developers or can clients use it too? Commit to your answer.
Common Belief:Swagger UI is just a developer tool and not meant for API consumers or clients.
Tap to reveal reality
Reality:Swagger UI is designed as an interactive interface for anyone to explore and test the API, including clients and testers.
Why it matters:Underestimating Swagger UI’s audience limits its usefulness and misses opportunities for better collaboration.
Quick: Does adding @ApiProperty to a DTO property change the runtime behavior of your API? Commit to yes or no.
Common Belief:Decorators like @ApiProperty affect how the API works at runtime, changing validation or logic.
Tap to reveal reality
Reality:@ApiProperty only adds metadata for documentation; it does not affect runtime validation or API behavior.
Why it matters:Confusing documentation decorators with runtime logic can cause misunderstandings and bugs in API design.
Quick: Can Swagger docs be used to generate client code automatically? Commit to yes or no.
Common Belief:Swagger docs are only for reading and cannot be used to generate code.
Tap to reveal reality
Reality:Swagger/OpenAPI specs are machine-readable and widely used to generate client SDKs and automated tests.
Why it matters:Missing this limits automation and integration possibilities, increasing manual work and errors.
Expert Zone
1
Swagger decorators do not validate data at runtime; you must use class-validator or similar libraries for validation.
2
The order of applying decorators and the use of inheritance in DTOs can affect how Swagger generates schemas, sometimes causing unexpected results.
3
Custom decorators or plugins can extend Swagger metadata, but improper use can break the OpenAPI spec and cause UI errors.
When NOT to use
Swagger is not ideal for APIs that are highly dynamic or use non-REST protocols like GraphQL or WebSockets. For those, use specialized tools like GraphQL Playground or AsyncAPI. Also, if your API is private and never consumed externally, lightweight inline docs or code comments may suffice.
Production Patterns
In production, teams often automate Swagger doc generation as part of CI/CD pipelines, validate the OpenAPI spec with linters, and generate client SDKs for frontend teams. They also secure Swagger UI behind authentication in staging or production to prevent exposing API details publicly.
Connections
OpenAPI Specification
Swagger is an implementation and tooling ecosystem built around the OpenAPI standard.
Understanding OpenAPI helps grasp Swagger’s format and enables using other tools that support the same standard.
API Gateway
API Gateways often consume Swagger/OpenAPI specs to configure routing, security, and rate limiting automatically.
Knowing Swagger docs can drive API Gateway setup shows how documentation integrates with infrastructure.
User Interface Design
Swagger UI is a specialized UI that presents complex API data in a clear, interactive way.
Understanding UI principles helps improve Swagger customization for better user experience.
Common Pitfalls
#1Not adding decorators to all endpoints, resulting in incomplete docs.
Wrong approach:import { Controller, Get } from '@nestjs/common'; @Controller('cats') export class CatsController { @Get() findAll() { return []; } }
Correct approach:import { Controller, Get } from '@nestjs/common'; import { ApiTags, ApiOperation } from '@nestjs/swagger'; @ApiTags('cats') @Controller('cats') export class CatsController { @Get() @ApiOperation({ summary: 'Get all cats' }) findAll() { return []; } }
Root cause:Assuming Swagger works fully without explicit metadata decorators.
#2Using @ApiProperty without specifying type or description, causing unclear docs.
Wrong approach:export class CreateCatDto { @ApiProperty() name; }
Correct approach:export class CreateCatDto { @ApiProperty({ type: String, description: 'Name of the cat' }) name: string; }
Root cause:Not providing enough detail in decorators leads to vague or incorrect schema generation.
#3Exposing Swagger UI publicly in production without security.
Wrong approach:app.use('/api', swaggerUi.serve, swaggerUi.setup(document));
Correct approach:if (process.env.NODE_ENV !== 'production') { app.use('/api', swaggerUi.serve, swaggerUi.setup(document)); }
Root cause:Forgetting to restrict access to API docs can leak sensitive API details.
Key Takeaways
Swagger API documentation in NestJS uses decorators to generate live, interactive API docs automatically from your code.
It improves communication by clearly showing endpoints, data models, and security requirements in one place.
Swagger docs are machine-readable, enabling client code generation and automated testing, not just human reading.
Proper use of decorators and DTOs ensures accurate and useful documentation that stays in sync with your API.
Understanding Swagger’s integration and limitations helps you build better APIs and avoid common pitfalls.

Practice

(1/5)
1. What is the main purpose of using Swagger in a NestJS application?
easy
A. To automatically generate interactive API documentation
B. To improve database query performance
C. To handle user authentication
D. To manage application state

Solution

  1. Step 1: Understand Swagger's role

    Swagger is a tool that creates easy-to-read and interactive API documentation automatically.
  2. Step 2: Compare options

    The other options relate to database performance, authentication, and state management, which Swagger does not handle.
  3. Final Answer:

    To automatically generate interactive API documentation -> Option A
  4. Quick Check:

    Swagger = API docs [OK]
Hint: Swagger = auto API docs, not database or auth [OK]
Common Mistakes:
  • Confusing Swagger with authentication tools
  • Thinking Swagger improves database queries
  • Assuming Swagger manages app state
2. Which NestJS class is used to configure the API information for Swagger documentation?
easy
A. HttpModule
B. SwaggerModule
C. ApiProperty
D. DocumentBuilder

Solution

  1. Step 1: Identify configuration class

    DocumentBuilder is the class used to set API title, description, version, and other info for Swagger.
  2. Step 2: Differentiate from other classes

    SwaggerModule sets up the docs route, ApiProperty decorates DTO properties, HttpModule handles HTTP requests.
  3. Final Answer:

    DocumentBuilder -> Option D
  4. Quick Check:

    API info config = DocumentBuilder [OK]
Hint: DocumentBuilder builds API info for Swagger [OK]
Common Mistakes:
  • Confusing SwaggerModule with DocumentBuilder
  • Using ApiProperty for API config instead of DTO properties
  • Thinking HttpModule configures Swagger
3. Given the following NestJS Swagger setup code, what URL will serve the Swagger UI?
const config = new DocumentBuilder()
  .setTitle('Cats API')
  .setDescription('API for cats')
  .setVersion('1.0')
  .build();

const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api-docs', app, document);
medium
A. http://localhost:3000/api-docs
B. http://localhost:3000/swagger
C. http://localhost:3000/docs
D. http://localhost:3000/api

Solution

  1. Step 1: Identify the setup path

    The setup method uses 'api-docs' as the first argument, which defines the URL path for Swagger UI.
  2. Step 2: Combine with default host and port

    By default, NestJS runs on localhost:3000, so the full URL is http://localhost:3000/api-docs.
  3. Final Answer:

    http://localhost:3000/api-docs -> Option A
  4. Quick Check:

    SwaggerModule.setup path = api-docs [OK]
Hint: First argument in setup() is Swagger URL path [OK]
Common Mistakes:
  • Assuming default path is /swagger or /docs
  • Confusing createDocument with setup URL
  • Ignoring the string passed to setup()
4. Identify the error in this NestJS Swagger setup code:
const config = new DocumentBuilder()
  .setTitle('Dogs API')
  .setDescription('API for dogs')
  .setVersion('1.0')
  .build();

const document = SwaggerModule.createDocument(config, app);
SwaggerModule.setup('docs', app, document);
medium
A. SwaggerModule.setup path should be '/swagger' not 'docs'
B. Missing call to build() on DocumentBuilder
C. The order of arguments in createDocument is incorrect
D. DocumentBuilder cannot set version

Solution

  1. Step 1: Check createDocument arguments

    The correct order is (app, config), but here it is (config, app), which causes an error.
  2. Step 2: Verify other parts

    build() is called correctly, setup path 'docs' is valid, and DocumentBuilder can set version.
  3. Final Answer:

    The order of arguments in createDocument is incorrect -> Option C
  4. Quick Check:

    createDocument(app, config) order matters [OK]
Hint: createDocument(app, config) order is fixed [OK]
Common Mistakes:
  • Swapping app and config in createDocument
  • Forgetting to call build() on DocumentBuilder
  • Thinking setup path must be '/swagger'
5. You want to add a global prefix '/api' to all routes in your NestJS app but still serve Swagger docs at '/docs'. Which setup correctly achieves this without breaking Swagger access?
hard
A. Do not set global prefix; use SwaggerModule.setup('docs', app, document);
B. app.setGlobalPrefix('api'); SwaggerModule.setup('docs', app, document);
C. app.setGlobalPrefix('api'); SwaggerModule.setup('api/docs', app, document);
D. SwaggerModule.setup('api/docs', app, document); app.setGlobalPrefix('api');

Solution

  1. Step 1: Understand global prefix effect

    Setting a global prefix like 'api' adds it to all routes except those explicitly set in SwaggerModule.setup.
  2. Step 2: Confirm Swagger path independence

    SwaggerModule.setup('docs', app, document) serves docs at '/docs' ignoring global prefix, so docs remain accessible.
  3. Step 3: Analyze other options

    Other sequences either omit the global prefix or incorrectly include it in the Swagger path, leading to double prefixing or wrong Swagger location.
  4. Final Answer:

    app.setGlobalPrefix('api'); SwaggerModule.setup('docs', app, document); -> Option B
  5. Quick Check:

    Global prefix separate from Swagger path [OK]
Hint: Set global prefix separately; Swagger path stays independent [OK]
Common Mistakes:
  • Adding global prefix inside Swagger path causing double prefix
  • Not setting global prefix when needed
  • Changing Swagger path to include global prefix unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard