Swagger is an open source tool/framework which is widely used by developers for building,documenting and testing out RESTful APIs for their system. It is very useful in the development phase of a system as it helps developer use and understand each other’s APIs.
To implement swagger in your NestJs project, you can go through the following steps:
Step 1: Assuming that you already have your NestJs project set up, install the necessary dependency to implement swagger.
$ npm install --save @nestjs/swagger
Step 2: Now, you have to initialize swagger in your main.ts file as follow:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
//swagger
const config = new DocumentBuilder()
.setTitle('Swagger example')
.setDescription('The users API description')
.setVersion('1.0')
.addTag('users')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
bootstrap();
Here, SwaggerModule class is being used to initialize the swagger.
Now, if you want to operate CRUD operation through swagger you can do it too.
You can use Prisma in you NestJs as your ORM. So assuming you are familiar with prisma(If not, visit : Getting started with Prisma) you can have a User model in your prisma.schema file as follow:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
password String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
To operate CRUD on this user model through swagger, you have to use decorators in users.controller.ts file like:
- @ApiTags(‘users’)- Defines the endpoints.
- @ApiOperation({ summary: ‘Create a new user’ })- Describes operation such as POST,GET,PATCH,DELETE.
- @ApiResponse({status: 201,description: ‘Return all users.’,})-Describes the expected response for the given operation
//users.controller.ts
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
@ApiTags('users')
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Post('add')
@ApiOperation({ summary: 'Create a new user' })
@ApiResponse({
status: 201,
description: 'The user has been successfully created.',
})
@ApiResponse({ status: 403, description: 'Forbidden.' })
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
@Get()
@ApiOperation({ summary: 'Get all users' })
@ApiResponse({status: 201,description: 'Return all users.',})
@ApiResponse({ status: 403, description: 'Forbidden.' })
findAll() {
return this.usersService.findAll();
}
@Get(':id')
@ApiResponse({
status: 201,
description: 'Return user by id',
})
@ApiResponse({ status: 403, description: 'Forbidden.' })
@ApiOperation({ summary: 'Get user by id' })
findOne(@Param('id') id: number) {
return this.usersService.findOne(+id);
}
@Patch(':id')
@ApiResponse({
status: 201,
description: 'Update user by id',
})
@ApiResponse({ status: 403, description: 'Forbidden.' })
@ApiOperation({ summary: 'Update user by id' })
update(@Param('id') id: number, @Body() updateUserDto: UpdateUserDto) {
return this.usersService.update(+id, updateUserDto);
}
@Delete(':id')
@ApiResponse({
status: 201,
description: 'User by id deleted successfully.',
})
@ApiResponse({ status: 403, description: 'Forbidden.' })
@ApiOperation({ summary: 'Delete user by id' })
remove(@Param('id') id: number) {
return this.usersService.remove(+id);
}
}
Now, to run the project you can hit command :
$npm run start:dev
or
$yarn start:dev
In your browser, hit the endpoint : http://localhost:3000/api
