安装依赖

    1. yarn add @nestjs/swagger swagger-ui-express --save

    配置

    1. import { NestFactory } from '@nestjs/core';
    2. import { AppModule } from './app.module';
    3. import { DocumentBuilder,SwaggerModule} from '@nestjs/swagger'
    4. async function bootstrap() {
    5. const app = await NestFactory.create(AppModule);
    6. const swaggerOptions = new DocumentBuilder()
    7. .setTitle('文档标题')
    8. .setDescription('描述信息')
    9. .setVersion('0.0.1')
    10. .addBasicAuth() // 鉴权?
    11. .build()
    12. // 创建文档到app服务上
    13. const document = SwaggerModule.createDocument(app,swaggerOptions)
    14. // 创建访问的路径
    15. SwaggerModule.setup('docs',app,document)
    16. await app.listen(3000);
    17. }
    18. bootstrap();

    使用

    1. import { Body, Controller, Delete, Get, Param, Post, Put, Query } from '@nestjs/common';
    2. import { ApiBody, ApiParam, ApiQuery, ApiResponse } from '@nestjs/swagger'
    3. @Controller('template')
    4. export class TemplateController {
    5. /**
    6. * get 请求
    7. * localhost:3000/template/?name=123&age=234
    8. */
    9. @ApiQuery({ name: 'name', required: true })
    10. @ApiQuery({ name: 'role', })
    11. @ApiResponse({
    12. status: 200,
    13. description: "reqeeust ok",
    14. })
    15. @Get()
    16. get(@Query() query): object {
    17. return query
    18. }
    19. /**
    20. * post 请求
    21. * localhost:3000/template/
    22. * {
    23. * "name":123,
    24. * "age":345
    25. * }
    26. */
    27. @ApiBody({ description: "请填写内容" })
    28. @Post()
    29. post(@Body() body): object {
    30. return body
    31. }
    32. /**
    33. * put 请求
    34. * localhost:3000/template/123
    35. * name在x-www-form-urlencoded 中传
    36. */
    37. @ApiParam({ name: "id" })
    38. @ApiBody({ description: "请输入id" })
    39. @Put(":id")
    40. put(@Param() { id }, @Body() { name }): string {
    41. return `put id is ${id} - ${name}`
    42. }
    43. /**
    44. * delete 请求
    45. * localhost:3000/template/?id=123
    46. */
    47. @Delete()
    48. @ApiQuery({ name: 'id', required: true })
    49. delete(@Query() { id }): string {
    50. return `del ${id}`
    51. }
    52. }

    访问上面定义好的 http://localhost:3000/docs 就可以看到