7

I'm trying to build a very simple REST API in Django 1.8 with Django REST Framework in Visual Studio, in which I want to have a single service method to process a JSON, but I can't seem to make a POST:

I'm trying to send this simple JSON through Postman, just as a test:

{
   "foo":"bar"
}

with the header:

Content-Type: application/json

Here's my method:

@csrf_exempt
@api_view(['POST'])
def test(request):
    data = request.data
    return HttpResponse(status=200)

But my problem is that request.data is empty. And if instead I try to access request.body, I get

You cannot access body after reading from request's data stream.

Any ideas what could be the issue here?

tamasgobesz
  • 185
  • 2
  • 9

4 Answers4

2

Figured this out somewhat, it seems to be an issue with Visual Studio while in debug mode. If I try to access the request while debugging before calling any Python function on it (such as a simple print, or passing in to a function to parse it), it shows up as an empty QueryDict, otherwise it shows up fine.

tamasgobesz
  • 185
  • 2
  • 9
1

Just a guess: maybe the issue is in Postman?

Try to send POST-request without headers, but with raw JSON (not form-data):

enter image description here

Ihor Pomaranskyy
  • 5,437
  • 34
  • 37
  • 1
    I was doing exactly this, but with the header set to Content-Type: application/json. Without the header, request.POST is still and empty QueryDict, while request.data gives me "Unsupported media type "text/plain;charset=UTF-8" in request." – tamasgobesz Nov 18 '15 at 16:30
1

This may help Where's my JSON data in my incoming Django request?

Outside of this, make sure the content-type and accept-type are set properly. What is the raw response in Postman? Is the security setup properly?

Community
  • 1
  • 1
Jared Knipp
  • 5,880
  • 7
  • 44
  • 52
  • As I only try to read the JSON and nothing else, the raw response gives my back 200 OK, as expected. It's running on localhost, nothing changed from the default project, so it should not be a security issue. The parser recognizes my content type as JSON, but the content just comes out as empty. – tamasgobesz Nov 18 '15 at 16:48
  • This is over simplifying, but have you confirmed your unit test produces a valid JSON result? What are you expecting it to return? – Jared Knipp Nov 18 '15 at 16:50
  • This is not related to unit tests, I'm manually making a post through Postman, which produces a valid JSON. – tamasgobesz Nov 19 '15 at 08:13
1

I have the same problem when using POSTMAN.

Solved and Credit goes to https://stackoverflow.com/a/31977373/764592

Quoted Answer:

Request payload is not converted into JSON format.

I am passing my data in Body as x-www-form-urlencoded

enter image description here

You can fix it by using Content-Type as application/x-www-form-urlencoded in request header.

enter image description here

Community
  • 1
  • 1
Yeo
  • 11,416
  • 6
  • 63
  • 90