Building CRUD API with NestJs - Swagger API Documentation.
Tags: tutorial, nestjs, node, swagger
Published: 2021-10-13 15:53:49

## Introduction
In this part, we will integrate Swagger UI which helps us to visualize our API resources and with visual documentation, it is easier for consuming and implementing APIs.

**Why Swagger?**
The swagger UI does the hard work of generating and maintaining our API docs, making sure our documentation stays up-to-date as our application evolves.

Before integrating Swagger UI, let's create some more APIs. In the last part we created a POST API to create new user. Let's create GET APIs to get all users and to get a single user. 

```
//Add these APIs in user.controller.ts
@Get('all')
  async getAll(): Promise<User[]> {
    return this.userService.getAll();
  }

  @Get(':userId')
  async getUser(@Param('userId') userId: number): Promise<User> {
    return await this.userService.getUser(userId);
  }
```

```
//user.service.ts
async getAll(): Promise<User[]> {
    return await this.userRepository.findAll();
  }

  async getUser(userId: number): Promise<User> {
    return await this.userRepository.findOne({ id: userId });
  }
```

>
*Note:* Here, we are just returning the data from database directly. But, this is not secure at all we shouldn't be exposing the data directly, we have to create response objects and return them to the client. Also, we have not added any validation what happens if the user we are requesting does not exist we are still returning 200 response which is not ideal. Please explore how to handle validation in APIs and how to use response objects to return data to client. Don't worry if you can't understand these, we will look into these in next part.

## Installation

We can install the swagger dependencies using npm
```
npm install --save @nestjs/swagger swagger-ui-express
```

Once the installation is complete we need to initialize Swagger in 'main.ts' file

{% gist https://gist.github.com/rskhan167/2ed73493e641e52b3085217e0fa7f6a8 %}

Now, in our browser if we go to: `http://localhost:3000/api/`. We can see the list of APIs we have created and we can see all the details of the APIs what parameters it requires and what responses it returns.

![Swagger Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dsx88uqgs1tbmfj60a0b.png)

## Swagger Schema
But if we see in schema below it contains 'CreateUserDto' object which we created but it's empty as Swagger is not able to recognize it.

![Swagger Schema](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jw2mpp7yx01ffxuuff2z.png)

We are using Nest CLI, so we need to add the following plugin configuration in 'nest-cli.json' file.

{% gist https://gist.github.com/rskhan167/f86d438be4379f4d4727793abaf77e51 %}

Also, in all the APIs the response objects are empty, as we need to mention them explicitly in controllers. So, let's do it now.

{% gist https://gist.github.com/rskhan167/475888e3f060d053cca512d28771d8bf %}

>
*Note:* We have added only response objects for status 200. Please explore what other return statuses are possible and add respective Api Response decorators for them.

![Swagger Response object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/agnybjrpz75poy9l6r8z.png)

Now we can see the response objects and the schema objects.

![Swagger Schema objects](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rav1ajdebml09dgxkx9b.png)

>
**Note:** If schema objects are still empty, please *delete* 'dist' directory and run the server again. This folder contains the file conversions of TypeScript to JavaScript. NestJs is entirely written in TypeScript but it has to be converted to JavaScript which is run by the server. Since we have updated the 'nest-cli.json' file we may have to generate the dist folder again.

## Summary

In this tutorial, we explored how we can integrate Swagger UI in our Nest application to document our APIs. We also saw how to add response objects and schema objects in swagger UI.

---

GitHub Repository - https://github.com/rskhan167/movie-review

That's it for this part. Please like and share if you found it useful.
Follow me on Twitter: https://twitter.com/Dotnetdotnet

Thanks for reading.