0
0
NestJSframework~30 mins

Swagger API documentation in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Swagger API documentation
📖 Scenario: You are building a simple NestJS API for managing books in a library. You want to add Swagger API documentation so that other developers can easily understand and test your API endpoints.
🎯 Goal: Create a NestJS controller with Swagger decorators to document the API endpoints for getting all books and adding a new book.
📋 What You'll Learn
Create a controller named BooksController
Add a GET endpoint /books that returns a list of books
Add a POST endpoint /books that accepts a book object
Use Swagger decorators @ApiTags, @ApiOperation, and @ApiResponse to document the endpoints
Define a DTO class CreateBookDto with title and author properties and document it with @ApiProperty
💡 Why This Matters
🌍 Real World
Swagger documentation helps developers understand and test APIs easily without guessing endpoints or request formats.
💼 Career
Knowing how to add Swagger docs is a common requirement for backend developers working with NestJS or other frameworks to improve API usability.
Progress0 / 4 steps
1
Create the initial data structure
Create a class called CreateBookDto with two string properties: title and author. Use @ApiProperty() decorator from @nestjs/swagger on both properties.
NestJS
Need a hint?

Use export class CreateBookDto and add @ApiProperty() above each property.

2
Add Swagger tag configuration
Create a controller class called BooksController and add the @ApiTags('books') decorator from @nestjs/swagger above it.
NestJS
Need a hint?

Use @ApiTags('books') and @Controller('books') above the BooksController class.

3
Add GET and POST endpoints with Swagger documentation
Inside BooksController, add a GET method called getAllBooks with @Get() decorator and Swagger decorators @ApiOperation({ summary: 'Get all books' }) and @ApiResponse({ status: 200, description: 'List of books returned.' }). Also add a POST method called createBook with @Post() decorator, Swagger decorators @ApiOperation({ summary: 'Add a new book' }) and @ApiResponse({ status: 201, description: 'Book created.' }), and accept a parameter createBookDto of type CreateBookDto decorated with @Body().
NestJS
Need a hint?

Use @Get() and @Post() decorators with matching method names and add Swagger decorators as shown.

4
Complete the Swagger setup in main.ts
In the main.ts file, import SwaggerModule and DocumentBuilder from @nestjs/swagger. Create a Swagger document with DocumentBuilder() setting the title to 'Library API', description to 'API for managing books', and version to '1.0'. Then call SwaggerModule.setup('api', app, document) to serve the docs at /api. Assume app is the NestJS application instance.
NestJS
Need a hint?

Use DocumentBuilder to create config and SwaggerModule.setup to serve docs at /api.