NestJS: Ultimate API documentation with Swagger
Swagger is an OpenAPI documentation tool that has become essential in recent years for those who code APIs. On the one hand because it allows to generate API documentation sites at lightning speed and on the other hand for its capacities to generate client proxies from a "swaggerized" API with Swagger CodeGen (an awesome approach, really!)
Swagger allows much more than this thin description but our story would be far too long.
To integrate Swagger into a NestJS project, let's run the following command:
> npm install --save @nestjs/swagger swagger-ui-express
Next we need to update all files "main.ts" in Reader and Writer APIs.
Through this configuration we activate the API versioning and create a specific url to access to Swagger documentation.
Let's launch the 2 applications in our favorites browsers on these URLs:
The documentation is generated but you notice that if you open the "InventoryItemCreateDTO", the schema is empty!
To solve this problem, we need to add some Swagger decorator in targeted objects. The "@ApiProperty()" decorator lets Swagger know that these properties are to display in the description of the APIs.
So let's update our DTOs and add the decorator on each properties:
Refresh browser pages and now the DTO are set with the fixed structure.
Et voila, your documentation is ready!
Mission complete!
Our NestJS tour is over, as you can see, this framework contains an incredible set of possibilities but we can't name them all here!
NestJS is very rich and all the layers it integrates are structured and well self documented. All external integrated libraries are wrapped with quality. In fact, when you use NestJS for the first time, and you have already created APIs in another language, you quickly find yourself on familiar ground because everything is implemented respecting all the best practices!
Thank you for the reading and stay connected for next awesome stories!
The GIT repository to download the code: https://github.com/ExFabrica/nestjs-stories
See U!