API Documentation with Swagger
A frontend dev pings you asking what POST /users returns on a validation error. You check the controller, then the form request, then the exception handler, and ten minutes later you've answered one question. Next week someone else asks the same thing. If the only documentation for your API is the code itself, every consumer pays that cost again and again.
Swagger tooling, built around the OpenAPI Specification, lets you describe the API once and get interactive docs, generated clients, and contract tests out of that one file. This post covers writing the spec, serving Swagger UI from Express and Laravel, documenting auth, validating the spec in CI, and a few things that tend to break once you put it in front of real users.
OpenAPI Specification (OAS) is the vendor-neutral, open standard that describes REST APIs. Swagger is the original name (donated to the Linux Foundation in 2016). Today it refers to the tools that work with OAS documents: Swagger UI, Swagger Editor, and Swagger Codegen. When people say "Swagger docs" they usually mean an OpenAPI 3.x spec rendered by Swagger UI.
Understanding the OpenAPI Specification
The spec itself is just a JSON or YAML file listing your endpoints, request parameters, response shapes, auth schemes, and so on. OpenAPI 3.1 is the current version (fully aligned with JSON Schema draft 2020-12), but 3.0.x still has the widest tooling support, so I'm using 3.0 throughout.
Here's a small but complete 3.0 document:
openapi: 3.0.3
info:
title: User Management API
description: CRUD operations for managing users
version: 1.0.0
contact:
name: Mayur Dabhi
email: mayurdabhi.6@gmail.com
servers:
- url: https://api.example.com/v1
description: Production
- url: http://localhost:3000/v1
description: Local development
paths:
/users:
get:
summary: List all users
operationId: listUsers
tags: [Users]
parameters:
- name: page
in: query
schema:
type: integer
default: 1
- name: limit
in: query
schema:
type: integer
default: 20
maximum: 100
responses:
'200':
description: Paginated list of users
content:
application/json:
schema:
$ref: '#/components/schemas/UserList'
'401':
$ref: '#/components/responses/Unauthorized'
post:
summary: Create a user
operationId: createUser
tags: [Users]
security:
- BearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserRequest'
responses:
'201':
description: User created
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'422':
$ref: '#/components/responses/ValidationError'
components:
schemas:
User:
type: object
properties:
id:
type: integer
example: 42
name:
type: string
example: Jane Doe
email:
type: string
format: email
example: jane@example.com
createdAt:
type: string
format: date-time
CreateUserRequest:
type: object
required: [name, email, password]
properties:
name:
type: string
minLength: 2
maxLength: 100
email:
type: string
format: email
password:
type: string
minLength: 8
UserList:
type: object
properties:
data:
type: array
items:
$ref: '#/components/schemas/User'
meta:
type: object
properties:
total: { type: integer }
page: { type: integer }
limit: { type: integer }
responses:
Unauthorized:
description: Missing or invalid token
content:
application/json:
schema:
type: object
properties:
message: { type: string, example: Unauthenticated }
ValidationError:
description: Validation failed
content:
application/json:
schema:
type: object
properties:
message: { type: string }
errors:
type: object
additionalProperties:
type: array
items: { type: string }
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
Most of what matters lives in three sections: paths (your endpoints), components (reusable schemas, responses, and security schemes), and info (metadata). Point to components with $ref and you define a schema once, then reuse it across as many endpoints as you like.
Swagger UI with Node.js and Express
In an Express app, the quickest setup I know is swagger-ui-express to serve the UI plus swagger-jsdoc to build the spec from comments in your route files.
Install the packages
Add swagger-ui-express and swagger-jsdoc to your project.
npm install swagger-ui-express swagger-jsdoc
Configure swagger-jsdoc
Create a swagger.js config that tells swagger-jsdoc where your JSDoc annotations live.
const swaggerJsdoc = require('swagger-jsdoc');
const options = {
definition: {
openapi: '3.0.3',
info: {
title: 'My API',
version: '1.0.0',
description: 'REST API documentation',
},
servers: [
{ url: 'http://localhost:3000', description: 'Development' },
],
components: {
securitySchemes: {
BearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
},
},
},
},
// Scan all route files for JSDoc annotations
apis: ['./src/routes/*.js', './src/models/*.js'],
};
module.exports = swaggerJsdoc(options);
Mount Swagger UI in Express
Add two lines to your main app.js to serve the interactive docs at /api-docs.
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./swagger');
const app = express();
app.use(express.json());
// Serve Swagger UI at /api-docs
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, {
customCss: '.swagger-ui .topbar { display: none }',
customSiteTitle: 'My API Docs',
swaggerOptions: {
persistAuthorization: true, // keep auth tokens across page refreshes
},
}));
// Export the spec as JSON for CI tooling
app.get('/api-docs.json', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(swaggerSpec);
});
// Your routes
app.use('/v1/users', require('./routes/users'));
app.listen(3000, () => console.log('API running on http://localhost:3000'));
module.exports = app;
Annotate your routes with JSDoc
swagger-jsdoc reads these comments and merges them into the spec. Indentation matters here: the comment body is parsed as YAML, so one misaligned line can silently drop an endpoint from the output.
const router = require('express').Router();
const UserController = require('../controllers/UserController');
/**
* @openapi
* /v1/users:
* get:
* summary: List all users
* tags: [Users]
* parameters:
* - in: query
* name: page
* schema:
* type: integer
* default: 1
* - in: query
* name: limit
* schema:
* type: integer
* default: 20
* responses:
* 200:
* description: Array of users
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/components/schemas/User'
* 401:
* description: Unauthorized
*/
router.get('/', UserController.index);
/**
* @openapi
* /v1/users:
* post:
* summary: Create a new user
* tags: [Users]
* security:
* - BearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/CreateUserRequest'
* responses:
* 201:
* description: User created successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/User'
* 422:
* description: Validation error
*/
router.post('/', UserController.store);
module.exports = router;
You can define components/schemas inside a JSDoc comment in any file. I usually put them in a src/schemas/ folder or next to the Mongoose/Sequelize models. Start the comment block with @openapi (preferred) or @swagger (legacy), and make sure the file path is covered by the apis globs, or the schemas won't be picked up.
/**
* @openapi
* components:
* schemas:
* User:
* type: object
* properties:
* id:
* type: integer
* example: 1
* name:
* type: string
* example: Jane Doe
* email:
* type: string
* format: email
* example: jane@example.com
* createdAt:
* type: string
* format: date-time
*
* CreateUserRequest:
* type: object
* required: [name, email, password]
* properties:
* name:
* type: string
* minLength: 2
* maxLength: 100
* email:
* type: string
* format: email
* password:
* type: string
* minLength: 8
* writeOnly: true
*/
// This file only holds schema definitions, so no JS exports are needed
Swagger in Laravel with L5-Swagger
On the Laravel side, most projects use L5-Swagger. It wraps zircote/swagger-php in a service provider, reads PHP 8 attributes (or PHPDoc annotations) from your controllers, and generates the OpenAPI spec when you ask it to.
# Install L5-Swagger
composer require "darkaonline/l5-swagger"
# Publish config and views
php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"
# Generate the spec (run whenever you update annotations)
php artisan l5-swagger:generate
The UI is served at /api/documentation by default. The spec path, annotation scan paths, and auth presets live in config/l5-swagger.php.
One gotcha: if l5-swagger:generate fails with Required @OA\Info() not found (or Required @OA\PathItem() not found), swagger-php didn't find your annotations at all. Check that the annotations paths in the config include the folder holding your #[OA\Info] class and controllers. Also remember the generated JSON is a build artifact: either run the generate command in your deploy script or set L5_SWAGGER_GENERATE_ALWAYS=true locally, otherwise you'll be staring at a stale spec.
Annotating Laravel Controllers
L5-Swagger supports both PHP 8 native attributes and the older PHPDoc-style annotations. I'd go with attributes on any new project, since your IDE and static analysis tools actually understand them:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
#[OA\Tag(name: 'Users', description: 'User management endpoints')]
class UserController extends Controller
{
#[OA\Get(
path: '/api/v1/users',
summary: 'List all users',
tags: ['Users'],
parameters: [
new OA\Parameter(name: 'page', in: 'query', schema: new OA\Schema(type: 'integer')),
new OA\Parameter(name: 'per_page', in: 'query', schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(response: 200, description: 'Paginated users'),
new OA\Response(response: 401, description: 'Unauthenticated'),
]
)]
public function index(Request $request)
{
return User::paginate($request->per_page ?? 15);
}
#[OA\Post(
path: '/api/v1/users',
summary: 'Create a user',
tags: ['Users'],
security: [['sanctum' => []]],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(ref: '#/components/schemas/CreateUserRequest')
),
responses: [
new OA\Response(
response: 201,
description: 'User created',
content: new OA\JsonContent(ref: '#/components/schemas/User')
),
new OA\Response(response: 422, description: 'Validation error'),
]
)]
public function store(Request $request)
{
$data = $request->validate([
'name' => 'required|string|max:100',
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
]);
return response()->json(User::create($data), 201);
}
}
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\User;
class UserController extends Controller
{
/**
* @OA\Get(
* path="/api/v1/users",
* summary="List all users",
* tags={"Users"},
* @OA\Parameter(
* name="page",
* in="query",
* @OA\Schema(type="integer")
* ),
* @OA\Response(
* response=200,
* description="Paginated users",
* @OA\JsonContent(ref="#/components/schemas/UserCollection")
* ),
* @OA\Response(response=401, description="Unauthenticated")
* )
*/
public function index()
{
return User::paginate(15);
}
}
The global OpenAPI info block (version, title, servers, security) is typically placed in a dedicated class:
<?php
namespace App\Http\Controllers\Api;
use OpenApi\Attributes as OA;
#[OA\Info(
title: 'My Laravel API',
version: '1.0.0',
description: 'REST API documentation',
contact: new OA\Contact(
name: 'Mayur Dabhi',
email: 'mayurdabhi.6@gmail.com'
)
)]
#[OA\Server(
url: 'https://api.example.com',
description: 'Production server'
)]
#[OA\Server(
url: 'http://localhost:8000',
description: 'Local development'
)]
#[OA\SecurityScheme(
securityScheme: 'sanctum',
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT'
)]
class OpenApiSpec {}
// This class has no methods. It only carries the attribute-based spec metadata
Swagger UI Request / Response Flow
Swagger UI is a static page that runs in the browser. Once you know that, most of the auth and CORS errors people hit in production stop being mysterious.
How Swagger UI loads the spec and executes live API requests
"Try it out" sends real HTTP requests from the user's browser straight to your API. If Swagger UI is hosted on a different origin than the API, the API has to return an Access-Control-Allow-Origin header for the docs domain, or the browser blocks the call. In Swagger UI that usually shows up as a vague "Failed to fetch" with no status code, so check the browser console for the real CORS error. And don't fix it by slapping * on authenticated endpoints.
Documenting Authentication
OpenAPI 3.0 has four security scheme types: HTTP (Bearer/Basic), API key (header, query, or cookie), OAuth 2.0, and OpenID Connect. Here are the ones you'll use most, plus how to turn auth off for a single public endpoint:
components:
securitySchemes:
# JWT Bearer token (most common for REST APIs)
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
# API key in header
ApiKeyHeader:
type: apiKey
in: header
name: X-API-Key
# API key in query param (less secure, avoid for sensitive endpoints)
ApiKeyQuery:
type: apiKey
in: query
name: api_key
# OAuth2 Authorization Code flow
OAuth2:
type: oauth2
flows:
authorizationCode:
authorizationUrl: https://auth.example.com/oauth/authorize
tokenUrl: https://auth.example.com/oauth/token
scopes:
read:users: Read user data
write:users: Create and update users
admin: Full administrative access
# Apply security globally (can be overridden per-endpoint)
security:
- BearerAuth: []
paths:
/public/status:
get:
summary: Health check (no auth required)
security: [] # Override to remove auth for this endpoint
responses:
'200':
description: API is running
/users/{id}:
get:
summary: Get user by ID
security:
- BearerAuth: [] # JWT OR
- ApiKeyHeader: [] # API key (user can use either)
parameters:
- name: id
in: path
required: true
schema:
type: integer
Securing the Swagger UI itself
Your docs are a map of every endpoint you have, so think about who should see /api-docs in production. Three common options:
// Option 1: Disable entirely in production
if (process.env.NODE_ENV !== 'production') {
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
}
// Option 2: Basic auth protection
const basicAuth = require('express-basic-auth');
app.use('/api-docs',
basicAuth({
users: { [process.env.DOCS_USER]: process.env.DOCS_PASS },
challenge: true,
}),
swaggerUi.serve,
swaggerUi.setup(swaggerSpec)
);
// Option 3: IP allowlist (for internal tools)
app.use('/api-docs', (req, res, next) => {
const ip = req.ip;
const allowed = ['127.0.0.1', '10.0.0.0/8'];
if (!allowed.some(range => ip.startsWith(range.split('/')[0]))) {
return res.status(403).json({ message: 'Forbidden' });
}
next();
}, swaggerUi.serve, swaggerUi.setup(swaggerSpec));
Treat option 3 as a sketch, not something to paste into production. The prefix check doesn't really understand CIDR ranges (10.0.0.0/8 becomes a match on "10.0.0.0"), Node often reports IPv4 clients as ::ffff:127.0.0.1, and behind a load balancer req.ip is the proxy's address unless you set app.set('trust proxy', ...). Use a proper library such as ipaddr.js if you go this route.
Spec Validation and Contract Testing
A spec nobody checks will drift away from the code within a few releases. The fix is to treat it as a contract your implementation has to satisfy, and there are several tools that check exactly that:
| Tool | What it validates | When to use |
|---|---|---|
| openapi-validator (IBM) | Spec linting: checks spec quality and style rules | Pre-commit / CI on the YAML file |
| schemathesis | Property-based testing: generates requests from the spec and fires them at your API | Integration test suite, fuzzing |
| dredd | Response contract: checks that real API responses match the spec | CI pipeline against staging |
| express-openapi-validator | Runtime request/response validation (middleware) | Development server, catches drift immediately |
| Spectral | Customizable linting with rulesets | Enforcing API design standards |
npm install express-openapi-validator
const OpenApiValidator = require('express-openapi-validator');
const path = require('path');
app.use(
OpenApiValidator.middleware({
apiSpec: path.join(__dirname, 'openapi.yaml'), // or your spec JSON
validateRequests: true, // validate incoming request bodies, params, headers
validateResponses: true, // validate outgoing response bodies (dev only)
})
);
// The validator throws structured errors that you catch with a global handler
app.use((err, req, res, next) => {
res.status(err.status || 500).json({
message: err.message,
errors: err.errors,
});
});
With validateResponses: true on in development, any response that doesn't match the spec turns into a 500 with details about which field was wrong. Annoying the first day, but it catches drift before your consumers do. Two things to watch: register the validator before your routes, and keep response validation off in production, because it adds work to every request and turns a harmless extra field into an outage.
Swagger Tooling Ecosystem
Once the spec exists, Swagger UI is only one of the things that can read it:
Code Generation with OpenAPI Generator
OpenAPI Generator produces typed API clients in 50+ languages from your spec. You stop hand-writing HTTP client code, and regenerating the client after an API change keeps it in sync:
# Install via Homebrew (macOS/Linux)
brew install openapi-generator
# Generate a TypeScript/Fetch client
openapi-generator-cli generate \
-i https://api.example.com/api-docs.json \
-g typescript-fetch \
-o ./generated/api-client
# Generate a Python client
openapi-generator-cli generate \
-i openapi.yaml \
-g python \
-o ./generated/python-client
# Generate server stubs (Express, Spring, Laravel, etc.)
openapi-generator-cli generate \
-i openapi.yaml \
-g nodejs-express-server \
-o ./generated/server
The generated TypeScript client has type definitions for every schema, so passing the wrong parameters fails at compile time instead of at runtime. That's only as good as the spec, though: if the spec says a field is a string and the API returns null, the types will lie to you.
Postman Import from OpenAPI
Postman can import your OpenAPI spec and build a collection with a request for every endpoint. Handy for QA folks who already live in Postman's environments and test runner.
- Open Postman → Import
- Paste your spec URL (e.g.,
http://localhost:3000/api-docs.json) or upload the YAML file - Postman generates a collection with all endpoints, example request bodies, and response schemas filled in
- Add environment variables for
baseUrlandtoken, then run the collection against any environment
Choosing a Documentation UI
Swagger UI is the default, but the same spec renders fine in other viewers:
| Tool | Strengths | Weaknesses | Best for |
|---|---|---|---|
| Swagger UI | Industry standard, "Try it out" built-in, huge ecosystem | Plain default design, large bundle | Internal tooling, developer portals |
| Redoc | Clean three-panel layout, handles large specs well, React-friendly | No "Try it out" in free tier | Public-facing API docs |
| Scalar | Modern UI, dark mode, client code snippets, free | Newer, smaller community | Modern developer portals |
| Stoplight Elements | Polished design, embeddable web component | Full platform requires paid plan | Product documentation sites |
| Postman | Full API lifecycle, team collaboration | Not embeddable in your app, requires account | API development workflow |
Making the Docs Worth Reading
A spec can pass every validator and still be useless to the person reading it. These are the habits that make the difference:
Habits that make API docs useful
- Write meaningful summaries and descriptions.
summary: Get useris useless.summary: Retrieve a single user by their numeric ID. Returns 404 if the user doesn't exist.is helpful. - Always include examples. Every schema property should have an
examplevalue. Swagger UI shows these in the "Example Value" panel and uses them for "Try it out" pre-fills. - Document all error responses. 400, 401, 403, 404, 422, 429, and 500. Consumers need to know what they'll get back and what to handle. Reuse error schemas via
$ref. - Use tags to group endpoints logically. Tags become the navigation headers in Swagger UI. Group by resource (Users, Orders, Payments), not by HTTP method.
- Version your spec. Keep the
info.versionin sync with your API version (use SemVer). Store the spec in version control alongside your code. - Generate from code, not alongside it. Maintaining a separate YAML file by hand leads to drift. Use annotations or schema reflection so the spec is always derived from the running code.
- Add
operationIdto every endpoint. These become function names in generated clients. Use camelCase and be descriptive:getUserById, notgetUser1. - Mark deprecated endpoints. Add
deprecated: trueto endpoints you're phasing out. Swagger UI renders them with a strikethrough, so consumers notice before you remove them.
Add a CI step that generates your spec and runs openapi-validator on every pull request. If a change breaks the spec (missing required property, wrong type), the build fails before merge, which beats finding out from a consumer after you've shipped a breaking change.
name: Validate API Spec
on: [push, pull_request]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Generate OpenAPI spec
run: node src/generate-spec.js > openapi.json
- name: Validate spec with IBM validator
run: |
npm install -g ibm-openapi-validator
lint-openapi openapi.json --errors-only
- name: Run contract tests with Schemathesis
run: |
pip install schemathesis
# Start API in background
node src/app.js &
sleep 3
# Fuzz all endpoints for spec compliance
schemathesis run openapi.json --base-url http://localhost:3000 --checks all
The sleep 3 in that workflow is a shortcut. On a slow runner the API may not be listening yet and Schemathesis fails with connection errors. Polling a health endpoint in a loop until it responds is more reliable.
When I'd use Swagger (and when I wouldn't)
I'd set it up for any REST API that someone outside the backend team consumes: a separate frontend, a mobile app, partners, or another service. That's where the "what does this return?" questions pile up, and where generated clients and contract tests pay for the setup time.
I'd skip it, or at least not start with it, in a few cases:
- The backend and frontend share one codebase and one developer. A Laravel app with Inertia, or a Next.js app calling its own route handlers, gets little from a spec that only you read.
- The API isn't REST. GraphQL has its own schema and introspection, and gRPC has protobuf. Bolting OpenAPI onto those adds a second source of truth.
- Nobody will maintain the annotations. A spec that's half right is worse than none, because people trust it. If you can't make CI fail on drift, keep the docs smaller and honest instead.
The other trade-off is noise. Annotation-heavy controllers get long, and in bigger projects I'd rather keep schemas in separate files (or in dedicated OpenApiSpec-style classes) than bury business logic under 40 lines of attributes. If you're starting out, document your five most-used endpoints first, put the UI behind auth, and add the CI check before the spec grows.