How to Build a REST API with Node.js and Express: Step-by-Step Guide for 2026
Introduction
Building a REST API is one of the most valuable skills a backend or full-stack developer can have in 2026. REST APIs power almost every modern application — from mobile apps to web dashboards and IoT devices. In this tutorial, we will build a fully functional REST API from scratch using Node.js and Express.js.
By the end of this guide, you will have a working API that can create, read, update, and delete data (CRUD operations), which you can use as the backend for any of your projects.
What is Node.js?
Node.js is a JavaScript runtime built on Chrome's V8 engine. It allows you to run JavaScript on the server side. Node.js is fast, lightweight, and perfect for building scalable network applications like REST APIs. In 2026, Node.js remains one of the most popular choices for backend development.
What is Express.js?
Express.js is a minimal and flexible web application framework for Node.js. It simplifies the process of building web servers and APIs by providing a set of robust features without forcing you into a rigid structure. Express handles HTTP routing, middleware, and request/response management efficiently.
Prerequisites
Before starting, make sure you have the following installed:
- Node.js (version 18 or higher) – download from nodejs.org
- npm (comes with Node.js)
- A code editor like VS Code
- Postman or Thunder Client for testing the API
Check your Node.js version by running node --version in your terminal.
Step 1: Set Up Your Project
Create a new folder for your project and initialize it with npm:
mkdir my-rest-api
cd my-rest-api
npm init -y
This creates a package.json file in your folder. Now install Express:
npm install express
Step 2: Create the Server
Create a file named index.js in your project folder and add the following code:
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to parse JSON request bodies
app.use(express.json());
// Basic route
app.get('/', (req, res) => {
res.json({ message: 'Welcome to my REST API!' });
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Run the server with: node index.js
Open your browser and go to http://localhost:3000. You should see the welcome message.
Step 3: Create In-Memory Data Store
For this tutorial, we will use a simple in-memory array to store data (in a real app, you would use a database like MongoDB or PostgreSQL). Let's build a REST API for managing a list of tasks:
// In-memory data store
let tasks = [
{ id: 1, title: 'Learn Node.js', completed: false },
{ id: 2, title: 'Build a REST API', completed: false },
{ id: 3, title: 'Deploy to AWS', completed: false }
];
let nextId = 4;
Step 4: Implement CRUD Routes
GET All Tasks
// Get all tasks
app.get('/tasks', (req, res) => {
res.json(tasks);
});
GET a Single Task by ID
// Get a single task
app.get('/tasks/:id', (req, res) => {
const task = tasks.find(t => t.id === parseInt(req.params.id));
if (!task) return res.status(404).json({ message: 'Task not found' });
res.json(task);
});
POST - Create a New Task
// Create a new task
app.post('/tasks', (req, res) => {
const { title } = req.body;
if (!title) return res.status(400).json({ message: 'Title is required' });
const newTask = { id: nextId++, title, completed: false };
tasks.push(newTask);
res.status(201).json(newTask);
});
PUT - Update a Task
// Update a task
app.put('/tasks/:id', (req, res) => {
const task = tasks.find(t => t.id === parseInt(req.params.id));
if (!task) return res.status(404).json({ message: 'Task not found' });
const { title, completed } = req.body;
if (title !== undefined) task.title = title;
if (completed !== undefined) task.completed = completed;
res.json(task);
});
DELETE - Remove a Task
// Delete a task
app.delete('/tasks/:id', (req, res) => {
const index = tasks.findIndex(t => t.id === parseInt(req.params.id));
if (index === -1) return res.status(404).json({ message: 'Task not found' });
const deleted = tasks.splice(index, 1);
res.json({ message: 'Task deleted', task: deleted[0] });
});
Step 5: Test Your API with Postman
With your server running, open Postman and test each endpoint:
- GET
http://localhost:3000/tasks– Returns all tasks - GET
http://localhost:3000/tasks/1– Returns task with ID 1 - POST
http://localhost:3000/taskswith body{"title": "New Task"}– Creates a new task - PUT
http://localhost:3000/tasks/1with body{"completed": true}– Updates task 1 - DELETE
http://localhost:3000/tasks/1– Deletes task 1
Step 6: Add Error Handling Middleware
Add a global error handler at the bottom of your file, just before app.listen:
// Global error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: 'Something went wrong!' });
});
Step 7: Connect to a Real Database (Optional Next Step)
To make your API production-ready, replace the in-memory array with a real database. Here is how to connect to MongoDB using Mongoose:
npm install mongoose
Then in your index.js:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb')
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Connection error:', err));
Best Practices for Building REST APIs
- Use proper HTTP status codes – 200 for success, 201 for created, 400 for bad request, 404 for not found, 500 for server error.
- Validate input data – Always validate and sanitize data coming from clients.
- Use environment variables – Store sensitive data like database passwords in .env files, never hardcode them.
- Version your API – Use URL versioning like /api/v1/tasks so you can update the API without breaking existing clients.
- Add authentication – Protect sensitive routes with JWT (JSON Web Tokens).
- Handle errors gracefully – Always return meaningful error messages with appropriate status codes.
Conclusion
Congratulations! You have just built a fully functional REST API with Node.js and Express. This is a major milestone in your backend development journey. You now understand how to create HTTP routes, handle request data, and return JSON responses.
The next steps are to connect your API to a real database like MongoDB or PostgreSQL, add user authentication with JWT, and deploy your API to a cloud platform like AWS, Heroku, or Railway.
Building REST APIs opens doors to creating full-stack applications, mobile app backends, and microservices. Keep practicing and building — every API you build strengthens your skills as a developer!
If you have questions or want to share what you built, drop a comment below!
Comments
Post a Comment