request.data in DRF vs request.body in Django

You should use request.data. It’s more flexible, covers more use cases and it can be accessed as many times as needed. Quoting the docs:

Aboout request.data

REST framework introduces a Request object that extends the regular
HttpRequest, and provides more flexible request parsing. The core
functionality of the Request object is the request.data attribute,
which is similar to request.POST, but more useful for working with Web
APIs.

request.POST # Only handles form data. Only works for ‘POST’ method.

request.data # Handles arbitrary data. Works for ‘POST’, ‘PUT’ and
‘PATCH’ methods.

About request.body

The raw HTTP request body as a byte string. This is useful for
processing data in different ways than conventional HTML forms: binary
images, XML payload etc. For processing conventional form data, use
HttpRequest.POST.

So unless you want to handle binary images or XML payload, never use request.body, it’ll only be a simple string containing, well, the body of the request. Always use request.data which’ll be the fully parsed body (i.e. a Python dict) which is much more convenient to handle.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)