Labs ICT
Pro Login

How to Build a REST API with Node.js and Express

JavaScript Web Development 8 min read

Build a fully functional REST API with Node.js and Express. Step-by-step guide with code examples.

How to Build a REST API with Node.js and Express

Building REST APIs is one of the most practical skills for a backend developer. With Node.js and Express, you can create a fully functional API in under an hour.

Setting Up Your Project

# Create project folder
mkdir my-api && cd my-api

# Initialize Node.js project
npm init -y

# Install Express
npm install express

Creating Your First API

const express = require('express');
const app = express();
app.use(express.json());

let users = [
  { id: 1, name: 'John', email: 'john@example.com' },
  { id: 2, name: 'Jane', email: 'jane@example.com' }
];

// GET all users
app.get('/api/users', (req, res) => {
  res.json(users);
});

// GET single user
app.get('/api/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).json({ error: 'User not found' });
  res.json(user);
});

// POST new user
app.post('/api/users', (req, res) => {
  const user = {
    id: users.length + 1,
    name: req.body.name,
    email: req.body.email
  };
  users.push(user);
  res.status(201).json(user);
});

// PUT update user
app.put('/api/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).json({ error: 'User not found' });
  user.name = req.body.name || user.name;
  user.email = req.body.email || user.email;
  res.json(user);
});

// DELETE user
app.delete('/api/users/:id', (req, res) => {
  users = users.filter(u => u.id !== parseInt(req.params.id));
  res.status(204).send();
});

app.listen(3000, () => {
  console.log('API running on http://localhost:3000');
});

Testing Your API

Use Postman, curl, or the browser to test:

# Get all users
curl http://localhost:3000/api/users

# Create a new user
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Bob","email":"bob@example.com"}'

Adding Error Handling

// Middleware for error handling
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Something went wrong!' });
});

Project Structure

For real projects, organize your code:

my-api/
├── routes/
│   └── users.js
├── models/
│   └── User.js
├── controllers/
│   └── userController.js
├── middleware/
│   └── auth.js
├── app.js
└── package.json

Note: Start simple, then add authentication, validation, database integration, and documentation as your API grows.