Skip to main content

Command Palette

Search for a command to run...

Documenting APIs with Swagger in My Workspace

Updated
2 min read

Swagger is helpful to document APIs, which is useful for other developers or for updating the API in the future. It makes it easy to understand endpoints, request/response schemas, and versioning.

Here’s how I implemented Swagger in my project.

Step 1 — Install dependencies

I used zod-to-openapi to generate OpenAPI docs from my Zod schemas:

npm install @asteasolutions/zod-to-openapi
npm install swagger-ui-express

Step 2 — Register your APIs

import { OpenAPIRegistry, OpenApiGeneratorV3 } from "@asteasolutions/zod-to-openapi";
import fs from "fs";
import SwaggerUi from "swagger-ui-express";

// Step 1: Create a registry
const registry = new OpenAPIRegistry();

// Step 2: Register all your API schemas
// Example: registry.registerPath({ ... });

// Step 3: Generate OpenAPI document
const generator = new OpenApiGeneratorV3(registry.definitions);

const openapi = generator.generateDocument({
  openapi: "3.0.0",
  info: {
    title: "API Documentation",
    version: "1.0.0",
    description: "This is the API documentation for our services.",
  },
  servers: [{ url: "http://localhost:6001/api" }],
});

// Step 4: Write it to a file
fs.writeFileSync("openapi.json", JSON.stringify(openapi, null, 2));
  • Registry: Acts as a container[] that holds all API definitions.

  • Generator: Converts the registry into a proper OpenAPI document.

  • Writing to openapi.json: Saves the documentation so it can be served or shared.

Step 3 — Serve Swagger UI

Finally, we can expose Swagger in our Express app:


import express from "express";
const app = express();

app.use("/docs", SwaggerUi.serve, SwaggerUi.setup(openapi));

app.listen(6001, () => console.log("Server running on http://localhost:6001"));

Now, visiting http://localhost:6001/docs will show the interactive Swagger UI with all your registered APIs.

You can check the official documentation to setup the swagger.

@asteasolutions/zod-to-openapi github