Express.js REST API
๐ Building a REST API with Express.js
This guide covers building a RESTful API using Express.js, a Node.js framework. It focuses on creating a To-Do application with various routes for managing tasks.
๐ ๏ธ Project Setup
To begin developing an Express.js application, follow these initial setup steps:
๐ Project Directory Creation
First, create a dedicated directory for your application.
Open your terminal.
Navigate to your desired location (e.g.,
cd Desktop).Create a new directory:
mkdir todos-app.Move into the new directory:
cd todos-app.Open the project in VS Code:
code .(ensurecodecommand is set up, otherwise open VS Code manually).
๐ฆ Node.js Application Initialization
Express.js runs on Node.js, so you need to initialize a Node.js project.
Open the integrated terminal in VS Code.
Initialize the project:
npm init -y.This command creates a
package.jsonfile, which manages project metadata and dependencies.
๐ Installing Express.js
Express is the only core dependency needed for this REST API.
Install Express:
npm install express.This adds Express to your
package.jsonand creates anode_modulesdirectory.
๐ก Creating the Express Server
The server logic will reside in index.js (or main.js).
Import Express:
const express = require('express');Create Express App:
const app = express();appis your Express application instance.
Listen on a Port:
const PORT = 3000; app.listen(PORT, () => { console.log(`Server listening on port ${PORT}`); });The
app.listen()method starts the server, making it listen for incoming requests on the specified port (e.g.,3000).The callback function executes once the server successfully starts.
๐ Running the Application
To run your Express application:
In the terminal, execute:
node index.js.You should see the message:
Server listening on port 3000.
๐ Hot Reloading with Nodemon
For development, Nodemon automatically restarts the server when file changes are detected.
Install Nodemon globally:
npm install -g nodemon.Mac/Linux users might need
sudo npm install -g nodemon.
Configure
package.json: Add adevscript.Run with Nodemon:
npm run dev.Now, changes to your
index.jsfile will automatically restart the server.
๐ฃ๏ธ Defining API Routes
RESTful APIs expose routes (endpoints) to perform operations. Express uses app.VERB(path, callback) to define these.
๐ Global To-Do Data Store
For simplicity, a global array todos will store our to-do items in memory.
let todos = []; // This will reset on server restartโ๏ธ Request and Response Objects
Every route handler receives two primary objects:
req(Request): Contains information about the incoming HTTP request, such as parameters, body, headers, and query strings.res(Response): Used to send back the HTTP response to the client, including data, status codes, and headers.
๐งน Middleware: express.json()
Before handling routes that receive JSON data in the request body (like POST or PUT), you need to tell Express to parse incoming JSON.
Add this middleware early in your
index.jsfile:app.use(express.json());Middleware functions have access to the request and response objects and the
nextmiddleware function. They can modify these objects, end the request-response cycle, or pass control to the next middleware.express.json()parses the JSON body and makes it available onreq.body.
๐ฆ UUID for Unique IDs
To generate unique identifiers for to-do items:
Install
uuid:npm install uuid.Import
v4:const { v4: uuidv4 } = require('uuid'); // Renamed for clarityUse
uuidv4()to generate a new ID:id: uuidv4().
๐ฏ To-Do Application Routes
Let's implement the core CRUD (Create, Read, Update, Delete) operations for our To-Do application.
โก๏ธ GET All To-Do's (/todos)
This route fetches all existing to-do items.
Verb:
GETPath:
/todosHandler:
app.get('/todos', (req, res) => { // In a real app, this would fetch from a database return res.json(todos); });Testing:
Browser:
localhost:3000/todosPostman/Insomnia: Send a
GETrequest tohttp://localhost:3000/todos.
โ Add a To-Do (/todos)
This route adds a new to-do item to the list.
Verb:
POSTPath:
/todosRequest Body: Expects a JSON object with a
titleproperty (e.g.,{ "title": "Pet the cat" }).Handler:
app.post('/todos', (req, res) => { const { title } = req.body; // Destructure title from request body if (!title) { return res.status(400).json({ message: 'Title is required' }); } const newTodo = { id: uuidv4(), // Generate unique ID title, completed: false, }; todos.push(newTodo); return res.status(201).json(newTodo); // Respond with the newly created to-do });Testing in Postman:
Set method to
POST.URL:
http://localhost:3000/todos.Go to Body tab, select
rawandJSON.Enter JSON:
{"title": "Clean the house"}.Send the request. The response should be the added to-do item.
๐ GET One To-Do (/todos/:id)
This route retrieves a single to-do item by its unique ID.
Verb:
GETPath:
/todos/:id:idis a route parameter, indicating a dynamic part of the URL.
Handler:
app.get('/todos/:id', (req, res) => { const { id } = req.params; // Get ID from route parameters const todo = todos.find(t => t.id === id); if (!todo) { return res.status(404).json({ message: 'To-do not found' }); } return res.json(todo); });Testing in Postman:
First, add a to-do using the POST route and copy its
id.Set method to
GET.URL:
http://localhost:3000/todos/<copied_id>.Send the request. The response should be the specific to-do item.
๐ Update a To-Do (/todos/:id)
This route toggles the completed status of a to-do item.
Verb:
PUTPath:
/todos/:idHandler:
app.put('/todos/:id', (req, res) => { const { id } = req.params; const todoIndex = todos.findIndex(t => t.id === id); if (todoIndex === -1) { return res.status(404).json({ message: 'To-do not found' }); } todos[todoIndex].completed = !todos[todoIndex].completed; // Toggle completed status return res.json(todos[todoIndex]); // Respond with the updated to-do });Testing in Postman:
First, add a to-do and copy its
id.Set method to
PUT.URL:
http://localhost:3000/todos/<copied_id>.Send the request. The
completedstatus in the response should toggle.
๐๏ธ Delete a To-Do (/todos/:id)
This route removes a to-do item from the list.
Verb:
DELETEPath:
/todos/:idHandler:
app.delete('/todos/:id', (req, res) => { const { id } = req.params; const initialLength = todos.length; todos = todos.filter(t => t.id !== id); // Filter out the deleted to-do if (todos.length === initialLength) { return res.status(404).json({ message: 'To-do not found' }); } return res.status(200).json({ message: 'To-do deleted successfully', remainingTodos: todos }); // Respond with remaining todos });Testing in Postman:
First, add a to-do and copy its
id.Set method to
DELETE.URL:
http://localhost:3000/todos/<copied_id>.Send the request. Then, use the
GET /todosroute to confirm deletion.
๐๏ธ Route Organization with Express Router
As an application grows, keeping all routes in one file (index.js) becomes unmanageable. Express Router helps organize routes into separate modules.
๐ Creating a Routes Directory
Create a
routesdirectory:mkdir routes.Inside, create
todos.jsfor to-do related routes.
๐ todos.js Content
Import Express Router:
const express = require('express'); const router = express.Router(); // Create a new router instance const { v4: uuidv4 } = require('uuid'); // Also need uuid here // Global todos array (for this example, still in memory) let todos = [];Replace
appwithrouter: Change allapp.get,app.post, etc., torouter.get,router.post.Export the Router:
module.exports = router;Remove duplicate path segments: If all routes in
todos.jsstart with/todos, you can remove/todosfrom each route definition withintodos.jsand specify it once when using the router.Example:
router.get('/', ...)instead ofrouter.get('/todos', ...).Example:
router.get('/:id', ...)instead ofrouter.get('/todos/:id', ...).
๐ Integrating Router in index.js
Import the To-Do Router:
const todosRouter = require('./routes/todos');Use the Router with a Base Path:
app.use('/todos', todosRouter);app.use('/todos', todosRouter)means all routes defined intodosRouterwill be prefixed with/todos. So,router.get('/')intodos.jsbecomesGET /todosin the main app, androuter.get('/:id')becomesGET /todos/:id.
๐ก๏ธ Middleware Deep Dive
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle.
โ๏ธ How Middleware Works
A client makes a request.
The request passes through a chain of middleware functions.
Each middleware can:
Execute any code.
Make changes to the request and the response objects.
End the request-response cycle (e.g., by sending a response).
Call the next middleware in the stack (
next()).
If
next()is not called, the request will be left hanging unless the middleware itself sends a response.
๐ Authentication Middleware Example
Let's create a simple authentication middleware to check for an authenticated header.
Create
middleware/check-auth.js:const checkAuth = (req, res, next) => { const authenticated = req.header('authenticated'); // Get header value if (authenticated === 'yes') { next(); // User is authenticated, proceed to next middleware or route handler } else { return res.status(403).json({ message: 'Not authenticated' }); // Forbidden error } }; module.exports = checkAuth;Integrate Middleware into Routes:
In
routes/todos.js, import the middleware:Add
checkAuthas a second argument to any route that requires authentication:router.get('/', checkAuth, (req, res) => { return res.json(todos); }); router.post('/', checkAuth, (req, res) => { // ... (rest of the post logic) }); // Apply to all other routes as neededMiddleware Order: Middleware functions are executed in the order they are defined. If
checkAuthis placed before the route handler, it runs first.
๐งช Testing Authentication
In Postman:
Go to the Headers tab for your request.
Add a key-value pair:
authenticated: yes. The request should succeed.Change to
authenticated: no. The request should fail with a403 Forbiddenstatus and aNot authenticatedmessage.
This structured approach demonstrates the core principles of building RESTful APIs with Express.js, covering setup, routing, and middleware for a robust and organized application.

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