NestJs swagger接口文档
文档:https://docs.nestjs.cn/9/recipes?id=swagger
安装
首先,您必须安装所需的包:
npm install --save @nestjs/swagger swagger-ui-express
如果你正在使用 fastify ,你必须安装 fastify-swagger 而不是 swagger-ui-express :
npm install --save @nestjs/swagger fastify-swagger
在main.ts 注册swagger
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
// 注册Swagger
const options = new DocumentBuilder().setTitle('makalo接口文档').setDescription('描述,。。。').setVersion('1').build();
const document = SwaggerModule.createDocument(app,options);
SwaggerModule.setup('/api-docs',app,document);

访问
http://localhost:3000/api-docs

现在没有分组比较乱
使用ApiTags 添加分组
@ApiTags('makalo 分组')


ApiOperation 接口描述
@ApiOperation({summary:"创建makalo的接口",description:"这是一个创建的接口的描述"})


ApiParam 动态参数描述
@ApiParam({name:"id",description:"用户id",required:true})

ApiQuery 修饰get
@ApiQuery({name:"testGet",description:"bbb"})


ApiProperty 修饰DTO
import { ApiProperty } from '@nestjs/swagger';
export class CreateMakaloDto {
@ApiProperty({ description: "姓名", example: "makalo" })
name: string
@ApiProperty({ description:"年龄", example: "18"})
age: number
}


ApiResponse 自定义返回信息
@ApiResponse({status:403,description:"自定义返回信息"})

ApiBearerAuth jwt token
main.ts 注册
.addBearerAuth()
例:
const options = new DocumentBuilder().addBearerAuth().setTitle('makalo接口文档').setDescription('描述,。。。').setVersion('1').build();

控制器中修饰
@ApiBearerAuth()

添加token



测试



其他装饰器
所有可用的 OpenAPI 装饰器都有一个 Api 前缀,可以清楚地区分核心装饰器。 以下是导出的装饰器的完整列表,以及可以应用装饰器的级别的名称。
@ApiOperation() |
Method |
@ApiResponse() |
Method / Controller |
@ApiProduces() |
Method / Controller |
@ApiConsumes() |
Method / Controller |
@ApiBearerAuth() |
Method / Controller |
@ApiOAuth2() |
Method / Controller |
@ApiBasicAuth() |
Method / Controller |
@ApiSecurity() |
Method / Controller |
@ApiExtraModels() |
Method / Controller |
@ApiBody() |
Method |
@ApiParam() |
Method |
@ApiQuery() |
Method |
@ApiHeader() |
Method / Controller |
@ApiExcludeEndpoint() |
Method |
@ApiTags() |
Method / Controller |
@ApiProperty() |
Model |
@ApiPropertyOptional() |
Model |
@ApiHideProperty() |
Model |
@ApiExtension() |
Model |

浙公网安备 33010602011771号