Document Your API: OpenAPI, Swagger UI and Postman

Node.js and Express: Build a Back End API from Scratch · Express Structure and REST in Depth · 8 min read · Updated

One file, three uses

  1. You describe the API once in an OpenAPI file and keep it in Git.
  2. Swagger UI turns the file into pages where each endpoint can be tried.
  3. Postman imports the same file into a ready collection of requests.
  4. The front-end developer builds against the agreement without asking you.

An API without documentation is only half finished. The front-end developer, the mobile developer and your own future self all need to know the URLs, the fields and the possible errors. Writing that in a chat message goes out of date in a week. The standard solution is an OpenAPI file: a machine-readable description of the API. Tools turn that one file into interactive pages, test requests and even client code.

What an OpenAPI file contains

OpenAPI, which many people still call by its old name Swagger, is a JSON or YAML file with a fixed structure. It lists each path, each method on that path, the parameters it accepts, the body it expects, and every response it can return, with the status code and shape. The components section holds shapes you reuse, such as a Product, so you describe them once. The file for our product API is below. Read the paths first, then components.

{
  "openapi": "3.0.3",
  "info": { "title": "Products API", "version": "1.0.0", "description": "A small API used to learn OpenAPI." },
  "servers": [{ "url": "http://localhost:3000" }],
  "paths": {
    "/api/v1/products": {
      "get": {
        "summary": "List products",
        "parameters": [
          { "name": "page", "in": "query", "schema": { "type": "integer", "minimum": 1, "default": 1 } },
          { "name": "limit", "in": "query", "schema": { "type": "integer", "minimum": 1, "maximum": 50, "default": 10 } },
          { "name": "category", "in": "query", "schema": { "type": "string", "enum": ["books", "games", "tools"] } }
        ],
        "responses": {
          "200": {
            "description": "A page of products",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProductPage" } } }
          }
        }
      },
      "post": {
        "summary": "Create a product",
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/NewProduct" } } }
        },
        "responses": {
          "201": { "description": "Created", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Product" } } } },
          "409": { "description": "A product with this name already exists" },
          "422": { "description": "Invalid input" }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "Product": {
        "type": "object",
        "properties": {
          "id": { "type": "integer" },
          "name": { "type": "string" },
          "price": { "type": "number" },
          "category": { "type": "string" }
        }
      },
      "NewProduct": {
        "type": "object",
        "required": ["name", "price"],
        "properties": {
          "name": { "type": "string" },
          "price": { "type": "number", "minimum": 0 },
          "category": { "type": "string" }
        }
      },
      "ProductPage": {
        "type": "object",
        "properties": {
          "data": { "type": "array", "items": { "$ref": "#/components/schemas/Product" } },
          "meta": { "type": "object", "properties": { "page": { "type": "integer" }, "total": { "type": "integer" } } }
        }
      }
    }
  }
}

Notice that the file documents the errors as well as the success cases. A client developer needs to know that a missing item returns 404 and that a wrong body returns 422 with a list of problems. Good documentation answers the question "what can go wrong?", not only "what do I send?".

Serving interactive docs with Swagger UI

Swagger UI reads the file and draws a web page where each endpoint can be opened, filled in and tried with a button. With the swagger-ui-express package it takes three lines. You also serve the raw file at /openapi.json, because other tools, such as Postman, can import it from there.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install express swagger-ui-express.
  3. Save the OpenAPI file as r21-openapi.json next to the code. For the test, install npm install -D supertest.
import express from 'express';
import swaggerUi from 'swagger-ui-express';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';

const spec = JSON.parse(fs.readFileSync(fileURLToPath(new URL('./r21-openapi.json', import.meta.url)), 'utf8'));

export function createDocsApp() {
  const app = express();
  app.get('/openapi.json', (req, res) => res.json(spec));          // for tools and code generators
  app.use('/docs', swaggerUi.serve, swaggerUi.setup(spec));         // the interactive page
  return app;
}
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createDocsApp } from './r21-docs.js';

test('the spec and the docs page are served', async () => {
  const app = createDocsApp();
  const spec = await request(app).get('/openapi.json');
  assert.equal(spec.body.openapi, '3.0.3');
  assert.ok(spec.body.paths['/api/v1/products'].post);

  const page = await request(app).get('/docs/');
  assert.equal(page.status, 200);
  assert.match(page.text, /swagger-ui/);
});

The test confirms that the spec is served as JSON and that the docs page loads. The docs usually live at a path such as /docs. In a real product, think about whether the documentation should be public. Public APIs benefit from open docs. For a private internal API, put the docs behind a login or serve them only in development, because they give an attacker a complete map of your endpoints.

Keeping the file true

The danger is a document that disagrees with the code. There are two ways to avoid it. You can write the spec first and build the code to match, which makes the file the agreement between front end and back end. Or you can generate the spec from comments or schemas in the code, for example with Zod and a conversion library. Whichever you choose, add a test that checks real replies against the described shapes, and review the file in every pull request that changes an endpoint.

Testing by hand with Postman

Postman is an app for sending requests and saving them. Import http://localhost:3000/openapi.json and it creates a collection with one request for every endpoint. Use an *environment* with a variable such as baseUrl, so the same collection works on your laptop and on the live server by switching one setting. Postman can also run simple checks on each reply, for example that the status is 201 and the body has an id, and can run a whole collection in a row, which is a gentle introduction to automated API tests. Insomnia and the VS Code extension Thunder Client do the same job, and curl always works from a terminal.

  • Document every status code you return, including 401, 403, 404 and 422.
  • Give each field a type and one example value.
  • Never put real passwords, tokens or customer data in examples.
  • Commit the spec to Git so its history shows when the API changed.

Your task

  1. Add the DELETE operation to the file and see it appear in the docs page.
  2. Import the spec in Postman and send a request to create a product.
  3. Protect /docs so that it only loads when NODE_ENV is not production.

How to check it worked

  • /openapi.json returns the spec.
  • /docs shows every endpoint and the Try it out button works.
  • You can say which status codes each endpoint can return without opening the code.

Frequently asked questions

Is Swagger the same as OpenAPI?

OpenAPI is the specification. Swagger was its old name and is now the name of a set of tools, such as Swagger UI, that read it.

Should my API docs be public?

For a public API, yes. For an internal API, serve them only in development or behind a login.

How do I stop the docs going out of date?

Write the spec first or generate it from your schemas, and add a test that compares real replies with the described shapes.

Practise with interview questions