Menu
CoddyTech

One Task by Id

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

A program that read the list now wants one task, at its own URL: /api/tasks/1/. The route takes the id with <int:pk>, as your detail pages did, and the starter's helper task_to_dict(task) turns a task into a dictionary.

The new part is a missing task. get_object_or_404 responds with Django's HTML 404 page, which a program cannot read, so an API sends its errors as JSON too, with the right status code, the number that says how a request went: 200 OK, 403 Forbidden, 404 Not Found. JsonResponse takes it as status:

return JsonResponse({"error": "Staff only"}, status=403)

To choose between the error and the task, look the row up without raising: filter(pk=...).first() returns the row, or None when there is none.

challenge icon

Challenge

Easy

Add an endpoint for one task.

  1. In tasks/views.py, add task_detail(request, pk). It responds with task_to_dict(task) as JSON. When no task has that id, respond with status 404 and {"error": "Task not found"}.
  2. In tasks/urls.py, add the route "api/tasks/<int:pk>/" named task_detail.

Open /api/tasks/99/: you see {"error": "Task not found"}.

Try it yourself

from django.http import JsonResponse
from django.shortcuts import render

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


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


def task_list(request):
    tasks = Task.objects.values("id", "title", "done", "priority")
    return JsonResponse(list(tasks), safe=False)
quiz iconTest yourself

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

All lessons in JSON APIs

Practice on your own: Django playground