6

I am trying to set up a view to received a JSON notification from an API. I'm trying to figure out how to get the JSON data, and I currently have this as a starting point to see that the request is being properly received:

def api_response(request):
    print request
    return HttpResponse('')

I know the JSON object is there because in the print request it shows:

META:{'CONTENT_LENGTH': '178',
[Fri Sep 09 16:42:27 2011] [error]  'CONTENT_TYPE': 'application/json',

However, both of the POST and GET QueryDicts are empty. How would I set up a view to receive the JSON object so I can process it? Thank you.

steveha
  • 74,789
  • 21
  • 92
  • 117
David542
  • 104,438
  • 178
  • 489
  • 842

4 Answers4

9

This is how I did it:

def api_response(request):
    try:
        data=json.loads(request.raw_post_data)
        label=data['label']
        url=data['url']
        print label, url
    except:
        print 'nope'
    return HttpResponse('')
David542
  • 104,438
  • 178
  • 489
  • 842
  • 2
    I would add: if this is a common pattern in your application, write a decorator to apply to affected functions. – Luke Sneeringer Sep 10 '11 at 18:18
  • 9
    looks like it changed in django 1.4 to use `request.body` instead of `raw_post_data`. http://stackoverflow.com/questions/1208067/wheres-my-json-data-in-my-incoming-django-request – Aleck Landgraf May 08 '13 at 04:38
2

I'm going to post an answer to this since it is the first thing I found when I searched my question on google. I am using vanilla django version 3.2.9. I was struggling to retrieve data after making a post request with a json payload to a view. After searching for a while, I finally found the json in request.body.

Note: request.body is of type bytes, you'll have to decode it to utf-8, my_json_as_bytes.decode('utf-8') or, if you want a dictionary, you can just use json.load(request.body) to decode directly.

gfdb
  • 311
  • 2
  • 9
1

On a function view, you can try this out.

dp = json.dumps(request.data)
contact = json.loads(dp)
print(contact['first_name'])
0

For Class-Based Views built Using Django-Rest-Framework, you can use built-in JSONParser to get JSON data in request.data

from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView

class MyOveridingView(APIView):
    parser_classes = [JSONParser]

class MyActualView(MyOveridingView):

    def post(self, request, *args, **kwargs):
        request_json = request.data
        return JsonResponse(data=request_json, status=200)
avvijeet
  • 41
  • 1
  • 4