OpenAPI/Swagger — Document Your REST API

Sanjeev SharmaSanjeev Sharma
2 min read

Advertisement

OpenAPI (formerly Swagger) is the standard for API documentation. Interactive docs and client generation.

Swagger-UI with Express

npm install swagger-ui-express swagger-jsdoc
npm install --save-dev @types/swagger-ui-express @types/swagger-jsdoc
import swaggerUi from "swagger-ui-express";
import swaggerJsdoc from "swagger-jsdoc";

const options = {
  definition: {
    openapi: "3.0.0",
    info: {
      title: "My API",
      version: "1.0.0",
      description: "API documentation",
    },
    servers: [{ url: "http://localhost:3000" }],
  },
  apis: ["./routes/*.ts"],
};

const specs = swaggerJsdoc(options);
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(specs));

JSDoc Comments

/**
 * @swagger
 * /users:
 *   get:
 *     summary: Get all users
 *     responses:
 *       200:
 *         description: List of users
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/User'
 */
app.get("/users", (req, res) => {
  res.json([]);
});

/**
 * @swagger
 * /users:
 *   post:
 *     summary: Create user
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/CreateUserInput'
 *     responses:
 *       201:
 *         description: User created
 */
app.post("/users", (req, res) => {
  res.status(201).json({ id: 1 });
});

Schemas

/**
 * @swagger
 * components:
 *   schemas:
 *     User:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *         name:
 *           type: string
 *         email:
 *           type: string
 *           format: email
 *     CreateUserInput:
 *       type: object
 *       required:
 *         - name
 *         - email
 *       properties:
 *         name:
 *           type: string
 *         email:
 *           type: string
 */

FAQ

Q: Should I use Swagger? A: Yes, for REST APIs. Auto-docs save time and keep documentation current.

Q: Can I generate code from OpenAPI? A: Yes, with openapi-generator or similar tools.

Q: GraphQL alternative? A: GraphQL has built-in documentation. Less need for Swagger.


OpenAPI/Swagger is industry standard for REST API documentation.

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro