Introduction

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

Installation

To begin using it, we first install the required dependencies.

  1. $ npm install --save @nestjs/swagger swagger-ui-express

If you use fastify, install fastify-swagger instead of swagger-ui-express:

  1. $ npm install --save @nestjs/swagger fastify-swagger

Bootstrap

Once the installation process is complete, open the main.ts file and initialize Swagger using the SwaggerModule class:

  1. @@filename(main)
  2. import { NestFactory } from '@nestjs/core';
  3. import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
  4. import { AppModule } from './app.module';
  5. async function bootstrap() {
  6. const app = await NestFactory.create(AppModule);
  7. const config = new DocumentBuilder()
  8. .setTitle('Cats example')
  9. .setDescription('The cats API description')
  10. .setVersion('1.0')
  11. .addTag('cats')
  12. .build();
  13. const document = SwaggerModule.createDocument(app, config);
  14. SwaggerModule.setup('api', app, document);
  15. await app.listen(3000);
  16. }
  17. bootstrap();

info Hint document (returned by the SwaggerModule#createDocument() method) is a serializable object conforming to OpenAPI Document. Instead of hosting it via HTTP, you could also save it as a JSON/YAML file, and consume it in different ways.

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. It accepts:

  1. The path to mount the Swagger UI
  2. An application instance
  3. The document object instantiated above
  4. Optional configuration parameter (read more here)

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

  1. $ npm run start

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

Introduction - 图1

The SwaggerModule automatically reflects all of your endpoints. Note that the Swagger UI is created using either swagger-ui-express or fastify-swagger, depending on the platform.

info Hint To generate and download a Swagger JSON file, navigate to http://localhost:3000/api-json (swagger-ui-express) or http://localhost:3000/api/json (fastify-swagger) in your browser (assuming that your Swagger documentation is available under http://localhost:3000/api).

warning Warning When using fastify-swagger and helmet, there may be a problem with CSP, to solve this collision, configure the CSP as shown below:

  1. app.register(helmet, {
  2. contentSecurityPolicy: {
  3. directives: {
  4. defaultSrc: [`'self'`],
  5. styleSrc: [`'self'`, `'unsafe-inline'`],
  6. imgSrc: [`'self'`, 'data:', 'validator.swagger.io'],
  7. scriptSrc: [`'self'`, `https: 'unsafe-inline'`],
  8. },
  9. },
  10. });
  11. // If you are not going to use CSP at all, you can use this:
  12. app.register(helmet, {
  13. contentSecurityPolicy: false,
  14. });

Document options

When creating a document, it is possible to provide some extra options to fine tune the library’s behavior. These options should be of type SwaggerDocumentOptions, which can be the following:

  1. export interface SwaggerDocumentOptions {
  2. /**
  3. * List of modules to include in the specification
  4. */
  5. include?: Function[];
  6. /**
  7. * Additional, extra models that should be inspected and included in the specification
  8. */
  9. extraModels?: Function[];
  10. /**
  11. * If `true`, swagger will ignore the global prefix set through `setGlobalPrefix()` method
  12. */
  13. ignoreGlobalPrefix?: boolean;
  14. /**
  15. * If `true`, swagger will also load routes from the modules imported by `include` modules
  16. */
  17. deepScanRoutes?: boolean;
  18. /**
  19. * Custom operationIdFactory that will be used to generate the `operationId`
  20. * based on the `controllerKey` and `methodKey`
  21. * @default () => controllerKey_methodKey
  22. */
  23. operationIdFactory?: (controllerKey: string, methodKey: string) => string;
  24. }

For example, if you want to make sure that the library generates operation names like createUser instead of UserController_createUser, you can set the following:

  1. const options: SwaggerDocumentOptions = {
  2. operationIdFactory: (
  3. controllerKey: string,
  4. methodKey: string
  5. ) => methodKey
  6. };
  7. const document = SwaggerModule.createDocument(app, config, options);

Setup options

You can configure Swagger UI by passing the options object which fulfills the ExpressSwaggerCustomOptions (if you use express) interface as a fourth argument of the SwaggerModule#setup method.

  1. export interface ExpressSwaggerCustomOptions {
  2. explorer?: boolean;
  3. swaggerOptions?: Record<string, any>;
  4. customCss?: string;
  5. customCssUrl?: string;
  6. customJs?: string;
  7. customfavIcon?: string;
  8. swaggerUrl?: string;
  9. customSiteTitle?: string;
  10. validatorUrl?: string;
  11. url?: string;
  12. urls?: Record<'url' | 'name', string>[];
  13. }

If you use fastify, you can configure the user interface by passing the FastifySwaggerCustomOptions object.

  1. export interface FastifySwaggerCustomOptions {
  2. uiConfig?: Record<string, any>;
  3. }

For example, if you want to make sure that the authentication token persists after refreshing the page, or change the page title (that shows up in the browser), you can use the following settings:

  1. const customOptions: SwaggerCustomOptions = {
  2. swaggerOptions: {
  3. persistAuthorization: true,
  4. },
  5. customSiteTitle: 'My API Docs',
  6. };
  7. SwaggerModule.setup('docs', app, document, customOptions);

Example

A working example is available here.