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-docs

Why 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

The configuration file defines the metadata for your API and where Swagger should look for documentation comments.

src/swagger.config.ts
import swaggerAutoGen from "swagger-autogen";
 
const doc = {
  info: {
    title: "Stateless Auth API",
    description: "Stateless Auth API",
    version: "1.0.0"
  },
  host: "localhost:8000",
  schemes: ["http"]
};
 
const outputFile = "./docs/swagger.json"; // Output file for the generated docs
const endpointsFiles = ["./routes/*.ts"]; // Endpoints files to be parsed
 
swaggerAutoGen(outputFile, endpointsFiles, doc);

Run the script to generate the swagger.json file.

node src/swagger.config.ts

It will generate a swagger.json file in the docs directory.

Create a swagger.ts file in the src/configs directory.

src/configs/swagger.ts
import swaggerUi from "swagger-ui-express";
import { Express } from "express";
 
import swaggerDocument from "../docs/swagger.json"; // Generated by swagger-autogen by running `node src/swagger.config.ts`
 
export const setupSwagger = (app: Express) => {
  app.use("/api/docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));
};

Update your main app.ts to initialize the Swagger documentation.

import express from "express";
import { setupSwagger } from "./configs/swagger";
 
const app = express();
 
// Initialize Swagger
setupSwagger(app);
 
app.listen(8000, () => {
  console.log("Server started on port 8000");
  console.log("Swagger docs available at http://localhost:8000/api/docs");
});

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.

File & Folder Structure

ServerCN

Select a file to view its contents

Installation

npx servercn-cli add swagger-docs