Integrating Swagger With Nestjs
Table of contents
Swagger is an OPEN source API documentation to help developers design, and document their RESTful web services. Swagger reads an API and extracts it in the form of an interactive UI called “Swagger UI”. On the whole, Swagger is a helpful documentation tool for any modern web backend that exposes a RESTful API. It’s live documentation that changes as the code changes.
In this article, we will be integrating Swagger with RESTful API built using nestjs. So we will be using a nestjs app, clone the app with
git clone
https://github.com/S-a-k-s-h-i/nestjs-rest-api.git
Then configure the app:
Run npm install
[creates a node_modules folder that contains all the dependencies]
Then create a database named mydb.
We need to ensure that all our routes work before we start showing Swagger. So run npm start
Adding Swagger
Now we will add Swagger. To get Swagger to work we need to do the following-
Install the dependencies
Configure bootstrap to start using Swagger
Ensure swagger is rendering in the browser
Installing Swagger
We need to install through the npm with the following command.
npm install --save @nestjs/swagger swagger-ui-express
Configuration
Once the installation is complete, open the main.ts file and initialize Swagger using the SwaggerModule class.
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('Users CRUD')
.setDescription('The users API description')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('/', app, document);
await app.listen(3000);
}
bootstrap();
First, we create a config object that gets the title, description, and version then finally call build() which ends up creating the config object. Then we create a document instance of createDocument() of the SwaggerModule. It will take the app instance and the config object that we have created. At last, we will call setup() of the SwaggerModule. The first argument is a path, which means we will find our API docs under http://localhost:3000/ the next argument is our app and the last argument is the document instance.
Trying out the docs- Let’s start our app
npm start
Then head to localhost:3000 There you should see the following:
This is as expected. We have a POST /user/new
, GET /user
, GET /user/:id
PATCH /user/:id
and DELETE /user/:id
So far so good.
Let’s start by checking the POST request.
We get a big edit window in which we type some JSON that corresponds to a new user we want to create.
Hitting Execute button gives the below response:
As you can see we get 201 as the status code, which means we have successfully created a new user.
Let’s ensure by hitting GET /user
.
Click the Execute button and you get the following response.
So you got the user which you have registered.
Improve our Docs
The first thing is applying @ApiTags()
decorator to our user controller. This will group all our related endpoints under a common tag in our Swagger doc.
Inside user.controller.ts
file, above UserController add the following code-
@ApiTags('User')
@Controller('user')
export class UserController {
Now see the swagger doc at http://localhost:3000/
You see the endpoints grouped under User instead of the default.
Now, If we scroll to the bottom of the page we have CreateUserDto and UpdateUserDto. It’s empty. We can fix this
We can get our DTOs to show up in our Swagger doc by applying the decorator @ApiProperty()
to the fields of our DTO classes.
import { ApiProperty } from "@nestjs/swagger";
export class CreateUserDto {
@ApiProperty()
firstName:string;
@ApiProperty()
lastName:string;
@ApiProperty()
userName:string;
@ApiProperty()
age:number;
@ApiProperty()
isActive:boolean;
}
Let’s start our app again- npm start
and go to http://localhost:3000/ and scroll to the bottom:
You can do the same with UpdateUserDto.
Example
A working example is available here
Summary
Having robust API documentation for RESTful API improves the maintainability and usability of an application. Documentation that changes as the code changes are worth keeping around. So gift your API some docs as well.