swagger 接口文档
安装
bash
npm install --save @nestjs/swagger swagger-ui-express
配置
typescript
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const options = new DocumentBuilder()
.setTitle('Cats example')
.setDescription('The cats API description')
.setVersion('1.0')
.addTag('cats')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
bootstrap();
访问
http://localhost:3000/api
基本使用
接口分组
typescript
@Controller('cats')
@ApiTags('cats')
export class CatsController {}
接口描述
typescript
@ApiOperation({ summary: '获取猫列表',description: 'The cats list'})
@Get()
async findAll(): Promise<Cat[]> {}
接口参数
typescript
@ApiQuery({ name: 'id', required: true, description: '猫的id' })
@Get(':id')
async findOne(@Param('id') id: string): Promise<Cat> {}
接口响应
typescript
@ApiResponse({ status: 200, description: '成功', type: Cat })
@ApiResponse({ status: 404, description: '未找到' })
@Get(':id')
async findOne(@Param('id') id: string): Promise<Cat> {}
接口异常
typescript
@ApiResponse({ status: 400, description: '无效的id' })
@Get(':id')
async findOne(@Param('id') id: string): Promise<Cat> {}
接口参数校验
typescript
@ApiProperty({ description: '猫的id', example: '1' })
@IsInt()
@IsNotEmpty()
@Param('id')
id: number;
权限装饰器
typescript
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const options = new DocumentBuilder()
.addBearerAuth()
.setTitle('Cats example')
.setDescription('The cats API description')
.setVersion('1.0')
.addTag('cats')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
bootstrap();
typescript
@ApiBearerAuth()