Menu
CoddyTech

Partial Updates with PATCH

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

Marking a task done should not mean sending its title again. PATCH carries only the fields that change, and the server keeps every other field as it was.

// PATCH /api/invoices/7   { "paid": true }
const { paid, amount } = req.body ?? {};
if (paid !== undefined) invoice.paid = paid;
if (amount !== undefined) invoice.amount = amount;
res.json(invoice);

Test each field against undefined, not with if (paid): false is a value a client can send. Copy the fields one by one instead of spreading req.body over the object, so a client cannot change the id. A request without a body leaves req.body undefined, which is what ?? {} covers. The answer is 200 with the whole updated invoice.

challenge icon

Challenge

Easy
  • PATCH /api/tasks/:id changes only the fields the body sends, title or done.
  • It answers 200 with the whole task.
  • An unknown id answers 404 with { "error": "Task not found" }.

Send PATCH /api/tasks/2 with { "done": true }, then GET /api/tasks/2, then the same PATCH to /api/tasks/99.

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);
});

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