Node.js API Structure — Routes, Controllers, Models & Server Setup
This article provides a clear, structured, and developer‑friendly explanation of how modern Node.js applications organize their API architecture using routes, controllers, models, and server configuration. It is designed to help beginners and experienced developers understand project structure, improve backend workflow, and follow best practices for scalable JavaScript development. With practical examples, clean code snippets, and step‑by‑step breakdowns, this guide supports learning, debugging, and building professional API systems.
Structure Breakdown
That looks like a file path to a JavaScript file in a web application's structure.
The file path /src/api/routes/catalog.js tells us a lot about its purpose and role within the project.
🏗️ Structure Breakdown
Path SegmentMeaning
/src/ — The Source Directory. This is the standard root for all the application's original source code (as opposed to
configuration files, build outputs, or external libraries).
api/ — Indicates this part of the code is responsible for handling the Application Programming Interface (API) — the
set of rules defining how client-side applications (like a web browser or mobile app) communicate with the server-side
logic.
routes/ — This directory specifically holds Route Definitions. In a modern web application (especially one using
frameworks like Express.js, Koa, or similar), routes define the endpoints (the URLs) that a client can request and map
those requests to specific functions (controllers) that handle the business logic.
catalog.js — This is the specific file name. It suggests the routes defined within this file are all related to the
application's product catalog (e.g., getting a list of products, retrieving product details, searching, etc.).
File Purpose: The Catalog Endpoint
This file, catalog.js, is almost certainly responsible for setting up the specific URL endpoints for your application's product catalog functionality.
It typically performs the following actions:
- Imports Dependencies
- Defines Endpoints
- Applies Middleware
Example Routes Defined in catalog.js
HTTP Method Endpoint Description
GET /api/catalog/products Retrieve a list of all products.
GET /api/catalog/products/:id Retrieve the details for a single product.
POST /api/catalog/products Create a new product (admin-only).
DELETE /api/catalog/products/:id Remove a product (admin-only).
Route File (catalog.js)
// 1. Import the Express Router
const express = require('express');
const router = express.Router();
// 2. Import the Controller
const catalogController = require('../../controllers/catalogController');
// 3. Optional middleware
const authMiddleware = require('../../middleware/auth');
// Route definitions...
Controller (catalogController.js)
catalogController.getAllProducts = async (req, res) => {
try {
const products = await Product.findAll();
return res.status(200).json({
status: 'success',
count: products.length,
data: products
});
} catch (error) {
return res.status(500).json({
status: 'error',
message: 'Failed to retrieve products due to a server error.'
});
}
};
Model (Product.js)
const Product = db.define('Product', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: { type: DataTypes.STRING, allowNull: false },
description: { type: DataTypes.TEXT },
price: { type: DataTypes.DECIMAL(10, 2), allowNull: false },
stock: { type: DataTypes.INTEGER, defaultValue: 0 }
});
Server Setup (server.js)
const express = require('express');
const app = express();
app.use('/api/catalog', catalogRoutes);
app.listen(3000);
Request Flow Summary
Client → Route → Controller → Model → Controller → Response
No comments:
Post a Comment