StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 17 · DRF Views & Routers

API View Responses

mediumDjango REST FrameworkDRF Views & Routers—No data yet

Problem statement

In this Django project, reimplement the catalogue's two endpoints as DRF APIView classes. Build the views in app/views.py and point the routes in app/urls.py at them, so that every outcome carries the status code that describes it and every body is parsed by the request rather than by the view. Today both endpoints are plain Django views that answer 200 whatever happened, read the body with their own json.loads so a form-encoded post is unreadable, and handle any method that arrives.

Requirements

Implement:

  • the two product endpoints in app/views.py
  • the two path() entries that point at them in app/urls.py

The following files are already implemented and provided: app/models.py and app/serializers.py. Product holds name, sku, price and in_stock. ProductSerializer carries id, name, sku, price and in_stock, with id read-only; it already decides what a valid payload is and what the output shape is, so no view in this project builds a dictionary by hand or writes an error message of its own. The home view and its "" route are given: an ordinary Django view answering the running server's port, and no part of this exercise.

1. The two routes

  • /api/products/ keeps the route name product-list, and /api/products/<int:pk>/ keeps the route name product-detail. The tests reach every endpoint through reverse("product-list") and reverse("product-detail"), so both paths and both names survive unchanged.
  • Each route points at an APIView subclass through .as_view(). The two product routes are the whole API surface: there is no update endpoint.
  • The home view and its "" route stay where they are.

2. The methods each route offers, and only those

  • The collection offers GET and POST. The item offers GET and DELETE.
  • A PUT at the collection comes back 405 Method Not Allowed with an Allow header that names GET and POST and does not name PUT, PATCH or DELETE.
  • A PATCH at an item comes back 405 Method Not Allowed with an Allow header that names GET and DELETE and does not name PATCH, PUT or POST.
  • A method a route does not offer changes nothing: the row a refused PATCH was aimed at is still as it was.

3. The body comes from the request, not from the view

  • The serializer is handed request.data, so one and the same POST succeeds whether the client sent a JSON body or a form-encoded body.
  • Nothing reads request.body, and json is not imported anywhere.

4. A status code and a body per outcome

  • A GET at the collection returns 200, and its body is every product as ProductSerializer(Product.objects.all(), many=True).data.
  • A GET at an item returns 200, and its body is that one product as the serializer renders it.
  • A POST the serializer accepts returns 201, the row is stored, and the body is the created product as the serializer renders it, including the id it was given.
  • A POST the serializer refuses returns 400, no row is stored, and the body is serializer.errors itself: nothing wrapped around it and nothing summarised.
  • A GET or a DELETE for an id that is not in the table returns 404, and no row is removed while answering it.
  • A DELETE that removed the row returns 204 with an empty body, and only that one row is gone.

Notes

  • An APIView offers exactly the HTTP methods it defines a handler for, and answers any other method with 405 and an Allow header listing the rest, without any code of yours. The handler is what declares the method, so withdrawing a verb means not defining it rather than guarding inside it.
  • request.data is the parsed body whatever the content type was, because the parsing happened before the handler ran. json.loads(request.body) understands one of the two content types and raises on the other.
  • rest_framework.status names the codes, so the code reads as the outcome rather than as a number. Response(status=status.HTTP_204_NO_CONTENT) is what produces a 204 with no body at all.
  • get_object_or_404 raises Http404 and DRF renders that as a 404; raising rest_framework.exceptions.NotFound does the same. Either beats Product.objects.filter(pk=pk).first() followed by a 200 with nothing in it, which tells the client the product exists and is empty.
  • serializer.errors as the whole body is the point: {"price": ["A valid number is required."]} tells the client which field to fix, and {"detail": "bad request"} does not.
  • Only app/views.py and app/urls.py change. Do not write a serializer, a validator or an error message.
  • APIView subclasses only: no generic view, no ViewSet and no router, and no authentication, permission, throttle or pagination setting on either class.

More in DRF Views & Routers

See the module
Generic API ViewsEvery method of the article API spells out the same fetch-validate-save-respond cycle by hand, and the hand-written code takes the author from whatever the client posted. Replace both classes with DRF's generic list-create and retrieve-update-destroy views, declaring queryset and serializer_class, and set the author from the request user in perform_create.—No data yetmediumViewSet With RouterThe recipe API spread one resource across five hand-written URL patterns and five separate views that kept drifting apart, and publishing was bolted on as an unrelated endpoint. Consolidate the resource into a ModelViewSet registered on a DefaultRouter under an explicit basename, with a detail-level publish action and a list-level recent action, each restricted to the method it declares.—No data yetmediumTask Board APIA team task board needs its whole API surface - task CRUD, workflow operations and a board summary - and today it is a tangle of JsonResponse views that answer 200 for everything. Build the API: a task ModelViewSet on a router with named routes, partial updates, a server-set creator, a detail-level complete action, a list-level overdue action and a board-summary APIView, with the defined status code for every outcome.—No data yetmedium

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.