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.

Introduction

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
Project Setup

Let's create a new Express.js project from scratch.

Step 1: Initialize project

bash
# Create project directory
mkdir my-api
cd my-api
# Initialize npm
npm init -y

Step 2: Install Express

bash
# Install Express
npm 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:

json
{
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
}
}
Creating Your First Route

Create an index.js file with a basic Express server:

js
1const express = require('express');
2const app = express();
3const PORT = 3000;
4
5// Middleware to parse JSON
6app.use(express.json());
7
8// Basic GET route
9app.get('/', (req, res) => {
10 res.json({ message: 'Welcome to my API' });
11});
12
13// Route with parameters
14app.get('/users/:id', (req, res) => {
15 const userId = req.params.id;
16 res.json({
17 userId,
18 message: `User ID: ${userId}`
19 });
20});
21
22// Route with query parameters
23app.get('/search', (req, res) => {
24 const { q, page = 1 } = req.query;
25 res.json({
26 query: q,
27 page: parseInt(page)
28 });
29});
30
31// Start server
32app.listen(PORT, () => {
33 console.log(`Server running on http://localhost:${PORT}`);
34});

Run your server

bash
# For development (auto-restart on changes)
npm run dev
# For production
npm start

Visit http://localhost:3000 in your browser or use a tool like Postman to test the API.

Middleware

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

js
1// Custom logging middleware
2app.use((req, res, next) => {
3 console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
4 next(); // Pass control to next middleware
5});

Authentication middleware

js
1// Authentication middleware
2const authenticate = (req, res, next) => {
3 const token = req.headers.authorization;
4
5 if (!token) {
6 return res.status(401).json({ error: 'No token provided' });
7 }
8
9 // Verify token (simplified example)
10 if (token !== 'valid-token') {
11 return res.status(401).json({ error: 'Invalid token' });
12 }
13
14 // Attach user to request
15 req.user = { id: 1, name: 'John' };
16 next();
17};
18
19// Use middleware on specific routes
20app.get('/protected', authenticate, (req, res) => {
21 res.json({
22 message: 'This is protected data',
23 user: req.user
24 });
25});

Error handling middleware

js
1// Error handling middleware (put this last)
2app.use((err, req, res, next) => {
3 console.error(err.stack);
4
5 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});
Building a Complete REST API

Here's a complete example of a RESTful API for managing users with all CRUD operations.

js
1const express = require('express');
2const app = express();
3
4// Middleware
5app.use(express.json());
6
7// 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];
12
13// GET all users
14app.get('/api/users', (req, res) => {
15 res.json(users);
16});
17
18// GET single user
19app.get('/api/users/:id', (req, res) => {
20 const user = users.find(u => u.id === parseInt(req.params.id));
21
22 if (!user) {
23 return res.status(404).json({ error: 'User not found' });
24 }
25
26 res.json(user);
27});
28
29// POST create user
30app.post('/api/users', (req, res) => {
31 const { name, email } = req.body;
32
33 // Validation
34 if (!name || !email) {
35 return res.status(400).json({ error: 'Name and email required' });
36 }
37
38 const newUser = {
39 id: users.length + 1,
40 name,
41 email
42 };
43
44 users.push(newUser);
45 res.status(201).json(newUser);
46});
47
48// PUT update user
49app.put('/api/users/:id', (req, res) => {
50 const user = users.find(u => u.id === parseInt(req.params.id));
51
52 if (!user) {
53 return res.status(404).json({ error: 'User not found' });
54 }
55
56 const { name, email } = req.body;
57 if (name) user.name = name;
58 if (email) user.email = email;
59
60 res.json(user);
61});
62
63// DELETE user
64app.delete('/api/users/:id', (req, res) => {
65 const index = users.findIndex(u => u.id === parseInt(req.params.id));
66
67 if (index === -1) {
68 return res.status(404).json({ error: 'User not found' });
69 }
70
71 users.splice(index, 1);
72 res.status(204).send();
73});
74
75// Start server
76const 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.

Testing Your API

You can test your API using cURL, Postman, or any HTTP client. Here are examples using cURL:

GET all users

bash
curl http://localhost:3000/api/users

GET single user

bash
curl http://localhost:3000/api/users/1

POST create user

bash
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"name":"Charlie","email":"charlie@example.com"}'

PUT update user

bash
curl -X PUT http://localhost:3000/api/users/1 \
-H "Content-Type: application/json" \
-d '{"name":"Alice Updated"}'

DELETE user

bash
curl -X DELETE http://localhost:3000/api/users/1

Using Postman

Postman is a popular API testing tool with a graphical interface:

  1. Download Postman from postman.com
  2. Create a new request
  3. Set the HTTP method (GET, POST, PUT, DELETE)
  4. Enter the URL (e.g., http://localhost:3000/api/users)
  5. For POST/PUT, add JSON body in the "Body" tab
  6. 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.

Built for learning — keep experimenting!