Node.js REST API
π‘ Vanilla Node.js REST API with CRUD
This guide details how to build a Vanilla Node.js REST API with full CRUD (Create, Read, Update, Delete) functionality. Unlike typical tutorials that use frameworks like Express, this API is built using only bare-bones Node.js with the built-in http module. This approach, while requiring more manual coding, offers a deeper understanding of the underlying HTTP request-response cycle and how frameworks abstract these processes.
π Project Setup & Dependencies
To begin, set up the project environment and install necessary dependencies.
π¦ Initializing Project
Create a project folder, e.g.,
vanilla-node-rest-api.Inside the folder, initialize
package.json:npm init -yThis command creates a
package.jsonfile with default values, skipping the interactive questions.
π Data Structure
The API will interact with a JSON file as its data source instead of a database.
Create a
datafolder in the project root.Inside
data, createproducts.jsonwith an array of product objects.Each product object should have
id,name,description, andprice.[ { "id": "1", "name": "Airpods Wireless Bluetooth Headphones", "description": "Bluetooth technology lets you connect it to compatible devices from up to 30ft away", "price": 89.99 }, { "id": "2", "name": "iPhone 13 Pro", "description": "The latest iPhone model with advanced camera features and A15 Bionic chip.", "price": 999.99 }, { "id": "3", "name": "Sony PlayStation 5", "description": "Next-gen gaming console with ultra-high-speed SSD and immersive haptic feedback.", "price": 499.99 }, { "id": "4", "name": "MacBook Air M1", "description": "Lightweight and powerful laptop with Apple's M1 chip, offering incredible performance and battery life.", "price": 1199.99 }, { "id": "5", "name": "Samsung 4K Smart TV", "description": "Experience stunning 4K UHD resolution and smart features for endless entertainment.", "price": 799.99 } ]
βοΈ Installing Dependencies
Only two third-party packages are used:
Nodemon: For automatically restarting the server on file changes during development.
UUID: For generating unique IDs for new products.
Install them:
npm install -D nodemon
npm install uuidnodemonis installed as a dev dependency (-D).
π NPM Scripts
Add the following scripts to package.json for easy execution:
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}npm start: For running the server in a production environment.npm run dev: For running the server withnodemonfor development.
π Server Entry Point (server.js)
The server.js file is the entry point of the application, responsible for creating the HTTP server and handling incoming requests.
π¦ Importing HTTP Module
The http module is a built-in Node.js module that provides functionalities for creating HTTP servers and clients.
const http = require('http');βοΈ Creating the Server
The http.createServer() method is used to create an HTTP server. It takes a callback function that executes every time a request is made to the server. This function receives req (request) and res (response) objects.
const server = http.createServer((req, res) => {
// Request handling logic goes here
});π Listening for Requests
The server needs to listen on a specific port for incoming connections.
const PORT = process.env.PORT || 5000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));process.env.PORTallows specifying the port via an environment variable, useful for deployment.If no environment variable is set, it defaults to port 5000.
π Basic Response (Initial Example)
Initially, to demonstrate functionality, a simple HTML response can be sent.
// Inside http.createServer callback
res.statusCode = 200; // HTTP Status Code: OK
res.setHeader('Content-Type', 'text/html'); // Set Content-Type header
res.write('<h1>Hello World!</h1>'); // Write content to the response body
res.end(); // End the responseres.statusCode: Sets the HTTP status code.200signifies success.res.setHeader(): Sets response headers, such asContent-Type.res.write(): Writes data to the response body.res.end(): Signals the server that all response headers and body have been sent. It must be called for every response.
π‘ res.writeHead() for Concise Headers
For setting status code and headers more concisely, res.writeHead() can be used:
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello World!</h1>');This combines
res.statusCodeandres.setHeader()into a single call.res.end()can also directly take the response body.
π οΈ Request Handling: Routing & Methods
In a vanilla Node.js API, routing and method handling must be done manually by inspecting the req object.
π£ Accessing Request Details
The req object provides crucial information about the incoming request:
req.url: The URL path of the request (e.g.,/api/products,/api/products/1).req.method: The HTTP method used (e.g.,GET,POST,PUT,DELETE).
π¦ Manual Routing Logic
Conditional statements (if/else if) are used to match specific URLs and HTTP methods.
β‘οΈ GET All Products
To fetch all products, the route is /api/products and the method is GET.
if (req.url === '/api/products' && req.method === 'GET') {
// Logic to get all products
}β‘οΈ GET Single Product by ID
To fetch a single product by its ID, the route uses a regular expression to match /api/products/:id and the method is GET. The ID needs to be extracted from the URL.
// Example URL: /api/products/1
if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === 'GET') {
// Extract ID:
const id = req.url.split('/')[3]; // Splits URL by '/' and gets the 3rd index (the ID)
// Logic to get single product by ID
}req.url.match(): Uses a regular expression to check if the URL conforms to the/api/products/:idpattern.([0-9]+): Captures one or more digits, representing the product ID.req.url.split('/')[3]: Manually parses the URL to extract the ID.
β‘οΈ POST Create Product
To create a new product, the route is /api/products and the method is POST.
if (req.url === '/api/products' && req.method === 'POST') {
// Logic to create a new product
}β‘οΈ PUT Update Product by ID
To update an existing product, the route is /api/products/:id and the method is PUT. The ID needs to be extracted.
if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === 'PUT') {
const id = req.url.split('/')[3];
// Logic to update product by ID
}β‘οΈ DELETE Product by ID
To delete a product, the route is /api/products/:id and the method is DELETE. The ID needs to be extracted.
if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === 'DELETE') {
const id = req.url.split('/')[3];
// Logic to delete product by ID
}π« Route Not Found (404)
If none of the defined routes match, a 404 Not Found response is sent.
else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Route Not Found' }));
}ποΈ MVC Architecture: Models & Controllers
To maintain a clean and scalable codebase, the API follows a Model-View-Controller (MVC) design pattern, even though there's no "View" component in a REST API.
πΊοΈ models Folder
Deals with data interaction. In this API, it interacts with
products.json.Model functions handle reading from and writing to the file system.
Model functions typically return Promises, simulating asynchronous database operations.
product_model.js
Load Data:
const products = require('../data/products.json'); // Loads the JSON file const { writeDataToFile } = require('../utils'); // Utility to write data const { v4: uuidv4 } = require('uuid'); // For generating unique IDsproducts.jsonis directlyrequired, which parses it into a JavaScript array of objects.uuidv4is destructured fromuuidto generate version 4 UUIDs.
findAll()- Get All Products:function findAll() { return new Promise((resolve, reject) => { resolve(products); // Simply resolves with the loaded products array }); }Returns a Promise that resolves with the entire
productsarray.
findById(id)- Get Single Product:function findById(id) { return new Promise((resolve, reject) => { const product = products.find((p) => p.id === id); // Finds product by ID resolve(product); }); }Uses
Array.prototype.find()to locate a product with a matching ID.
create(product)- Create Product:function create(product) { return new Promise((resolve, reject) => { const newProduct = { id: uuidv4(), ...product }; // Assigns a UUID and spreads product data products.push(newProduct); // Adds to the in-memory array writeDataToFile('./data/products.json', products); // Writes updated array to file resolve(newProduct); }); }Generates a unique
idusinguuidv4().Uses the spread operator (
...) to combine the newidwith theproductdata received from the controller.Pushes the
newProductto the in-memoryproductsarray.Calls
writeDataToFile()(fromutils.js) to persist the changes toproducts.json.
update(id, product)- Update Product:function update(id, product) { return new Promise((resolve, reject) => { const index = products.findIndex((p) => p.id === id); // Finds index of product products[index] = { id, ...product }; // Updates product at index, keeping original ID writeDataToFile('./data/products.json', products); resolve(products[index]); // Resolves with the updated product }); }Uses
Array.prototype.findIndex()to get the index of the product to be updated.Replaces the product at that index with the new
productdata, ensuring theidremains the same.Persists changes to
products.json.
remove(id)- Delete Product:function remove(id) { return new Promise((resolve, reject) => { // Filters out the product with the matching ID const updatedProducts = products.filter((p) => p.id !== id); writeDataToFile('./data/products.json', updatedProducts); resolve(); // Resolves without data after deletion }); }Uses
Array.prototype.filter()to create a new array excluding the product with the specifiedid.Writes this
updatedProductsarray back to the file.
π¦ controllers Folder
Handles request-specific logic, interacts with the model, and prepares the response.
Controller functions take
reqandres(and sometimesid) as arguments.They use
try-catchblocks for error handling.
product_controller.js
Import Model & Utilities:
const Product = require('../models/product_model'); // Product Model const { getPostData } = require('../utils'); // Utility for POST/PUT body datagetProducts(req, res)- Get All Products:async function getProducts(req, res) { try { const products = await Product.findAll(); // Awaits Promise from model res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(products)); // Sends JSON response } catch (error) { console.log(error); } }Uses
awaitto handle the Promise returned byProduct.findAll().Sets status
200andContent-Type: application/json.JSON.stringify()is crucial to convert the JavaScript object/array into a JSON string for the response.
getProduct(req, res, id)- Get Single Product:async function getProduct(req, res, id) { try { const product = await Product.findById(id); if (!product) { // If product not found res.writeHead(404, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Product Not Found' })); } else { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(product)); } } catch (error) { console.log(error); } }Checks if the
productexists; sends404if not found,200with the product if found.
createProduct(req, res)- Create Product:async function createProduct(req, res) { try { const body = await getPostData(req); // Awaits utility to parse request body const { name, description, price } = JSON.parse(body); // Parses JSON string to object const product = { name, description, price }; // Product data for model const newProduct = await Product.create(product); // Awaits model to create res.writeHead(201, { 'Content-Type': 'application/json' }); // 201 Created res.end(JSON.stringify(newProduct)); } catch (error) { console.log(error); } }Uses
getPostData(req)utility to asynchronously read and parse the request body.Destructures
name,description, andpricefrom the parsed body.Sends
201 Createdstatus on success.
updateProduct(req, res, id)- Update Product:async function updateProduct(req, res, id) { try { const product = await Product.findById(id); if (!product) { // Check if product exists res.writeHead(404, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Product Not Found' })); } else { const body = await getPostData(req); const { name, description, price } = JSON.parse(body); // Allows partial updates: use new value if provided, else keep existing const productData = { name: name || product.name, description: description || product.description, price: price || product.price }; const updProduct = await Product.update(id, productData); // Awaits model to update res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(updProduct)); } } catch (error) { console.log(error); } }First, checks if the product to be updated actually exists.
Handles partial updates by using
||operator: if a field is not provided in the request body, it retains the existing value from the product.
deleteProduct(req, res, id)- Delete Product:async function deleteProduct(req, res, id) { try { const product = await Product.findById(id); if (!product) { res.writeHead(404, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Product Not Found' })); } else { await Product.remove(id); // Awaits model to remove res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: `Product ${id} removed` })); } } catch (error) { console.log(error); } }Checks for product existence before attempting to delete.
Sends a confirmation message upon successful deletion.
π¦ Exporting Controller Functions
All controller functions must be exported so they can be imported and used in server.js.
module.exports = {
getProducts,
getProduct,
createProduct,
updateProduct,
deleteProduct
};π§ Utility Functions (utils.js)
A utils.js file centralizes common helper functions, reducing code duplication.
πΎ writeDataToFile(filename, content)
This function handles writing data to a JSON file.
const fs = require('fs'); // Node.js File System module
function writeDataToFile(filename, content) {
fs.writeFileSync(filename, JSON.stringify(content, null, 4), 'utf8', (err) => {
if (err) {
console.log(err);
}
});
}fs.writeFileSync(): Writes data to a file synchronously.JSON.stringify(content, null, 4): Converts the JavaScript objectcontentinto a JSON string.null, 4formats the JSON with an indent of 4 spaces for readability.'utf8': Specifies the file encoding.
π₯ getPostData(req)
This crucial utility function parses the incoming request body for POST and PUT requests, which is more complex in vanilla Node.js compared to frameworks.
function getPostData(req) {
return new Promise((resolve, reject) => {
try {
let body = '';
// Event listener for 'data' chunks
req.on('data', (chunk) => {
body += chunk.toString(); // Append buffer chunks to body string
});
// Event listener for 'end' of request
req.on('end', () => {
resolve(body); // Resolve the Promise with the complete body string
});
} catch (error) {
reject(error);
}
});
}req.on('data', ...): Listens fordataevents, which emit chunks of the request body as aBuffer. These chunks are converted to strings and appended to thebodyvariable.req.on('end', ...): Listens for theendevent, which signifies that the entire request body has been received. At this point, the completebodystring is resolved.This function returns a Promise, allowing
async/awaitto be used in controllers.
π¦ Exporting Utility Functions
module.exports = {
writeDataToFile,
getPostData
};π Final server.js Structure
The server.js ties everything together, handling routing and delegating tasks to the controllers.
const http = require('http');
const {
getProducts,
getProduct,
createProduct,
updateProduct,
deleteProduct
} = require('./controllers/product_controller');
const PORT = process.env.PORT || 5000;
const server = http.createServer((req, res) => {
// GET /api/products
if (req.url === '/api/products' && req.method === 'GET') {
getProducts(req, res);
}
// GET /api/products/:id
else if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === 'GET') {
const id = req.url.split('/')[3];
getProduct(req, res, id);
}
// POST /api/products
else if (req.url === '/api/products' && req.method === 'POST') {
createProduct(req, res);
}
// PUT /api/products/:id
else if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === 'PUT') {
const id = req.url.split('/')[3];
updateProduct(req, res, id);
}
// DELETE /api/products/:id
else if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === 'DELETE') {
const id = req.url.split('/')[3];
deleteProduct(req, res, id);
}
// Route Not Found
else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Route Not Found' }));
}
});
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));π§ͺ Testing the API with Postman
Postman (or a similar API client) is essential for testing the different HTTP methods and routes.
π CRUD Operations
Operation | Method | URL | Body (JSON) Example | Expected Response |
|---|---|---|---|---|
Read All |
|
| None | Array of all products (Status: |
Read Single |
|
| None | Single product object (Status: |
Create |
|
|
| Newly created product with ID (Status: |
Update |
|
|
| Updated product object (Status: |
Delete |
|
| None |
|
Not Found |
|
| None |
|
β οΈ Key Takeaways for Vanilla Node.js API
Manual Routing: Every route and HTTP method combination needs explicit
if/else ifchecks.Body Parsing: Request body data for
POST/PUTmust be manually collected fromreq.on('data')andreq.on('end')events.JSON Stringification: All JSON responses must be explicitly converted using
JSON.stringify().HTTP Headers:
Content-TypeandStatus Codemust be manually set for each response.Error Handling:
try-catchblocks are essential in asynchronous controller functions.
This vanilla approach provides a foundational understanding of how web servers and APIs function at a low level, highlighting the conveniences offered by frameworks like Express.

Ask anything
We've read this whole study set, so questions about it get the best answers.