Search code examples
node.jsswaggernestjs

How to use externally generated swagger.json in NestJS?


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


Solution

  • 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 { join } from 'path';
    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);
    }
    bootstrap();