Routing: The Map of Your API

Routing: The Map of Your API in JavaScript: If Node.js is the engine, Express is the steering wheel and the dashboard.

Concept Explanation

If Node.js is the engine, Express is the steering wheel and the dashboard. Routing defines how your application responds to client requests to particular endpoints (URIs).

In a professional app, you don't put all your routes in one file. You use the express.Router to create modular, mountable route handlers.


Syntax or Core Structure

Modular Routing

// routes/userRoutes.js
import express from 'express';
const router = express.Router();

router.get('/:id', (req, res) => {
    const userId = req.params.id;
    res.json({ id: userId, name: "Alice" });
});

export default router;

// app.js
app.use('/users', userRoutes);

Best Practices

  • RESTful Naming: Use nouns, not verbs. GET /books is better than GET /get-all-books.
  • Version your API: Start your routes with /api/v1/. This allows you to make big changes later without breaking old apps.
  • Status Codes: Always send the correct HTTP status code. 201 for Created, 400 for Bad Request, 404 for Not Found.

Practice Exercises

  1. The Parameter Grabber: Create a route that accepts a category and a price as URL parameters and returns them in a JSON object.
  2. The Status Tester: Write a route that returns a 418 I'm a teapot status code just for fun.
  3. The API Architect: Plan out the 5 main REST routes for a "To-Do List" application (Create, Read All, Read One, Update, Delete).