Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 39 ยท Getting Started

Request, Response and Status Codes

Understand DRF's Request and Response objects: request.data, query_params, user, headers, status codes and error responses, with runnable examples.

Every DRF handler receives a Request and returns a Response. They look like Django's HttpRequest and HttpResponse, but they are designed for APIs: the request parses JSON, form data and uploads into one uniform attribute, and the response stores plain Python data that is rendered into JSON, HTML or another format only at the last moment, after the framework has negotiated with the client.

Understanding these two classes removes most of the surprises beginners meet, such as "why is request.POST empty?" or "why does my response change shape in the browser?".

The Request object

A DRF Request wraps the Django request and adds a few attributes. The important ones are:

Attribute What it holds
request.data The parsed body: a dict for JSON and form data, a QueryDict for forms and multipart, including uploaded files
request.query_params The query string (?page=2&q=dune), the same as Django's request.GET
request.method "GET", "POST", ... in upper case
request.user The authenticated user, or AnonymousUser
request.auth The credential used (for example the token object)
request.content_type The media type of the body
request.accepted_renderer The renderer that will format the response

request.data replaces both request.POST and request.body. Unlike request.POST, it works for every HTTP method (a PUT body is parsed too) and for every format your parsers support.

Python One request.data, three body formats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the values: the JSON body gives you real integers, while the two form formats deliver text ("36"). That is expected: HTML forms only send strings. The serializer you will add in the next chapter converts them for you. The PUT body was parsed too, and for a GET request request.data is simply empty.

Do not read request.body after touching request.data. A request body is a stream that can be read once, and DRF has already consumed it. If you need the raw bytes (for example to verify a webhook signature), read them before anything else, or use a lower-level Django view for that endpoint.

The Response object

Python
from rest_framework.response import Response

Response(data=None, status=None, template_name=None, headers=None, content_type=None)

data is any structure of dicts, lists, strings, numbers, booleans and None. It is not rendered yet: it waits until the view returns, so the framework can pick JSON, the browsable HTML page or any other renderer based on the Accept header. Do not pass in a rendered JSON string, a Django model instance or a queryset; serialize them first.

You can set the status code and extra headers on construction. After the call, response.data still holds the original data, which is convenient in tests.

Python Status codes, headers and an empty body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The 204 response has an empty body: b''. That is correct for "success, nothing to send back". The /missing/ URL has no view at all, so Django answers with its own 404 page (an HTML or empty body, not DRF JSON): URL resolution happens before DRF is involved. Finally, status.is_success() and friends help in tests and middleware.

Choosing the right status code

Status codes are part of your API's contract. Clients (and developers reading logs) rely on them. The common ones:

Code Name Use it when
200 OK A read or update succeeded and you return a body
201 Created A new resource was created (add a Location header when you can)
204 No Content Success with nothing to return, usually after DELETE
400 Bad Request The body is malformed or fails validation
401 Unauthorized The caller is not authenticated (missing or invalid credentials)
403 Forbidden Authenticated, but not allowed
404 Not Found The resource does not exist (or you hide that it exists)
405 Method Not Allowed The URL exists but not for this method
409 Conflict The request clashes with current state, for example a duplicate
415 Unsupported Media Type No parser matches the request's Content-Type
429 Too Many Requests A throttle limit was hit
500 Server Error A bug; never return it deliberately
flowchart TD
    Q["Did the request succeed?"] -->|yes| S{"Return a body?"}
    S -->|yes| OK["200 / 201"]
    S -->|no| NC["204"]
    Q -->|no| W{"Whose fault?"}
    W -->|client| C["4xx: 400, 401, 403, 404, 409 ..."]
    W -->|server| E["5xx: fix the bug"]

Pick a 2xx for success, a 4xx when the caller must change something and a 5xx only for your own failures.

The shape of error responses

DRF uses a consistent shape that clients can rely on. A single problem such as a missing resource or denied permission is {"detail": "..."}. Validation problems are a dictionary of field names to lists of messages. You saw both in earlier examples. Keep to these shapes in your own views: raise rest_framework.exceptions classes (NotFound, PermissionDenied, ValidationError, ParseError) instead of building error dictionaries by hand, and DRF produces the right status and body. The next chapters return to this in custom exception handling.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which attribute holds the parsed body of a JSON PUT request in DRF?

    request.data is parsed for every method and format. request.POST only covers form data on POST.
  2. 2. A client posts an HTML form. What type will the number 36 have in request.data?

    Form encodings carry only text. A serializer field such as IntegerField converts it.
  3. 3. Which status fits a successful DELETE with no response body?

    204 No Content means success without a body.
  4. 4. When does DRF turn the data in a Response into JSON?

    Response stores plain data. The renderer chosen from the Accept header formats it afterwards.
  5. 5. Which status should an unauthenticated caller receive for a protected endpoint?

    401 means credentials are missing or invalid. 403 means the authenticated caller lacks permission.

Summary

  • request.data is the one place for parsed body data, whatever the method and format; request.query_params replaces request.GET.
  • Form-based bodies deliver strings; JSON keeps numbers and booleans.
  • Response holds plain data and is rendered later, so give it dictionaries and lists, never model instances.
  • Choose status codes deliberately: 200, 201, 204 for success; 400, 401, 403, 404, 405, 409, 429 for client problems.
  • Raise DRF exception classes to get consistent {"detail": ...} and field-error bodies.

Next: Parsers, Renderers and Content Negotiation