Routes and Endpoints: The Pathways of Your Application
Think of routes as the streets in a city, and endpoints as specific addresses. A route (like "/users") is just the path, while an endpoint combines that path with a specific action (like "GET /users" or "POST /users"). Let's see this in practice:
Example: Defining Routes and Endpoints
// A simple Express.js application demonstrating routes and endpoints
const express = require('express');
const app = express();
// This defines a route pattern
app.use('/users', userRouter);
// These define specific endpoints
class UserController {
// GET /users - An endpoint for listing users
static async listUsers(req, res) {
try {
const users = await User.findAll();
res.json(users);
} catch (error) {
res.status(500).json({ error: 'Failed to retrieve users' });
}
}
// POST /users - A different endpoint using the same route
static async createUser(req, res) {
try {
const newUser = await User.create(req.body);
res.status(201).json(newUser);
} catch (error) {
res.status(400).json({ error: 'Failed to create user' });
}
}
}
// Defining the routes and connecting them to endpoints
const userRouter = express.Router();
userRouter.get('/', UserController.listUsers); // Endpoint: GET /users
userRouter.post('/', UserController.createUser); // Endpoint: POST /users
// This shows how one route (/users) can have multiple endpoints
// Each endpoint serves a different purpose