Question: Unable to access values in Request

Question

Unable to access values in Request

Answers 1
Added at 2016-12-28 01:12
Tags
Question

I am not understanding how to access values in my POST request from within my Python API.

Why can I not access the values in my API Request? I am clearly getting them in the request.body, but am unable to retrieve them.

I have tried the following methods:

request.POST['username']
request.POST.get('username')

I receive an error stating django.utils.datastructures.MultiValueDictKeyError:

Here is the request.body, which does not seem like JSON at all.

"{\n \"username\": \"TestUsername\",\n \"password\": \"TestPass\"\n}"

POST REQUEST

{
  "username": "TestUsername",
  "password": "TestPass"
}

HEADERS

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

VIEW

@csrf_exempt
@api_view(['POST'])
def create(request):
    user = User()
    if 'username' in request.POST and 'password' in request.POST:
        user.username = request.POST['username']
        user.set_password(request.POST['password'])
        user.save()
        return Response({'Status' : 'Complete'})
    else:
        return Response({'Status': 'Incomplete'})
Answers
nr: #1 dodano: 2016-12-28 01:12

Seems to me that because your Content-Type header is application/json, you first need to parse the request body as JSON:

import json

body = json.loads(request.POST)

Although I would think that Django should automatically handle this. Let me know if it works out for you!

EDIT: Looks like you're using Django REST Framework. If so: access your data using request.data instead of request.POST['key'].

Source Show
◀ Wstecz