简体   繁体   中英

Django Rest API POST issues

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?

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.

Just a guess: maybe the issue is in Postman?

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

在此输入图像描述

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?

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 传递

在此输入图像描述

You can fix it by using as in request header. 作为来修复它。

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM