Across this series, we emphasize code readability and maintainability. In part #52 of this course, we’ve gone through generating documentation with Compodoc and JSDoc. This time we look into the OpenAPI specification and the Swagger tool.
You can check out an interactive demo prepared by the Swagger team.
Introducing OpenAPI and Swagger
With OpenAPI and Swagger, we can create a user interface that serves as interactive API documentation for our project. However, since it might be confusing, it is worth outlining the difference between the OpenAPI and the Swagger.
The OpenAPI is a specification used to describe our API and gives us a way to provide the details of our endpoints. It includes the endpoints and the description of each operation’s inputs and outputs. It also allows us to specify our authentication method, license, and contact information.
Swagger is a set of tools built around the OpenAPI specification. The one that we present in this article is the Swagger UI. It allows us to render the OpenAPI specification we wrote in as the API documentation. The thing that makes it so valuable is that it is interactive. Swagger generates a web page that we can publish so that people can view our API and make HTTP requests. It is a great tool to share knowledge with other people working in our organization. If our API is open to the public, we can also deploy the above page and share it with everyone.
OpenAPI Specification was formerly called the Swagger Specification, which might add more to the confusion.
Adding Swagger to our NestJS project
We need to install two dependencies to add Swagger to our NestJS project.
1npm install @nestjs/swagger swagger-ui-expressIf you use Fastify, install fastify-swagger instead of swagger-ui-express.
To generate the basics of our Swagger UI, we need to use the SwaggerModule and DocumentBuilder from @nestjs/swagger.
1import { NestFactory } from '@nestjs/core';
2import { AppModule } from './app.module';
3import { ConfigService } from '@nestjs/config';
4import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
5
6async function bootstrap() {
7 const app = await NestFactory.create(AppModule);
8
9 const configService = app.get(ConfigService);
10
11 // ...
12
13 const swaggerConfig = new DocumentBuilder()
14 .setTitle('API with NestJS')
15 .setDescription('API developed throughout the API with NestJS course')
16 .setVersion('1.0')
17 .build();
18
19 const document = SwaggerModule.createDocument(app, swaggerConfig);
20 SwaggerModule.setup('api', app, document);
21
22 const port = configService.get('PORT') ?? 3000;
23
24 await app.listen(port);
25}
26bootstrap();The DocumentBuilder class contains a set of methods we can use to configure our Swagger UI.
Besides the above functions such as the setTitle, we will also go through some of the others in this article.
1export declare class DocumentBuilder {
2 private readonly logger;
3 private readonly document;
4 setTitle(title: string): this;
5 setDescription(description: string): this;
6 setVersion(version: string): this;
7 setTermsOfService(termsOfService: string): this;
8 setContact(name: string, url: string, email: string): this;
9 setLicense(name: string, url: string): this;
10 addServer(url: string, description?: string, variables?: Record<string, ServerVariableObject>): this;
11 setExternalDoc(description: string, url: string): this;
12 setBasePath(path: string): this;
13 addTag(name: string, description?: string, externalDocs?: ExternalDocumentationObject): this;
14 addSecurity(name: string, options: SecuritySchemeObject): this;
15 addSecurityRequirements(name: string | SecurityRequirementObject, requirements?: string[]): this;
16 addBearerAuth(options?: SecuritySchemeObject, name?: string): this;
17 addOAuth2(options?: SecuritySchemeObject, name?: string): this;
18 addApiKey(options?: SecuritySchemeObject, name?: string): this;
19 addBasicAuth(options?: SecuritySchemeObject, name?: string): this;
20 addCookieAuth(cookieName?: string, options?: SecuritySchemeObject, securityName?: string): this;
21 build(): Omit<OpenAPIObject, 'paths'>;
22}Doing all of the above generates the Swagger UI and serves it under at http://localhost:3000/api.
The above URL might be different based on the port of your NestJS application.
Generating our OpenAPI specification automatically
Unfortunately, the specification we’ve defined so far does not contain much detail.
We can help NestJS generate a more detailed OpenAPI specification out of the box. To do that, we need to use the CLI plugin "@nestjs/swagger" gives us. To use it, we need to adjust our nest-cli.json file and run nest start.
1{
2 "collection": "@nestjs/schematics",
3 "sourceRoot": "src",
4 "compilerOptions": {
5 "plugins": ["@nestjs/swagger"]
6 }
7}The CLI plugin assumes that our DTOs are suffixed with .dto.ts or .entity.ts. It also assumes that the files that contain controllers end with .controller.ts.
Defining the OpenAPI specification manually
Thanks to using the above solution, we automatically get a significant part of the specification generated. If we want to make some changes, we can use the wide variety of decorators that NestJS gives us.
Models definition
We can use the @ApiProperty() decorator to annotate class properties.
1import { IsEmail, IsString, IsNotEmpty, MinLength, Matches } from 'class-validator';
2import { ApiProperty } from '@nestjs/swagger';
3
4export class RegisterDto {
5 @IsEmail()
6 email: string;
7
8 @IsString()
9 @IsNotEmpty()
10 name: string;
11
12 @ApiProperty({
13 deprecated: true,
14 description: 'Use the name property instead'
15 })
16 fullName: string;
17
18 @IsString()
19 @IsNotEmpty()
20 @MinLength(7)
21 password: string;
22
23 @ApiProperty({
24 description: 'Has to match a regular expression: /^\\+[1-9]\\d{1,14}$/',
25 example: '+123123123123'
26 })
27 @IsString()
28 @IsNotEmpty()
29 @Matches(/^\+[1-9]\d{1,14}$/)
30 phoneNumber: string;
31}
32
33export default RegisterDto;The CLI plugin can understand the decorators from the class-validator such as @MinLength()
Grouping endpoints
All of our endpoints go into the “default” group by default. To categorize them better, we can use the @ApiTags() decorator.
1import {
2 Controller,
3} from '@nestjs/common';
4import PostsService from './posts.service';
5import { ApiTags } from '@nestjs/swagger';
6
7@Controller('posts')
8@ApiTags('posts')
9export default class PostsController {
10 constructor(
11 private readonly postsService: PostsService
12 ) {}
13
14 // ...
15}Describing our endpoints with more details
We can use decorators such as @ApiParam() and @ApiResponse() to provide more details about our endpoints.
1@Get(':id')
2@ApiParam({
3 name: 'id',
4 required: true,
5 description: 'Should be an id of a post that exists in the database',
6 type: Number
7})
8@ApiResponse({
9 status: 200,
10 description: 'A post has been successfully fetched',
11 type: PostEntity
12})
13@ApiResponse({
14 status: 404,
15 description: 'A post with given id does not exist.'
16})
17getPostById(@Param() { id }: FindOneParams) {
18 return this.postsService.getPostById(Number(id));
19}Instead of passing status: 200 and status: 404 we could use the @ApiOkResponse() and @ApiNotFoundResponse() decorators.
Authenticating with cookies
In this series, we use cookie-based authentication. Since many of our endpoints require the user to log in, let’s add this functionality to our OpenAPI specification.
If you want to know more about authentication, check out API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies
Swagger supports a variety of different types of authentication. Unfortunately, it currently does not support sending cookies when using the “Try it out” button. We can deal with this issue by using the Swagger interface to directly log in to our API.
In our application, we have the /log-in endpoint. A lot of its logic happens in the LocalAuthenticationGuard. Therefore, the CLI plugin does not note that the user needs to provide an email and a password. Let’s fix that using the @ApiBody() decorator.
1@HttpCode(200)
2@UseGuards(LocalAuthenticationGuard)
3@Post('log-in')
4@ApiBody({ type: LogInDto })
5async logIn(@Req() request: RequestWithUser) {
6 const { user } = request;
7 const accessTokenCookie = this.authenticationService.getCookieWithJwtAccessToken(user.id);
8 const {
9 cookie: refreshTokenCookie,
10 token: refreshToken
11 } = this.authenticationService.getCookieWithJwtRefreshToken(user.id);
12
13 await this.usersService.setCurrentRefreshToken(refreshToken, user.id);
14
15 request.res.setHeader('Set-Cookie', [accessTokenCookie, refreshTokenCookie]);
16
17 if (user.isTwoFactorAuthenticationEnabled) {
18 return;
19 }
20
21 return user;
22}We now can use the “Try it out” button to send a request to the /log-in endpoint.
Performing the above request sets the right cookie in our browser. Thanks to that, we will send this cookie when interacting with other endpoints automatically.
Handling file uploads
In part #55 of this series, we’ve implemented a way to upload files and store them on our server. To reflect that in Swagger, we can use the @ApiBody() and @ApiConsumes() decorators.
1import { UsersService } from './users.service';
2import { BadRequestException, Controller, Post, Req, UploadedFile, UseGuards, UseInterceptors } from '@nestjs/common';
3import JwtAuthenticationGuard from '../authentication/jwt-authentication.guard';
4import RequestWithUser from '../authentication/requestWithUser.interface';
5import { Express } from 'express';
6import LocalFilesInterceptor from '../localFiles/localFiles.interceptor';
7import { ApiBody, ApiConsumes } from '@nestjs/swagger';
8import FileUploadDto from './dto/fileUpload.dto';
9
10@Controller('users')
11export class UsersController {
12 constructor(
13 private readonly usersService: UsersService,
14 ) {}
15
16 @Post('avatar')
17 @UseGuards(JwtAuthenticationGuard)
18 @UseInterceptors(LocalFilesInterceptor({
19 fieldName: 'file',
20 path: '/avatars',
21 fileFilter: (request, file, callback) => {
22 if (!file.mimetype.includes('image')) {
23 return callback(new BadRequestException('Provide a valid image'), false);
24 }
25 callback(null, true);
26 },
27 limits: {
28 fileSize: Math.pow(1024, 2) // 1MB
29 }
30 }))
31 @ApiConsumes('multipart/form-data')
32 @ApiBody({
33 description: 'A new avatar for the user',
34 type: FileUploadDto,
35 })
36 async addAvatar(@Req() request: RequestWithUser, @UploadedFile() file: Express.Multer.File) {
37 return this.usersService.addAvatar(request.user.id, {
38 path: file.path,
39 filename: file.originalname,
40 mimetype: file.mimetype
41 });
42 }
43}1import { ApiProperty } from '@nestjs/swagger';
2import { Express } from 'express';
3
4class FileUploadDto {
5 @ApiProperty({ type: 'string', format: 'binary' })
6 file: Express.Multer.File;
7}
8
9export default FileUploadDto;Doing the above creates an interface in Swagger UI where we can upload our image.
Summary
We’ve gone through the OpenAPI specification and the Swagger UI tool in this article. We’ve used the CLI plugin to get a lot out of the box. Still, there were some cases that we had to cover manually using different decorators that NestJS gives us. We’ve also dealt with cookie authentication and file uploads. The above gave us the necessary knowledge to create robust, interactive documentation.