Menu
CoddyTech

Changing with PATCH

Part of the JSON APIs section of Coddy's Django journey. Lesson 9 of 19.

A program ticks a task off by sending {"done": true} to the task's URL, and nothing else. That URL stands for the task itself, a resource, and the method says what to do with it: GET reads it, PATCH changes part of it. Its sibling PUT replaces the whole resource.

So a PATCH view changes only the fields in the body. A default is the trap. In a bookshop API:

book.title = data.get("title", "")

A program that sends only {"available": false} wipes the title. Ask first whether the key was sent: "title" in data is True only then. Set each field that is there, save once, and answer with the changed object. The view needs @csrf_exempt and the new method in require_http_methods, as task_list has.

challenge icon

Challenge

Medium

Let programs change a task with PATCH /api/tasks/<id>/:

  • task_detail accepts GET and PATCH, and is @csrf_exempt.
  • PATCH sets title and done only when the body has them, saves, and answers with the task.
  • A missing task still answers 404.

Press Run, then in the Shell tab: from django.test import Client; print(Client().patch("/api/tasks/1/", {"done": True}, content_type="application/json").json())

Try it yourself

import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET, require_http_methods

from .models import Task


def task_to_dict(task):
    return {
        "id": task.id,
        "title": task.title,
        "done": task.done,
        "priority": task.priority,
    }


def home(request):
    return render(request, "tasks/home.html", {"tasks": Task.objects.all()})


@require_GET
def stats(request):
    data = {
        "total": Task.objects.count(),
        "done": Task.objects.filter(done=True).count(),
    }
    return JsonResponse(data)


@csrf_exempt
@require_http_methods(["GET", "POST"])
def task_list(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return JsonResponse({"error": "The body is not valid JSON."}, status=400)
        errors = {}
        title = data.get("title", "").strip()
        if not title:
            errors["title"] = "This field is required."
        if errors:
            return JsonResponse({"errors": errors}, status=400)
        task = Task.objects.create(
            title=title,
            priority=data.get("priority", "normal"),
        )
        return JsonResponse(task_to_dict(task), status=201)
    tasks = Task.objects.all()
    done = request.GET.get("done")
    if done == "true":
        tasks = tasks.filter(done=True)
    elif done == "false":
        tasks = tasks.filter(done=False)
    return JsonResponse([task_to_dict(task) for task in tasks], safe=False)


@require_GET
def task_detail(request, pk):
    task = Task.objects.filter(pk=pk).first()
    if task is None:
        return JsonResponse({"error": "Task not found"}, status=404)
    return JsonResponse(task_to_dict(task))

All lessons in JSON APIs

Practice on your own: Django playground