Build Complete REST API Feature with Nest JS (Using Prisma and Postgresql) from Scratch - Beginner-friendly - PART 7
Tags: nestjs, typescript, openapi, node
Published: 2023-11-01 13:31:49

## Scope of discussion:
Create API documentation

---

This is the last part of this Nest JS series.

Since we already created some endpoints in our API, now it's time for us to write the documentation.

Nest JS itself is compatible with `OpenAPI`. It's well-documented and super easy to write using Nest JS Swagger.
> [openAPI doc](https://docs.nestjs.com/openapi/introduction).

Here, I'll just give a small example of how to build Nest JS API documentation. We'll use register API as a reference. Without any further ado, let's go 🔥🔥🔥

### Installation and Config
First of all, let's install the Nest JS Swagger:
`$ npm install --save @nestjs/swagger`

Once installed, let's continue to update our `main.ts`, because we need to initialize in the Nest JS `bootstrap` function:
```typescript
// src/main.ts

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  ...

  // Check here - Swagger setup
  const config = new DocumentBuilder()
    .setTitle('Superb API')
    .setDescription('The Super API documentation')
    .setVersion('1.0')
    .addTag('superb')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  ...

  await app.listen(3000);
}
```

Then let's try to run our API using `npm run start:dev`, and open this URL `http://localhost:3000/api`. We'll see:

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

All endpoints that we created will be listed there. If you scroll down, you'll see the empty DTO schemas:

![Empty DTO schemas](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06trc8m1ddvks1v1fg8k.png)

Our API documentation is ready, but it's still messy. So we're going to make it more organized. We'll only touch `controller` and `dto` files, and add some decorators.

#### Add decorators to controller
Let's update our `registerUser` function in `users.controller.ts` for an example:
```typescript
@Post('register')
// 💡 See here. Add this decorator to add operationId to swagger docs
@ApiOperation({
  summary: 'Register a new user',
  operationId: 'create',
})
// 💡 See here. Add this decorator to add API response to swagger docs
@ApiResponse({
  status: 201,
  description: 'Created',
  type: CreateUserDto,
})
async registerUser(@Body() createUserDto: CreateUserDto): Promise<User> {
  // call users service method to register new user
  return this.usersService.registerUser(createUserDto);
}
```

If you refresh the documentation page, you'll see `users` endpoints are grouped:
![Grouped users doc](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qau8b5ghmyv0qdyjr1sz.png)

Register API is updated:
![Register API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/utvjhxsw59n6vcv5ynfv.png)
> Schema is still empty

And we can see the responses as well:

![API Responses](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mj55iuirbtt67zt4cj7j.png)

#### Add decorators to DTO
Now let's add decorators to our `CreateUserDto`:
```typescript
export class CreateUserDto {
  // 💡 See here. Add this decorator
  @ApiProperty({
    example: 'email@email.com',
    description: 'The email of new user.',
    type: String,
  })
  @IsNotEmpty()
  @IsEmail()
  email: string;

  // 💡 See here. Add this decorator
  @ApiProperty({
    example: 'super_secret_password',
    description: 'The password of new user.',
    type: String,
  })
  @IsNotEmpty()
  password: string;

  // 💡 See here. Add this decorator
  @ApiProperty({
    example: 'John Doe',
    description: 'The full name of new user.',
    type: String,
  })
  @IsNotEmpty()
  name: string;
}
```

Now we can see the DTO schema:
![Schema DTO](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t4d2s3ozmpt9ra916huy.png)

It's super easy, isn't it? 😄

OpenAPI itself has so many attributes. If you want to explore more, just open Nest JS documentation here:
![Doc](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/86o43ywt3mttvrg1ovvn.png)
and you'll find tons of features.

I think that's all about this latest part.

The full code of part 7 can be accessed here:
https://github.com/alfism1/nestjs-api/tree/part-seven

Thank you!