Skip to main content

500. OpenAPI

OpenAPI Specifications

Installation

npm install --save @nestjs/swagger

Configuration

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

const config = new DocumentBuilder()
.setTitle('Cats example')
.setDescription('The cats API description')
.setVersion('1.0')
.addTag('cats')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);

await app.listen(3000);
}

While the application is running, open your browser and navigate to http://localhost:3000/api. You should see the Swagger UI. http://localhost:3000/api-json for downloadable json version

How Openapi Words

  • The SwaggerModule searches for all @Body(), @Query(), and @Param() decorators in route handlers to generate the API document. It also creates corresponding model definitions by taking advantage of reflection.

How to Use Openapi Swagger in Your Projects

@Post()
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}
  • in order to make class properties visible to the swagger, we have to either annotate then with @ApiProperty() decorator or use the CLI plugin which will do it automatically
import { ApiProperty } from '@nestjs/swagger';

export class CreateCatDto {
@ApiProperty()
name: string;

@ApiProperty({
description: 'The age of a cat',
minimum: 1,
default: 1,
})
age: number;

@ApiProperty()
breed: string;

@ApiProperty({ type: [String] })
friends: string[];
}

dtos by default won't be picked up by swagger, to resolve this add the following options to nest-cli.json CLI Plugin - OpenAPI | NestJS - A progressive Node.js framework

{
//..
"compilerOptions": {
"deleteOutDir": true,
"plugins": ["@nestjs/swagger/plugin"]
}
}
//import { PartialType } from "@nestjs/mapped-types"; //before

import { PartialType } from "@nestjs/swagger"; //after
import { IsString } from "class-validator";
import { CreateCoffeDto } from "./create-coffe.dto";

export class UpdateCoffeDto extends PartialType(CreateCoffeDto) {

@IsString()
readonly id: string;
}

  @ApiResponse({
status: 201,
description: 'The record has been successfully created.',
type: CreateCoffeDto,
})
@ApiResponse({ status: 404, description: 'Record not found.' })
@Get(':id')
findOne(@Param('id') id: string) {
return this.coffesService.findOne(id);
}
@ApiTags('coffes')
@Controller('coffes')
export class CoffesController {
//..crud functions
}