Swagger API Documentation
The Swagger API Documentation component provides an automated way to generate and serve interactive API documentation.
It leverages swagger-autogen to parse JSDoc comments in your route files and swagger-ui-express to provide a beautiful web interface for testing your endpoints.
Installation
Install the component using the ServerCN CLI:
npx servercn-cli add swagger-docsWhy Swagger?
- Interactive Testing: Test your API endpoints directly from the browser without Postman or Insomnia.
- Auto-generated: Keep your documentation in sync with your code using JSDoc comments.
- Standardized: Built on the Industry-standard OpenAPI Specification (OAS).
- On-boarding: Makes it easy for frontend developers or third-party consumers to understand your API.
Implementation Guide
1. Configuration
The configuration file defines the metadata for your API and where Swagger should look for documentation comments.
src/swagger.config.ts
2. Run the Script
Run the script to generate the swagger.json file.
It will generate a swagger.json file in the docs directory.
3. Setup Swagger
Create a swagger.ts file in the src/configs directory.
src/configs/swagger.ts
4. Integration with App
Update your main app.ts to initialize the Swagger documentation.
5. Update swagger.json file (Optional)
Update the swagger.json file with the new API documentation.
Accessing the Docs
Once your server is running, navigate to:
http://localhost:8000/api/docs
You will see the Swagger UI dashboard where you can explore and test your API.
Don't forget to run `node src/swagger.config.ts` command and update the base url, routes... in `swagger.json` file.