What You'll Build
In this tutorial, you'll create a fully functional REST API using Node.js and Express. By the end, you'll have a working API that handles CRUD operations — Create, Read, Update, and Delete — for a simple resource like a to-do list.
Prerequisites
- Node.js (v18 or higher) installed on your machine
- Basic familiarity with JavaScript
- A terminal and a code editor (VS Code recommended)
- Postman or a similar API testing tool
Step 1: Initialize Your Project
Start by creating a new project directory and initializing it with npm:
mkdir my-api && cd my-api
npm init -y
npm install express
This creates a package.json and installs Express as a dependency.
Step 2: Create Your Entry Point
Create a file called index.js in your project root. This is where your server lives:
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
app.get('/', (req, res) => {
res.json({ message: 'Welcome to my API!' });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Step 3: Add CRUD Routes
Now let's add routes for a /tasks resource. We'll use an in-memory array to keep things simple:
let tasks = [];
let nextId = 1;
// GET all tasks
app.get('/tasks', (req, res) => res.json(tasks));
// POST a new task
app.post('/tasks', (req, res) => {
const task = { id: nextId++, ...req.body };
tasks.push(task);
res.status(201).json(task);
});
// PUT update a task
app.put('/tasks/:id', (req, res) => {
const index = tasks.findIndex(t => t.id === parseInt(req.params.id));
if (index === -1) return res.status(404).json({ error: 'Not found' });
tasks[index] = { ...tasks[index], ...req.body };
res.json(tasks[index]);
});
// DELETE a task
app.delete('/tasks/:id', (req, res) => {
tasks = tasks.filter(t => t.id !== parseInt(req.params.id));
res.status(204).send();
});
Step 4: Test Your API
Run your server with node index.js, then use Postman or curl to test each endpoint:
- GET /tasks — retrieves all tasks
- POST /tasks — send a JSON body like
{"title": "Learn Express"} - PUT /tasks/1 — update task with ID 1
- DELETE /tasks/1 — delete task with ID 1
Next Steps
This is a great foundation. From here, you can:
- Connect a real database like MongoDB or PostgreSQL
- Add input validation with a library like Joi or Zod
- Implement authentication using JWT
- Add error-handling middleware for cleaner responses
REST APIs power the majority of modern web applications. Mastering Express gives you a versatile tool that scales from small projects to production-grade systems.