500. OpenAPI
OpenAPI Specifications
- OpenAPI (Swagger) | NestJS - A progressive Node.js framework
- The OpenAPI specification is a language-agnostic definition format used to describe RESTful APIs.
- Nest provides a dedicated module which allows generating such a specification by leveraging decorators.
Installation
npm install --save @nestjs/swagger
Configuration
- OpenAPI (Swagger) | NestJS - A progressive Node.js framework
- Once the installation process is complete, open the
main.ts
file and initialize Swagger using theSwaggerModule
class:
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
- Types and Parameters - OpenAPI | NestJS - A progressive Node.js framework
- create dto for your endpoints
@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"]
}
}
- moreover mapped types(partial, pick, omit…) will also not work, to fix this, update your import of e.x.
PartialType
to swagger partial type
//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;
}
- use
@ApiResponse
decorator to add more info on an API response, this can be an info on why an error response and when it returned…
@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);
}
- if you want to group, all endpoints from a single controller into one drop-down swagger component, use the decorator
@ApiTags
@ApiTags('coffes')
@Controller('coffes')
export class CoffesController {
//..crud functions
}