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 answers with Django's HTML 404 page, which a program cannot read. An API answers errors in 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 one task's endpoint:

  • A view task_detail(request, pk) that answers task_to_dict(task) as JSON.
  • For a missing id, {"error": "Task not found"} with status 404.
  • The route "api/tasks/<int:pk>/", named task_detail.

Press Run, then open /api/tasks/1/ and /api/tasks/99/.

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