This is a record of my experiences parsing JSON in a REST service written with Django, in Python.
I’m following various tutorials (including Django’s REST framework tutorial), but I was really struggling to get a snippet of JSON actually processed on the server side.
The service in question was really quite simple: a name completion service, given a band name in a Suggestion
object.
def bandnames(request):
if(request.method)=='POST':
d=request.body
stream=BytesIO(d)
data=JSONParser().parse(stream)
serializer=SuggestionSerializer(data=data)
return bandcompletion(request, serializer.initial_data["band"])
else:
return HttpResponse("Bad request: Wrong method")
The bandcompletion
method actually does the work of returning a JSONResponse
– this is basically a wrapper method to accept JSON from the body of a POST request.
I was unimpressed with the sequence: I get a str
from request.body
, but then I have to convert it to a stream for JSONParser.parse
(with BytesIO
), which was actually the point at which I was getting lost. Apart from that – which I think was obscure only to me – everything was pretty straightforward.
Now I can issue an HTTP request via curl
:
curl -i -H "Content-Type: application/json" -X POST \
-d "{ \"band\":\"r\" }" \
http://127.0.0.1:8000/bands
Postman can submit the data as raw body text for the request as well.
There’s no error checking here yet, and the error message for the wrong method is terrible, but all of that is going to be fixed. I’m still playing around.
Exciting stuff, I know, but I’m a big believer in recording things I find significant, just so other people can correct me, or learn from me if I managed to see something they didn’t.