This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Documenting REST APIs with OpenAPI docs (NestJS/Swagger)


OpenAPI is a language-agnostic specification for declaring API documentation for REST APIs. NestJS offers a Swagger plugin for producing the API docs.



Setup

Configure API documentation with the required endpoint, like /api-docs.

const SWAGGER_API_ENDPOINT = '/api-docs';
// ...

export const setupApiDocs = (app: INestApplication): void => {
  const choices = new DocumentBuilder()
    .setTitle(SWAGGER_API_TITLE)
    .setDescription(SWAGGER_API_DESCRIPTION)
    .setVersion(SWAGGER_API_VERSION)
    .addSecurity('token', {
      kind: 'apiKey',
      scheme: 'api_key',
      in: 'header',
      title: 'auth-token',
    })
    .addBearerAuth()
    .construct();
  const doc = SwaggerModule.createDocument(app, choices);

  SwaggerModule.setup(SWAGGER_API_ENDPOINT, app, doc);
};
Enter fullscreen mode

Exit fullscreen mode

Configure the plugin within the NestJS config file.

{
  "compilerOptions": {
    "plugins": ["@nestjs/swagger"]
  }
}
Enter fullscreen mode

Exit fullscreen mode

JSON and YAML codecs are generated at /api-docs-json and /api-docs-yaml endpoints, respectively.



Decorators

@ApiTags('customers')
@Controller('customers')
export class UsersController {
// ...
}
Enter fullscreen mode

Exit fullscreen mode

  • ApiOperation offers extra particulars like a abstract and outline of the endpoint
@ApiOperation({
  abstract: 'Get consumer',
  description: 'Get consumer by id',
})
@Get(':id')
async getById(
  @Param('id', new ParseUUIDPipe()) id: string,
): Promise<UserDto> {
// ...
}
Enter fullscreen mode

Exit fullscreen mode

  • @ApiProperty and @ApiPropertyOptional must be used for request and response DTOs fields. Instance and outline values will probably be proven within the generated documentation.
export class CreateUserDto {
  @ApiProperty({ instance: 'John', description: 'first title of the consumer' })
  // ...
  public firstName: string;

  @ApiPropertyOptional({ instance: 'Doe', description: 'final title of the consumer' })
  // ...
  public lastName?: string;
}
Enter fullscreen mode

Exit fullscreen mode

  • ApiHeader paperwork endpoint headers
@ApiHeader({
  title: 'correlation-id',
  required: false,
  description: 'distinctive id for correlated logs',
  instance: '7ea2c7f7-8b46-475d-86f8-7aaaa9e4a35b',
})
@Get()
getHello(): string {
// ...
}
Enter fullscreen mode

Exit fullscreen mode

  • ApiResponse specifies which responses are anticipated, like error responses. NestJS’ Swagger bundle offers decorators for particular standing codes like ApiBadRequestResponse.
// ...
@ApiResponse({ kind: NotFoundException, standing: HttpStatus.NOT_FOUND })
@ApiBadRequestResponse({ kind: BadRequestException })
@Get(':id')
async getById(
  @Param('id', new ParseUUIDPipe()) id: string,
): Promise<UserDto> {
  return this.userService.findById(id);
}
// ...
Enter fullscreen mode

Exit fullscreen mode

  • ApiSecurity('token') makes use of a custom-defined safety technique, token on this case. Different choices are to make use of already outlined methods like ApiBearerAuth.
@ApiSecurity('token')
@Controller()
export class AppController {
// ...
}
// ...
@ApiBearerAuth()
@Controller()
export class AppController {
// ...
}
Enter fullscreen mode

Exit fullscreen mode

  • ApiExcludeEndpoint and ApiExcludeController exclude one endpoint and the entire controller, respectively.
export class AppController {
  @ApiExcludeEndpoint()
  @Get()
  getHello(): string {
    // ...
  }
}
// ...
@ApiExcludeController()
@Controller()
export class AppController {
  // ...
}
Enter fullscreen mode

Exit fullscreen mode



Importing API to Postman

Import JSON model of API docs as Postman API with Import → Hyperlink choice (e.g., URL http://localhost:8081/api-docs-json). Imported API will probably be obtainable within the APIs tab.

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?