OpenAPI (Swagger) module for Nest framework

OpenAPI (Swagger) module for Nest framework

·

2 min read

Introduction

  • The OpenAPI specification is a language-agnostic definition format used to describe RESTful APIs. Nest provides a dedicated module that allows generating such a specification by leveraging decorators.

Installation

  • $ npm i --save @nestjs/swagger

Bootstrap

  • Once the installation process is complete, open the main.ts file and initialize Swagger using the SwaggerModule class
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('Student example')
    .setDescription('The Student API description')
    .setVersion('1.0')
    .addTag('Student')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('swagger', app, document);

  await app.listen(3000);
}
bootstrap();
  • The DocumentBuilder helps to structure a base document that conforms to the OpenAPI Specification. It provides several methods that allow setting such properties as title, description, version, etc. In order to create a full document (with all HTTP routes defined) we use the createDocument() method of the SwaggerModule class. This method takes two arguments, an application instance and a Swagger options object. Alternatively, we can provide a third argument, which should be of type SwaggerDocumentOptions. More on this in the Document options section.
  • Once we create a document, we can call the setup() method.
  1. It accepts:The path to mount the Swagger UI .
  2. An application instance .
  3. The document object instantiated above .
  4. Optional configuration parameter.

    Now you can run the following command to start the HTTP server:

    $ npm run start

    While the application is running, open your browser and navigate to http://localhost:3000/swagger. You should see the Swagger UI.

More Visit Documentation

Did you find this article valuable?

Support Inspriom's by becoming a sponsor. Any amount is appreciated!