---
# System prepended metadata

title: Swagger in NestJS Project
tags: [published, SJbG-ZSJbe, backend, self-taught]

---

# Swagger in NestJS Project
![image](https://hackmd.io/_uploads/SJbG-ZSJbe.png)

In a [blog](https://hackmd.io/@linfini/husky-and-lintstaged) I wrote earlier, I mentioned tools that once used, I don't want to go back and I would like to add one more to the list. Yes :smile: you can see from the banner, it's Swagger!

### I. Why Swagger

It's probably the most popular name you'll hear when it comes to API documentation and generation. Since TypeScript has become almost mandatory for front-end development, I find it hard to have to manually create type for API response and Request, especially in a complex project. 

### II. Swagger in NestJS

I first used Swagger in a Java Springboot project, where we define everything in a YAML file first, then generate DTOs for both frontend and backend. You can check out how to structure the Swagger doc [here](https://hackmd.io/@linfini/write-rest-docs-with-swagger). But with NestJS, we do the opposite, which is defining DTOs and entities first and then generating API docs for frontend.

### III. How to implement

#### 1 - Installation

We first install the required dependency.

```javascript!
npm install --save @nestjs/swagger
```

Then we initialize Swagger using the `SwaggerModule` class 

```javascript!
// main.ts

import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

  // Swagger config
  const config = new DocumentBuilder()
    .setTitle('My API')
    .setDescription('Auto-generated OpenAPI spec')
    .setVersion('1.0')
    .build();

  const document = SwaggerModule.createDocument(app, config);

  // Serve Swagger UI
  SwaggerModule.setup('api/docs', app, document);

  // write spec file
  writeFileSync('swagger/openapi-spec.json', JSON.stringify(document, null, 2));
```

So, what we’re doing is simply integrating Swagger into your app. When you develop the app locally (let’s say it’s running on port 8080), you can access the API documentation at `http://localhost:8080/api/docs`.

<img src="https://hackmd.io/_uploads/SkhqU6NkWg.png" alt="swagger_doc" style="border: 1px solid black">

In the official documentation, you won’t find the `writeFileSync` function, but I’ve included it here because we’re attempting to create the document file that the frontend can use to generate and utilize the type. You can also download this document as JSON manually by adding `jsonDocumentUrl` in swagger setup. Then the JSON file will be exposed in `http://localhost:8080/swagger/json`

```javascript!
  SwaggerModule.setup('api/docs', app, document, {
    jsonDocumentUrl: 'swagger/json',
  });
```

<img src="https://hackmd.io/_uploads/ByhVe04ybg.png" alt="swagger_json" style="border: 1px solid black">

*And here’s a simple tip: all API endpoints should have the same tag unless your app is exceptionally complex. Otherwise, it would be a hassle for the frontend because we would need to set up a separate configuration for each level 1 endpoint.*

#### 2 - Generate document for frontend usage

With the provided JSON file, frontend developers can generate the types themselves. However, with a bit of additional setup, they can do so more easily.

To achieve this, create a shell script in the same folder as the JSON file. Whenever you want to generate the document, simply run the script.

```shell!
#!/bin/bash
set -e

npx openapi-generator-cli generate \
  -i openapi-spec.json \
  -g typescript-axios \
  -o ./output

echo "Frontend client generated in swagger/output/"
```

#### 3 - It's all about decorator

The reason I say this is that all we need to do is add decorators to any controllers and DTOs we want to expose.

All the available OpenAPI decorators have an `Api` prefix to differentiate them from the core decorators. However, I won’t mention all of them; I’ll only mention those I use the most, which can create sufficient documents for both the front and back end. Each decorator has a designated level at which it may be applied. You can refer to the full list for more information [here](https://docs.nestjs.com/openapi/decorators).

**@ApiTags('Default')**

This decorator should be added to the top of all your controllers so that all API endpoints can be set up simultaneously on the frontend. As I mentioned earlier, if you want the frontend to set up differently for each endpoint, you can ignore this decorator.

**@ApiOperation({ operationId: 'getRecipes', summary: 'Get recipes'})**

This decorator will indicate the API function that the frontend will call, as shown below. At the very least, declare `operationId`. Otherwise, the API function name will be automatically generated and will be long and not very intuitive.

![image](https://hackmd.io/_uploads/ByfXzyrkbl.png)

**@ApiResponse({status: 200, description: 'Get recipes', type: RecipeListResponseDto})**

This decorator is essential for generating the type of the API response. Since an error will be thrown, we don’t need to specify the error response. Make sure to clarify the type, or it will be meaningless.

**@ApiParam** & **@ApiQuery**

We don’t need to define this since Swagger scans everything automatically. If your API has queries and parameters, they will be included in the Swagger documentation. I’m not sure why, but when working on my own project, even when queries are optional, the type is still generated as required. So, if you encounter the same issue, simply add this decorator to specify that the query is optional.

```javascript!
@ApiQuery({ name: 'name', required: false })
```

**@ApiProperty()**

For defining additional information or a specific property of a Data Transfer Object (DTO), use this decorator. Typically, we don’t need to use this decorator if we name our file with the correct suffix `.dto.ts`. Swagger can scan it and it will be generated as is. I usually include examples for the properties of my DTOs to make my document more meaningful for others.

```javascript!
 @ApiProperty({ example: '1' })
  id: string;
```

With just a few decorators like these, we can enhance our API document by adding more details and making it easier for frontend developers to generate a usable type. For document generation, you can use the open API CLI. Please take your time to check out their [rules](https://docs.nestjs.com/openapi/cli-plugin).

### IV. Conclusion

I’m writing this to share my implementation of Swagger in NestJS. However, if you have a more efficient way to achieve this, please comment and let me know.
For more details, you can refer to the [official document](https://docs.nestjs.com/openapi/introduction).