A librarian looking for notes

Add Swagger API documentation to your Nest app

Adding documentaion can be a tidious task. Luckily, NestJS has a built-in Swagger module that can be used to generate API documentation. In this tutorial, we will learn how to add Swagger to our NestJS app. It's as easy as adding a few lines of code. First things first, let's create a new NestJS app. If you don't have NestJS installed, you can install it by running the following command in your terminal. Next use the nest cli to create a new project and name it whatever you'd like.

        
    npm i -g @nestjs/cli
    nest new swagger-demo
        
      

Next, we will install the Swagger module. First enter the swagger-demo file. Then install the module as a dev dependency because we don't need it in production.

        
    cd swagger-demo
    npm install --save @nestjs/swagger
        
      

Finally we just need to bootstrap the Swagger module. Open the main.ts file and add the following code. Here we are setting up the Swagger module and telling it to use the /api endpoint, and also setting the configuration for the title, description, and version of our documentation.

        
    main.ts
        
      
        
          
    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);
    
      const config = new DocumentBuilder()
        .setTitle('Swagger Api example')
        .setDescription('Swagger API description')
        .setVersion('1.0')
        .addTag('swagger')
        .build();
      const document = SwaggerModule.createDocument(app, config);
      SwaggerModule.setup('api', app, document);
    
      await app.listen(3000);
    }
    bootstrap();
          
        
      
Done!

That's it! Now we can run our app using nest start and navigate to localhost:3000/api to see our documentation. Swagger api automatically generates documentation based on the code we write. It's that easy! For more information on how to set up your endpoints, check out my other tutorial on how to create a CRUD API with NestJS. There I show you how to create you modules, controllers, entities, and much more with one simple command. Feel free to reach out to me on Twitter @GmoMedel if you have any questions.

Swagger API

My Blog