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.
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.
import{NestFactory}from"@nestjs/core";import{AppModule}from"./app.module";import{ConfigService}from"@nestjs/config";import{SwaggerModule,DocumentBuilder}from"@nestjs/swagger";asyncfunctionbootstrap(){constapp=awaitNestFactory.create(AppModule);constconfigService=app.get(ConfigService);// ...constswaggerConfig=newDocumentBuilder().setTitle("API with NestJS").setDescription("API developed throughout the API with NestJS course").setVersion("1.0").build();constdocument=SwaggerModule.createDocument(app,swaggerConfig);SwaggerModule.setup("api",app,document);constport=configService.get("PORT")??3000;awaitapp.listen(port);}bootstrap();
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.
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.
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.
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.
import{IsEmail,IsString,IsNotEmpty,MinLength,Matches}from"class-validator";import{ApiProperty}from"@nestjs/swagger";exportclassRegisterDto{@IsEmail()email:string;@IsString()@IsNotEmpty()name:string;@ApiProperty({deprecated:true,description:"Use the name property instead",})fullName:string;@IsString()@IsNotEmpty()@MinLength(7)password:string;@ApiProperty({description:"Has to match a regular expression: /^\\+[1-9]\\d{1,14}$/",example:"+123123123123",})@IsString()@IsNotEmpty()@Matches(/^\+[1-9]\d{1,14}$/)phoneNumber:string;}exportdefaultRegisterDto;
The CLI plugin can understand the decorators from the class-validator such as @MinLength()
classDemoController{@Get(":id")@ApiParam({name:"id",required:true,description:"Should be an id of a post that exists in the database",type:Number,})@ApiResponse({status:200,description:"A post has been successfully fetched",type:PostEntity,})@ApiResponse({status:404,description:"A post with given id does not exist.",})getPostById(@Param(){id}:FindOneParams){returnthis.postsService.getPostById(Number(id));}}
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.
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.
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.
import{UsersService}from"./users.service";import{BadRequestException,Controller,Post,Req,UploadedFile,UseGuards,UseInterceptors}from"@nestjs/common";importJwtAuthenticationGuardfrom"../authentication/jwt-authentication.guard";importRequestWithUserfrom"../authentication/requestWithUser.interface";import{Express}from"express";importLocalFilesInterceptorfrom"../localFiles/localFiles.interceptor";import{ApiBody,ApiConsumes}from"@nestjs/swagger";importFileUploadDtofrom"./dto/fileUpload.dto";@Controller("users")exportclassUsersController{constructor(privatereadonlyusersService:UsersService){}@Post("avatar")@UseGuards(JwtAuthenticationGuard)@UseInterceptors(LocalFilesInterceptor({fieldName:"file",path:"/avatars",fileFilter:(request,file,callback)=>{if(!file.mimetype.includes("image")){returncallback(newBadRequestException("Provide a valid image"),false);}callback(null,true);},limits:{fileSize:Math.pow(1024,2),// 1MB},}))@ApiConsumes("multipart/form-data")@ApiBody({description:"A new avatar for the user",type:FileUploadDto,})asyncaddAvatar(@Req()request:RequestWithUser,@UploadedFile()file:Express.Multer.File){returnthis.usersService.addAvatar(request.user.id,{path:file.path,filename:file.originalname,mimetype:file.mimetype,});}}