Introduction
Building a REST API using Node.js and Express is one of the most in-demand skills in modern web development. REST APIs allow different applications (like web apps, mobile apps, and services) to communicate with each other using HTTP.
Node.js provides a fast and scalable runtime, while Express is a lightweight framework that makes API development simple and efficient. Together, they are widely used for backend development.
In this step-by-step guide, you will learn how to build a REST API using Node.js and Express in simple words, with practical examples and best practices.
What is a REST API?
A REST API (Representational State Transfer API) is a way to communicate between client and server using standard HTTP methods.
Common HTTP Methods
Example
A simple API for users:
GET /users → Get all users
POST /users → Create a user
PUT /users/1 → Update user
DELETE /users/1 → Delete user
Step 1: Install Node.js and Setup Project
First, install Node.js from the official website.
Then create a new project:
mkdir rest-api
cd rest-api
npm init -y
This creates a package.json file.
Step 2: Install Express
Install Express framework:
npm install express
Express helps in routing and handling HTTP requests easily.
Step 3: Create Basic Server
Create a file named server.js:
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.send('API is running');
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Run the server:
node server.js
Open browser: http://localhost:3000
Step 4: Use Middleware (JSON Parsing)
To handle JSON data, use built-in middleware:
app.use(express.json());
This allows your API to read JSON from request body.
Step 5: Create Routes
Now create basic CRUD routes.
let users = [];
// GET users
app.get('/users', (req, res) => {
res.json(users);
});
// POST user
app.post('/users', (req, res) => {
const user = req.body;
users.push(user);
res.status(201).json(user);
});
Step 6: Add PUT and DELETE Routes
// PUT update user
app.put('/users/:id', (req, res) => {
const id = parseInt(req.params.id);
users[id] = req.body;
res.json(users[id]);
});
// DELETE user
app.delete('/users/:id', (req, res) => {
const id = parseInt(req.params.id);
users.splice(id, 1);
res.send('User deleted');
});
Step 7: Use Express Router (Better Structure)
Create a routes file:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Users route');
});
module.exports = router;
Use it in server:
const userRoutes = require('./routes/users');
app.use('/users', userRoutes);
Step 8: Connect to Database (Optional)
In real projects, data is stored in databases like MongoDB or MySQL.
Example with MongoDB (conceptual):
// connect to database and store users
Step 9: Error Handling
Handle errors properly:
app.use((err, req, res, next) => {
res.status(500).json({ message: err.message });
});
Step 10: Test API
You can test APIs using:
Postman
Thunder Client
Browser (for GET)
Example request:
POST /users
{
"name": "John",
"age": 25
}
Best Practices for REST API Development
Use proper HTTP methods
Keep routes clean and meaningful
Validate user input
Use status codes correctly
Structure project properly
Common Mistakes Developers Make
Real-World Use Cases
Summary
Building a REST API using Node.js and Express is simple and powerful. By following a step-by-step approach, you can create scalable and maintainable APIs for modern applications. With features like routing, middleware, and JSON handling, Express makes backend development easy. Understanding REST principles and best practices helps you build efficient and production-ready APIs.