You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NestJS中自定义Swagger JSON文件的生成与下载路径

修改NestJS中Swagger JSON的访问路径

当然有可行方案,直接通过SwaggerModule的配置参数就能自定义JSON文件的访问路径,具体操作如下:

  • 在项目的main.ts(或你配置Swagger的入口文件)中,调用SwaggerModule.setup()方法时,传入额外的配置对象,指定jsonDocumentUrl属性即可。

示例代码:

import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 构建Swagger文档基础配置
  const swaggerConfig = new DocumentBuilder()
    .setTitle('你的API服务')
    .setDescription('API接口文档')
    .setVersion('1.0.0')
    .build();
  const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig);

  // 配置Swagger UI及自定义JSON路径
  SwaggerModule.setup('api', app, swaggerDocument, {
    // 结合第一个参数的基础路径/api,最终JSON路径为/api/openapi.json
    jsonDocumentUrl: 'openapi.json',
  });

  await app.listen(3000);
}
bootstrap();

配置完成后,Swagger JSON的访问路径就会变为http://localhost:3000/api/openapi.json,同时Swagger UI会自动从该路径加载文档,无需额外调整。

如果需要完全独立于UI路径设置JSON路由,也可以手动注册单独路由返回文档:

// 在main.ts中添加该路由
app.get('/api/openapi.json', (req, res) => {
  res.json(swaggerDocument);
});

// 此时Swagger UI可直接指向这个绝对路径
SwaggerModule.setup('api', app, swaggerDocument, {
  jsonDocumentUrl: '/api/openapi.json',
});

两种方式都能满足需求,第一种是官方推荐的简洁配置方式,第二种更适合需要单独控制JSON路由的场景。

内容的提问来源于stack exchange,提问作者Krish909

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:40:46