0
0
Expressframework~5 mins

API documentation best practices in Express

Choose your learning style9 modes available
Introduction

Good API documentation helps developers understand how to use your API easily. It saves time and reduces mistakes.

When creating a new API for others to use
When updating an existing API with new features
When sharing your API with teammates or external users
When you want to reduce support questions about your API
Syntax
Express
/*
  Route: GET /users
  Description: Returns a list of users
  Query Params:
    - page (optional): number, page number for pagination
  Response:
    200: JSON array of user objects
    400: Bad request error
*/
Use clear comments above your route handlers to explain their purpose.
Include HTTP method, URL, parameters, and response details.
Examples
This documents a login route with required body parameters and possible responses.
Express
/*
  Route: POST /login
  Description: Authenticates a user
  Body Params:
    - username: string, required
    - password: string, required
  Response:
    200: JSON with auth token
    401: Unauthorized error
*/
This documents a delete user route with URL parameter and response codes.
Express
/*
  Route: DELETE /users/:id
  Description: Deletes a user by ID
  URL Params:
    - id: string, required
  Response:
    204: No content on success
    404: User not found
*/
Sample Program

This Express app has a documented GET /items route. It explains the optional query parameter and the response format.

Express
import express from 'express';
const app = express();
app.use(express.json());

/*
  Route: GET /items
  Description: Returns all items
  Query Params:
    - limit (optional): number, max items to return
  Response:
    200: JSON array of items
*/
app.get('/items', (req, res) => {
  const limit = parseInt(req.query.limit) || 10;
  const items = Array.from({ length: 20 }, (_, i) => ({ id: i + 1, name: `Item ${i + 1}` }));
  res.json(items.slice(0, limit));
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Keep your documentation up to date as your API changes.

Use tools like Swagger or OpenAPI for interactive docs if possible.

Write examples for requests and responses to help users understand usage.

Summary

Good API docs explain routes, parameters, and responses clearly.

Use comments or tools to keep docs close to your code.

Clear docs help others use your API without confusion.