Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 a new user, so I send the user data in JSON format:

{     "username": "Test1",     "email": "[email protected]",     "first_name": "Test1",     "last_name": "Test2",     "password":"12121212" } 

I am using Google Chrome extension Postman to test the API. But, after sending the request, the user data is not saving. The response contains this error:

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

This is what the request details look like in Postman:

Postman API request to django-rest-framework error

like image 477
Elisa Avatar asked Jun 29 '15 04:06

Elisa


2 Answers

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.

like image 151
Rahul Gupta Avatar answered Sep 19 '22 21:09

Rahul Gupta


I'm posting this answer in case someone is facing a problem like mine.

I'm working on a Front-End app using Angular 2 with an API made with Django Rest Framework and I used to send requests with the following headers:

'Content-Type': 'application/json' 

And it was working fine until I tried it on Fire Fox and I couldn't load the needed data and I solved it with adding the following headers

'Content-Type': 'application/json', 'Accept': 'application/json' 

Here's an explanation, Content-Type tells the server what is the content type of data is while Accept tells it what content type the client side will accpet.

Here's a nice clear answer about this issue:

https://webmasters.stackexchange.com/questions/31212/difference-between-the-accept-and-content-type-http-headers

like image 29
Khaled Al-Ansari Avatar answered Sep 22 '22 21:09

Khaled Al-Ansari