[SOLVED] How to use externally generated swagger.json in NestJS?


This Content is from Stack Overflow. Question asked by Kamalakannan J

I have generated swagger.yaml/swagger.json from external documentation library. Now, I wanted to import and host that as API documentation on my API platform which is running on NestJS. I know, we can generate and export swagger from NestJS code, but for me the need is reverse, we have the swagger.json, we need to render it in the NestJS platform, like https://example.com/docs


If you already have a swagger.json file you can ignore the SwaggerModule.createDocument and the DocumentBuilder and just pass the parsed JSON file to SwaggerModule.setup()

import { NestFactory } from '@nestjs/core';
import { SwaggerModule } from '@nestjs/swagger';
import { readFile } from 'fs/promises';
import { path } from 'join';
import { AppModule } from './app.module';

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

  // read the JSON file to string and parse the string to object literal
  const document = JSON.parse(
    (await readFile(join(process.cwd(), 'swagger.json'))).toString('utf-8')
  SwaggerModule.setup('api', app, document);

  await app.listen(3000);

This Question was asked in StackOverflow by Kamalakannan J and Answered by Jay McDoniel It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?