0
0
Expressframework~5 mins

Documenting endpoints in Express

Choose your learning style9 modes available
Introduction

Documenting endpoints helps others understand how to use your web server. It explains what each URL does and what data it needs or returns.

When building an API for a mobile app to use your server
When sharing your backend with other developers
When you want to remember what each route does later
When creating public APIs for external users
When testing endpoints with tools like Postman or curl
Syntax
Express
app.METHOD(PATH, HANDLER)

// Example:
app.get('/users', (req, res) => {
  res.send('List of users');
});

METHOD is the HTTP method like get, post, put, delete.

PATH is the URL path for the endpoint.

Examples
This endpoint responds with 'Hello World' when you visit /hello with a GET request.
Express
app.get('/hello', (req, res) => {
  res.send('Hello World');
});
This endpoint handles form submissions sent with POST to /submit.
Express
app.post('/submit', (req, res) => {
  res.send('Form submitted');
});
This endpoint updates a user by their id from the URL.
Express
app.put('/user/:id', (req, res) => {
  res.send(`Update user with id ${req.params.id}`);
});
Sample Program

This Express app has three endpoints. Each one is documented with a comment explaining what it does. This helps anyone reading the code understand the API quickly.

Express
import express from 'express';
const app = express();
const port = 3000;

// Documenting endpoints with comments

// GET / - Welcome message
app.get('/', (req, res) => {
  res.send('Welcome to our API!');
});

// GET /users - Returns a list of users
app.get('/users', (req, res) => {
  res.json([{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]);
});

// POST /users - Adds a new user (example, no real data handling)
app.post('/users', (req, res) => {
  res.status(201).send('User created');
});

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

Use clear comments above each endpoint to explain its purpose.

Include HTTP method and URL path in your documentation.

Consider using tools like Swagger or Postman for more detailed API docs.

Summary

Documenting endpoints makes your API easier to use and maintain.

Use comments to explain each route's purpose and expected data.

Clear docs help teammates and future you understand your server.