Question

I'm using tastypie with django. I have one line of code:

data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))

I use this code from the command line to send a post request to my webserver:

curl -X post -d "{ 'username' : 'user', 'password' : 'password' }" http://127.0.0.1:8000/api/employee/login/ --header "Content-Type:application/json"

When I run this, it results in a json response of

{"error": ""}

Looking at my server logs I see:

[15/Feb/2014 20:39:49] "post /api/user/login/ HTTP/1.1" 400 13

A log message logged immediately before the deserialize line will be logged successfully, but a log message logged immediately after the deserialize line will not be logged, so I am pretty sure the deserialize is wrong. Does anyone know what could be wrong or if I should consider something else as the problem?

Was it helpful?

Solution

Your JSON is not valid. Please check it here. The 400 (bad request) status should give you clue about that. It should be: {"username": "user", "password": "password"}. Here you have some solutions how to escape " char in CURL command. Tastypie unfortunately raises exception without message here but we can easily fix that for future to save time for other people which will use your API.

from tastypie.exceptions import BadRequest
from tastypie.serializers import Serializer
class VerboseSerializer(Serializer):
    """
    Gives message when loading JSON fails.
    """
    # Tastypie>=0.9.6,<=0.11.0
    def from_json(self, content):
        """
        Override method of `Serializer.from_json`. Adds exception message when loading JSON fails.
        """
        try:
            return json.loads(content)
        except ValueError as e:
            raise BadRequest(u"Incorrect JSON format: Reason: \"{}\" (See www.json.org for more info.)".format(e.message))

class MyResource(BaseModelResource):
    class Meta:
        serializer = VerboseSerializer(formats=['json'])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top