Elisa Elisa - 1 month ago 35
Python Question

django-rest-framework accept JSON data?

I have created RESTFul APIs using django-rest-framework. The user endpoint is

/api/v1/users


I want to create new user. I send user data in JSOn format.

{
"username": "Test1",
"email": "test1@gmail.com",
"first_name": "Test1",
"last_name": "Test2",
"password":"12121212"
}


I am using Chrome extension Postman to test api. But user data has not been saving. The response is:

{
"detail": "Unsupported media type \"text/plain;charset=UTF-8\" in request."
}


Attached screenshot
enter image description here

Answer

You have missed adding the Content-Type header in the headers section. Just set the Content-Type header to application/json and it should work.

See the below image:

postman

Also, you might also need to include a CSRF token in the header in case you get an error {"detail": "CSRF Failed: CSRF token missing or incorrect."} while making a POST request using Postman. In that case, add an X-CSRFToken header also with value as the CSRF token value.