Introduction
RESTful APIs are essential for modern web applications, allowing seamless communication between the frontend and backend. Express.js, a lightweight Node.js framework, makes it easy to create robust and scalable REST APIs.
In this guide, we will:
- Understand the basics of RESTful APIs
- Set up an Express server
- Create routes for CRUD operations
- Use middleware for request handling
- Connect the API to a database (MongoDB)
By the end, you’ll have a fully functional REST API that you can extend for your applications.
1. Understanding RESTful APIs
A REST API (Representational State Transfer) follows a set of principles:
- Stateless: Each request is independent and contains all necessary information.
- Resource-based: Uses endpoints (e.g.,
/users
,/products
). - Uses HTTP Methods:
GET
→ Retrieve dataPOST
→ Create new dataPUT
→ Update existing dataDELETE
→ Remove data
2. Setting Up the Project
Step 1: Install Node.js and Express
Ensure you have Node.js installed:
node -v # Check Node.js version
Create a project folder and initialize it:
mkdir rest-api-express
cd rest-api-express
npm init -y
Install Express:
npm install express
3. Creating a Basic Express Server
Create a file server.js
and add the following:
const express = require('express');
const app = express();
const PORT = 5000;
// Middleware to parse JSON
aap.use(express.json());
// Test Route
app.get('/', (req, res) => {
res.send('Welcome to the REST API');
});
// Start server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Run the server:
node server.js
Visit http://localhost:5000/
in your browser to see the welcome message.
4. Creating REST API Routes
We will build a users
API with CRUD operations.
Step 1: Define Routes in server.js
const users = [
{ id: 1, name: 'John Doe', email: '[email protected]' },
{ id: 2, name: 'Jane Doe', email: '[email protected]' }
];
// GET all users
app.get('/users', (req, res) => {
res.json(users);
});
// GET user by ID
app.get('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).send('User not found');
res.json(user);
});
// POST: Add a new user
app.post('/users', (req, res) => {
const newUser = { id: users.length + 1, ...req.body };
users.push(newUser);
res.status(201).json(newUser);
});
// PUT: Update a user
app.put('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).send('User not found');
Object.assign(user, req.body);
res.json(user);
});
// DELETE: Remove a user
app.delete('/users/:id', (req, res) => {
const index = users.findIndex(u => u.id === parseInt(req.params.id));
if (index === -1) return res.status(404).send('User not found');
users.splice(index, 1);
res.send('User deleted');
});
Test API using Postman or cURL:
curl -X GET http://localhost:5000/users
5. Connecting the API to MongoDB
Step 1: Install MongoDB and Mongoose
npm install mongoose
Step 2: Set Up MongoDB Connection
Modify server.js
:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/usersDB', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
Step 3: Define a User Model
Create models/User.js
:
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: String,
email: String
});
module.exports = mongoose.model('User', UserSchema);
Step 4: Modify Routes to Use MongoDB
const User = require('./models/User');
// GET all users
app.get('/users', async (req, res) => {
const users = await User.find();
res.json(users);
});
// POST a new user
app.post('/users', async (req, res) => {
const newUser = new User(req.body);
await newUser.save();
res.status(201).json(newUser);
});
Run the API, and MongoDB will store data persistently.
6. Using Middleware for Validation
Install express-validator
:
npm install express-validator
Modify server.js
:
const { check, validationResult } = require('express-validator');
app.post('/users', [
check('name', 'Name is required').notEmpty(),
check('email', 'Invalid email').isEmail()
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });
const newUser = new User(req.body);
await newUser.save();
res.status(201).json(newUser);
});
Now, invalid requests will be blocked.
7. Deploying the API
Step 1: Install Heroku CLI
npm install -g heroku
heroku login
Step 2: Push to Heroku
git init
heroku create
heroku addons:create mongolab # Add MongoDB
heroku config:set NODE_ENV=production
git add .
git commit -m "Deploy REST API"
git push heroku master
Your API is now live!
Conclusion
You have successfully built a RESTful API using Node.js, Express, and MongoDB. You learned how to:
- Set up an Express server
- Implement CRUD operations
- Connect to MongoDB
- Validate input using middleware
- Deploy the API to production
Next Steps
- Implement JWT authentication
- Add pagination and sorting
- Improve security using Helmet & Rate Limiting
Start building your next project with Express.js! 🚀