'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.
Solution 1:[1]
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('')
Solution 2:[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.
Solution 3:[3]
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)
Solution 4:[4]
On a function view, you can try this out.
dp = json.dumps(request.data)
contact = json.loads(dp)
print(contact['first_name'])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | David542 |
Solution 2 | |
Solution 3 | |
Solution 4 | Noah Olatoye |