Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a JSON request in a view (using Django)

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.

like image 638
David542 Avatar asked Sep 10 '11 00:09

David542


2 Answers

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('')
like image 121
David542 Avatar answered Oct 03 '22 09:10

David542


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.

like image 28
gfdb Avatar answered Oct 03 '22 08:10

gfdb