Introduction
REST APIs are the backbone of modern web applications. Whether you're powering a mobile app, a frontend SPA, or a microservice architecture, knowing how to build a clean, reliable REST API is a fundamental skill for every backend developer. In this tutorial, we'll walk through building a REST API from scratch using Node.js and Express.
Prerequisites
- Node.js (v18+) installed on your machine
- Basic knowledge of JavaScript
- A code editor (VS Code recommended)
- A REST client like Postman or Insomnia for testing
Step 1: Initialize Your Project
Start by creating a new directory and initializing a Node.js project:
mkdir my-rest-api
cd my-rest-api
npm init -y
npm install express
This sets up your package.json and installs Express as a dependency.
Step 2: Create the Express Server
Create an index.js file in your project root and add the following boilerplate:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
The express.json() middleware automatically parses incoming JSON request bodies — essential for handling POST and PUT requests.
Step 3: Define Your Routes (CRUD)
For this example, we'll build a simple items resource. Add these routes to your index.js:
let items = [];
let nextId = 1;
// GET all items
app.get('/items', (req, res) => {
res.json(items);
});
// GET single item
app.get('/items/:id', (req, res) => {
const item = items.find(i => i.id === parseInt(req.params.id));
if (!item) return res.status(404).json({ error: 'Item not found' });
res.json(item);
});
// POST create item
app.post('/items', (req, res) => {
const item = { id: nextId++, ...req.body };
items.push(item);
res.status(201).json(item);
});
// PUT update item
app.put('/items/:id', (req, res) => {
const index = items.findIndex(i => i.id === parseInt(req.params.id));
if (index === -1) return res.status(404).json({ error: 'Item not found' });
items[index] = { ...items[index], ...req.body };
res.json(items[index]);
});
// DELETE item
app.delete('/items/:id', (req, res) => {
items = items.filter(i => i.id !== parseInt(req.params.id));
res.status(204).send();
});
Step 4: Add Basic Error Handling
Always add a catch-all error handler at the end of your middleware stack:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Internal Server Error' });
});
Step 5: Test Your API
Run your server with node index.js and use Postman to send requests to http://localhost:3000/items. Test each HTTP method to confirm your CRUD operations work correctly.
Next Steps
- Connect to a real database like MongoDB or PostgreSQL
- Add input validation with a library like Joi or Zod
- Implement authentication using JWT
- Structure your project using the MVC pattern for scalability
Building a REST API with Node.js and Express is straightforward once you understand the fundamentals. From here, you can evolve this simple server into a production-grade API with proper structure, validation, and security.