Difficulty:
Last updated:
In this tutorial, you'll learn how to build a complete REST API from scratch using Node.js and Express. By the end, you'll have a working API that can:
First, let's create a new directory for our project and initialize it with npm.
mkdir my-first-api
cd my-first-api
npm init -y
This creates a package.json file with default settings. Your file should look like this:
{
"name": "my-first-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Tip: The -y flag accepts all default options. You can run npm init without it to customize each field.
Progress:
Express is a minimal and flexible Node.js web application framework. Let's install it:
npm install express
This will add Express to your package.json dependencies:
{
"dependencies": {
"express": "^4.18.2"
}
}
We'll also need a few more packages for our API:
npm install dotenv mongoose joi cors
dotenv.env filemongoosejoicorsnpm install --save-dev nodemon
nodemon automatically restarts your server when files change. Let's add a start script to package.json:
{
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
}
Progress:
Create a new file called server.js in your project root:
// server.js
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to parse JSON
app.use(express.json());
// Your first route!
app.get('/', (req, res) => {
res.json({ message: 'Hello, World!' });
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Let's break down what each part does:
require('express') - Imports the Express moduleexpress() - Creates an Express applicationapp.use(express.json()) - Adds middleware to parse JSON request bodiesapp.get('/', ...) - Defines a route that responds to GET requestsapp.listen(PORT, ...) - Starts the server on port 3000Run the server:
npm run dev
You should see:
Server is running on port 3000
Open your browser and visit http://localhost:3000. You should see:
{
"message": "Hello, World!"
}
Success! Your first API endpoint is working.
Progress:
Let's connect to MongoDB using Mongoose. First, create a .env file:
# .env
PORT=3000
MONGODB_URI=mongodb://localhost:27017/myapi
Important: Add
.envto your.gitignorefile to keep your secrets safe!
Create a new file config/database.js:
// config/database.js
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
console.log('MongoDB connected successfully');
} catch (error) {
console.error('MongoDB connection error:', error);
process.exit(1);
}
};
module.exports = connectDB;
Update server.js to use the database connection:
// server.js
require('dotenv').config();
const express = require('express');
const connectDB = require('./config/database');
const app = express();
const PORT = process.env.PORT || 3000;
// Connect to database
connectDB();
// Middleware
app.use(express.json());
// Routes
app.get('/', (req, res) => {
res.json({ message: 'API is running' });
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Progress:
CRUD operations are the foundation of any API. Let's build a simple user management system.
Create models/User.js:
// models/User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
lowercase: true
},
age: {
type: Number,
min: 0,
max: 120
},
createdAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('User', userSchema);
Create routes/users.js:
// routes/users.js
const express = require('express');
const router = express.Router();
const User = require('../models/User');
// CREATE - Add new user
router.post('/', async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).json(user);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// READ - Get all users
router.get('/', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// READ - Get user by ID
router.get('/:id', async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// UPDATE - Update user by ID
router.put('/:id', async (req, res) => {
try {
const user = await User.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true, runValidators: true }
);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// DELETE - Delete user by ID
router.delete('/:id', async (req, res) => {
try {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json({ message: 'User deleted successfully' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
Update server.js to use the routes:
// Add this line with other requires
const userRoutes = require('./routes/users');
// Add this line after middleware
app.use('/api/users', userRoutes);
| Operation | HTTP Method | Endpoint | Description |
|---|---|---|---|
| Create | POST |
/api/users |
Create a new user |
| Read | GET |
/api/users |
Get all users |
| Read | GET |
/api/users/:id |
Get user by ID |
| Update | PUT |
/api/users/:id |
Update user by ID |
| Delete | DELETE |
/api/users/:id |
Delete user by ID |
Progress:
Input validation is crucial for API security and data integrity. Let's use Joi to validate requests.
Create middleware/validation.js:
// middleware/validation.js
const Joi = require('joi');
const userSchema = Joi.object({
name: Joi.string()
.min(3)
.max(50)
.required()
.messages({
'string.min': 'Name must be at least 3 characters',
'string.max': 'Name cannot exceed 50 characters',
'any.required': 'Name is required'
}),
email: Joi.string()
.email()
.required()
.messages({
'string.email': 'Please provide a valid email',
'any.required': 'Email is required'
}),
age: Joi.number()
.min(0)
.max(120)
.optional()
.messages({
'number.min': 'Age must be at least 0',
'number.max': 'Age cannot exceed 120'
})
});
const validateUser = (req, res, next) => {
const { error } = userSchema.validate(req.body);
if (error) {
return res.status(400).json({
error: error.details[0].message
});
}
next();
};
module.exports = { validateUser };
Update routes/users.js to use validation:
const { validateUser } = require('../middleware/validation');
// Apply validation to POST and PUT routes
router.post('/', validateUser, async (req, res) => {
// ... existing code
});
router.put('/:id', validateUser, async (req, res) => {
// ... existing code
});
Try creating a user with invalid data:
POST /api/users
Content-Type: application/json
{
"name": "AB",
"email": "invalid-email"
}
Response:
{
"error": "Name must be at least 3 characters"
}
Progress:
Proper error handling makes your API more robust and user-friendly.
Create middleware/errorHandler.js:
// middleware/errorHandler.js
const errorHandler = (err, req, res, next) => {
console.error(err.stack);
// Mongoose validation error
if (err.name === 'ValidationError') {
return res.status(400).json({
error: 'Validation Error',
details: Object.values(err.errors).map(e => e.message)
});
}
// Mongoose duplicate key error
if (err.code === 11000) {
return res.status(400).json({
error: 'Duplicate Error',
message: 'A user with this email already exists'
});
}
// Mongoose cast error (invalid ID)
if (err.name === 'CastError') {
return res.status(400).json({
error: 'Invalid ID format'
});
}
// Default error
res.status(500).json({
error: 'Internal Server Error',
message: err.message
});
};
module.exports = errorHandler;
Add to server.js (at the end, after all routes):
const errorHandler = require('./middleware/errorHandler');
// Error handling middleware (must be last)
app.use(errorHandler);
| Code | Name | When to Use |
|---|---|---|
200 |
OK | Request succeeded |
201 |
Created | Resource created successfully |
400 |
Bad Request | Invalid request data |
404 |
Not Found | Resource not found |
500 |
Internal Server Error | Server error occurred |
Progress:
Let's test all our endpoints using curl or a tool like Postman.
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{
"name": "Alice Johnson",
"email": "alice@example.com",
"age": 28
}'
Response:
{
"_id": "65a1b2c3d4e5f6789abcdef0",
"name": "Alice Johnson",
"email": "alice@example.com",
"age": 28,
"createdAt": "2024-01-15T10:30:00.000Z"
}
curl http://localhost:3000/api/users
curl http://localhost:3000/api/users/65a1b2c3d4e5f6789abcdef0
curl -X PUT http://localhost:3000/api/users/65a1b2c3d4e5f6789abcdef0 \
-H "Content-Type: application/json" \
-d '{
"age": 29
}'
curl -X DELETE http://localhost:3000/api/users/65a1b2c3d4e5f6789abcdef0
Progress:
Congratulations! You've built a complete REST API. Here's what to learn next:
my-first-api/
├── config/
│ └── database.js
├── middleware/
│ ├── errorHandler.js
│ └── validation.js
├── models/
│ └── User.js
├── routes/
│ └── users.js
├── .env
├── .gitignore
├── package.json
└── server.js