Coova
Coova

Reputation: 1858

Unable to access values in Request

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'})

Upvotes: 2

Views: 222

Answers (1)

Chuck
Chuck

Reputation: 884

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'].

Upvotes: 3

Related Questions