JSON From a View

The smallest possible API. A view that returns JsonResponse instead of render. No extra library, and perfectly reasonable for a handful of endpoints.

.values("id", "title") returns dictionaries rather than model instances, which serialize directly.

Return an object, not a bare array. {"results": [...]} rather than [...].

A bare array leaves you nowhere to put a count, a next page, or an error, and adding one later breaks every client that already parses it. The wrapper costs nothing today and buys room to change.

Choose the fields deliberately. Serializing a whole model is how email addresses and password hashes end up in public responses. Name what goes out, exactly as you name form fields, and for the same reason.

◈ Graded Challenge

Write serialize(posts, page, per_page) shaping an API response. posts is a list of dictionaries, each with id, title, body, secret and published. Include only published posts. From each, expose only id, title and body, never secret. Paginate with page starting at 1. Return {"count": total published, "page": page, "results": [...]} where results holds only that page's items.

Name it exactly: serialize(posts, page, per_page)

Python3 visible + 4 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Django REST Framework →
← Back