A CRUD REST API for a task manager — GET, POST, PUT, DELETE endpoints using Express and an in-memory store.
Create a folder, init npm, and install Express.
mkdir task-api && cd task-api
npm init -y
npm install express
Write server.js with all four CRUD routes.
const express = require('express');
const app = express();
app.use(express.json());
let tasks = [];
let nextId = 1;
// GET all tasks
app.get('/tasks', (req, res) => {
res.json(tasks);
});
// GET single task
app.get('/tasks/:id', (req, res) => {
const task = tasks.find(t => t.id === +req.params.id);
if (!task) return res.status(404).json({ error: 'Not found' });
res.json(task);
});
// POST create task
app.post('/tasks', (req, res) => {
const { title } = req.body;
if (!title) return res.status(400).json({ error: 'Title is required' });
const task = { id: nextId++, title, done: false };
tasks.push(task);
res.status(201).json(task);
});
// PUT update task
app.put('/tasks/:id', (req, res) => {
const task = tasks.find(t => t.id === +req.params.id);
if (!task) return res.status(404).json({ error: 'Not found' });
Object.assign(task, req.body);
res.json(task);
});
// DELETE task
app.delete('/tasks/:id', (req, res) => {
tasks = tasks.filter(t => t.id !== +req.params.id);
res.status(204).send();
});
app.listen(3000, () => console.log('API running on http://localhost:3000'));
Run node server.js, then try these commands in a second terminal.
# Create a task
curl -X POST http://localhost:3000/tasks \
-H "Content-Type: application/json" \
-d '{"title":"Learn Express"}'
# List all tasks
curl http://localhost:3000/tasks
# Mark done
curl -X PUT http://localhost:3000/tasks/1 \
-H "Content-Type: application/json" \
-d '{"done":true}'
# Delete
curl -X DELETE http://localhost:3000/tasks/1
{"id":1,"title":"Learn Express","done":false}
[{"id":1,"title":"Learn Express","done":false}]
{"id":1,"title":"Learn Express","done":true}You now have a fully functional REST API. Connect a front-end to it or keep extending it with auth and a real database.
Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.