DEV Community

Alfi Samudro Mulyo
Alfi Samudro Mulyo

Posted on • Updated on

Build Complete REST API Feature with Nest JS (Using Prisma and Postgresql) from Scratch - Beginner-friendly - PART 7

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.

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:



// 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);
}


Enter fullscreen mode Exit fullscreen mode

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

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

Empty DTO schemas

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:



@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);
}


Enter fullscreen mode Exit fullscreen mode

If you refresh the documentation page, you'll see users endpoints are grouped:
Grouped users doc

Register API is updated:
Register API

Schema is still empty

And we can see the responses as well:

API Responses

Add decorators to DTO

Now let's add decorators to our CreateUserDto:



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;
}


Enter fullscreen mode Exit fullscreen mode

Now we can see the DTO schema:
Schema DTO

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
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!

Top comments (2)

Collapse
 
fadlithirafi profile image
Fadli Thirafi

easy to understand, Nice :)

Collapse
 
zanuar_hanif_ra profile image
Zanuar Hanif Rachmat Adi

mantab pak cik :'v