Menu
CoddyTech

Replacing with PUT

Part of the REST APIs section of Coddy's Node.js journey. Lesson 5 of 18.

An edit form sends back the whole task, every field at once. PUT means "replace the resource with this", so the body must be complete.

PATCH /api/invoices/7  { "paid": true }               → paid changes
PUT   /api/invoices/7  { "amount": 90, "paid": true } → a new invoice 7
PUT   /api/invoices/7  { "paid": true }               → 400: amount missing

A PUT with a field missing answers 400: replacing with half an invoice would lose the amount. Fields the server owns, like the id and the creation time, come from the old version, never from the body:

const { id, issuedAt } = invoices[index];
invoices[index] = { id, amount, paid, issuedAt };
challenge icon

Challenge

Easy
  • PUT /api/tasks/:id replaces title and done with the body's values and answers 200 with the task.
  • id and createdAt stay as they were.
  • A missing title or done: 400. An unknown id: 404.

Send PUT /api/tasks/2 with { "title": "Book the big room", "done": true }, then with { "done": true }.

Try it yourself

import { Router } from 'express';
import { nextId, tasks } from '../store.js';

const router = Router();

router.get('/', (req, res) => {
    res.json(tasks);
});

router.get('/:id', (req, res) => {
    const task = tasks.find((t) => t.id === Number(req.params.id));
    if (!task) {
        return res.status(404).json({ error: 'Task not found' });
    }
    res.json(task);
});

router.post('/', (req, res) => {
    const { title } = req.body ?? {};
    if (!title) {
        return res.status(400).json({ error: 'title is required' });
    }
    const task = { id: nextId(), title, done: false, createdAt: new Date().toISOString() };
    tasks.push(task);
    res.status(201).location(`/api/tasks/${task.id}`).json(task);
});

router.patch('/:id', (req, res) => {
    const task = tasks.find((t) => t.id === Number(req.params.id));
    if (!task) {
        return res.status(404).json({ error: 'Task not found' });
    }
    const { title, done } = req.body ?? {};
    if (title !== undefined) task.title = title;
    if (done !== undefined) task.done = done;
    res.json(task);
});

router.delete('/:id', (req, res) => {
    const index = tasks.findIndex((t) => t.id === Number(req.params.id));
    if (index === -1) {
        return res.status(404).json({ error: 'Task not found' });
    }
    tasks.splice(index, 1);
    res.status(204).end();
});

export default router;
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in REST APIs