API Development with Express.js
Learn how to build production-ready REST APIs using Express.js and Node.js. From basic routes to complete CRUD operations with best practices.
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It's the de facto standard for building APIs with Node.js.
Why Express.js?
- Minimal: Provides just what you need, no bloat
- Flexible: Use any database, template engine, or architecture
- Fast: Built on Node.js for high performance
- Popular: Large ecosystem and community support
Let's create a new Express.js project from scratch.
Step 1: Initialize project
# Create project directorymkdir my-apicd my-api# Initialize npmnpm init -y
Step 2: Install Express
# Install Expressnpm install express# Install nodemon for development (optional but recommended)npm install --save-dev nodemon
Step 3: Update package.json
Add scripts to your package.json:
{"scripts": {"start": "node index.js","dev": "nodemon index.js"}}
Create an index.js file with a basic Express server:
1const express = require('express');2const app = express();3const PORT = 3000;45// Middleware to parse JSON6app.use(express.json());78// Basic GET route9app.get('/', (req, res) => {10 res.json({ message: 'Welcome to my API' });11});1213// Route with parameters14app.get('/users/:id', (req, res) => {15 const userId = req.params.id;16 res.json({17 userId,18 message: `User ID: ${userId}`19 });20});2122// Route with query parameters23app.get('/search', (req, res) => {24 const { q, page = 1 } = req.query;25 res.json({26 query: q,27 page: parseInt(page)28 });29});3031// Start server32app.listen(PORT, () => {33 console.log(`Server running on http://localhost:${PORT}`);34});
Run your server
# For development (auto-restart on changes)npm run dev# For productionnpm start
Visit http://localhost:3000 in your browser or use a tool like Postman to test the API.
Middleware functions have access to the request and response objects. They can modify them, end the request-response cycle, or call the next middleware.
Logging middleware
1// Custom logging middleware2app.use((req, res, next) => {3 console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);4 next(); // Pass control to next middleware5});
Authentication middleware
1// Authentication middleware2const authenticate = (req, res, next) => {3 const token = req.headers.authorization;45 if (!token) {6 return res.status(401).json({ error: 'No token provided' });7 }89 // Verify token (simplified example)10 if (token !== 'valid-token') {11 return res.status(401).json({ error: 'Invalid token' });12 }1314 // Attach user to request15 req.user = { id: 1, name: 'John' };16 next();17};1819// Use middleware on specific routes20app.get('/protected', authenticate, (req, res) => {21 res.json({22 message: 'This is protected data',23 user: req.user24 });25});
Error handling middleware
1// Error handling middleware (put this last)2app.use((err, req, res, next) => {3 console.error(err.stack);45 res.status(err.status || 500).json({6 error: {7 message: err.message || 'Something went wrong!',8 ...(process.env.NODE_ENV === 'development' && { stack: err.stack })9 }10 });11});
Here's a complete example of a RESTful API for managing users with all CRUD operations.
1const express = require('express');2const app = express();34// Middleware5app.use(express.json());67// In-memory data store (use a database in production)8let users = [9 { id: 1, name: 'Alice', email: 'alice@example.com' },10 { id: 2, name: 'Bob', email: 'bob@example.com' }11];1213// GET all users14app.get('/api/users', (req, res) => {15 res.json(users);16});1718// GET single user19app.get('/api/users/:id', (req, res) => {20 const user = users.find(u => u.id === parseInt(req.params.id));2122 if (!user) {23 return res.status(404).json({ error: 'User not found' });24 }2526 res.json(user);27});2829// POST create user30app.post('/api/users', (req, res) => {31 const { name, email } = req.body;3233 // Validation34 if (!name || !email) {35 return res.status(400).json({ error: 'Name and email required' });36 }3738 const newUser = {39 id: users.length + 1,40 name,41 email42 };4344 users.push(newUser);45 res.status(201).json(newUser);46});4748// PUT update user49app.put('/api/users/:id', (req, res) => {50 const user = users.find(u => u.id === parseInt(req.params.id));5152 if (!user) {53 return res.status(404).json({ error: 'User not found' });54 }5556 const { name, email } = req.body;57 if (name) user.name = name;58 if (email) user.email = email;5960 res.json(user);61});6263// DELETE user64app.delete('/api/users/:id', (req, res) => {65 const index = users.findIndex(u => u.id === parseInt(req.params.id));6667 if (index === -1) {68 return res.status(404).json({ error: 'User not found' });69 }7071 users.splice(index, 1);72 res.status(204).send();73});7475// Start server76const PORT = 3000;77app.listen(PORT, () => {78 console.log(`API server running on http://localhost:${PORT}`);79});
Production Note
This example uses an in-memory array for simplicity. In production, use a proper database like PostgreSQL, MongoDB, or MySQL.
You can test your API using cURL, Postman, or any HTTP client. Here are examples using cURL:
GET all users
curl http://localhost:3000/api/users
GET single user
curl http://localhost:3000/api/users/1
POST create user
curl -X POST http://localhost:3000/api/users \-H "Content-Type: application/json" \-d '{"name":"Charlie","email":"charlie@example.com"}'
PUT update user
curl -X PUT http://localhost:3000/api/users/1 \-H "Content-Type: application/json" \-d '{"name":"Alice Updated"}'
DELETE user
curl -X DELETE http://localhost:3000/api/users/1
Using Postman
Postman is a popular API testing tool with a graphical interface:
- Download Postman from postman.com
- Create a new request
- Set the HTTP method (GET, POST, PUT, DELETE)
- Enter the URL (e.g., http://localhost:3000/api/users)
- For POST/PUT, add JSON body in the "Body" tab
- Click "Send" to execute the request
Congratulations!
You've completed the Node.js essentials! You now have the knowledge to build production-ready applications with Node.js and Express.js. Keep practicing and building projects to solidify your skills.