API Template Guide
The API Template is designed for building RESTful services quickly. It includes a pre-configured setup with security best practices, logging, and an organized MVC-like structure.
To generate an API project:
npx kaelum create my-api --template apiProject Structure
The generated project has the following layout:
my-api/
├── controllers/ # Request handlers (logic)
│ └── usersController.js
├── middlewares/ # Custom middleware
│ └── authMock.js
├── app.js # Application entry point & configuration
├── routes.js # Route definitions
└── package.jsonKey Files Explained
1. app.js
This file initializes the Kaelum app and sets up global configurations.
const kaelum = require("kaelum");
const app = kaelum();
// 1. Configure global settings
app.setConfig({
cors: true, // Enable CORS for cross-origin requests
helmet: true, // Add security headers
logs: true, // Log requests to console (morgan)
bodyParser: true, // Parse JSON and URL-encoded bodies
});
// 2. Load routes
const routes = require("./routes");
routes(app);
// 3. Start server
app.start(process.env.PORT || 4000);2. routes.js
This file acts as the central router. It uses Kaelum's helpers like apiRoute to define endpoints concisely.
const usersController = require("./controllers/usersController");
module.exports = function (app) {
// Apply middleware globally to a path
app.setMiddleware("/users", require("./middlewares/authMock"));
// Define RESTful routes for a resource
app.apiRoute("users", {
get: usersController.getUsers, // GET /users
post: usersController.createUser, // POST /users
"/:id": {
get: usersController.getUserById, // GET /users/:id
put: usersController.updateUser, // PUT /users/:id
delete: usersController.deleteUser // DELETE /users/:id
},
});
};3. controllers/
Controllers contain the actual business logic. They are standard Express middleware functions (req, res, next).
// controllers/usersController.js
exports.getUsers = (req, res) => {
res.json([{ id: 1, name: "Alice" }]);
};
exports.createUser = (req, res) => {
const newUser = req.body;
// logic to save user...
res.status(201).json(newUser);
};How to Adapt and Extend
Adding a New Resource
To add a new resource, for example, products:
Create a Controller: Create
controllers/productsController.js.Define Logic: Export functions like
listProducts,createProduct, etc.Register Route: Open
routes.jsand add:jsconst products = require("./controllers/productsController"); app.apiRoute("products", { get: products.listProducts, post: products.createProduct, });
Middleware
You can add middleware globally via app.use(), or per-route using app.setMiddleware().
// Protect all /products routes
app.setMiddleware("/products", (req, res, next) => {
if (!req.headers.authorization) return res.status(401).send("Unauthorized");
next();
});Running the Project
npm install
npm startThe server will start (default port 4000 for API template). You can test endpoints using curl or Postman:
curl http://localhost:4000/users