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);

image-20230407150624987

訪問

http://localhost:3000/api-docs

image-20230407150827103

現在沒有分組比較亂

使用ApiTags 添加分組

@ApiTags('makalo 分組')

image-20230407152905448

image-20230407152929728

ApiOperation 接口描述

 @ApiOperation({summary:"創建makalo的接口",description:"這是一個創建的接口的描述"})

image-20230407153256076

image-20230407153327216

ApiParam 動態參數描述

@ApiParam({name:"id",description:"用戶id",required:true})

image-20230407153511612

ApiQuery 修飾get

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

image-20230407153713942

image-20230407153746137

ApiProperty 修飾DTO

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

image-20230407161536559

image-20230407161646628

ApiResponse 自定義返回信息

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

image-20230407161939125

ApiBearerAuth jwt token

main.ts 註冊

.addBearerAuth()
例:
const options = new DocumentBuilder().addBearerAuth().setTitle('makalo接口文檔').setDescription('描述,。。。').setVersion('1').build();

image-20230407162821993

控制器中修飾

@ApiBearerAuth()

image-20230407163134199

添加token

image-20230407163613750

image-20230407163316358

image-20230407163339000

測試

image-20230407163734832

image-20230407163756450

image-20230407163828487

其他裝飾器

所有可用的 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章