Search code examples
jquerypythonpyramid

In pyramid how to return 400 response with json data?


I have the following jquery code:

$.ajax({
    type: 'POST',
    url: url,
    data: data,
    dataType: 'json',
    statusCode: {
        200: function (data, textStatus, jqXHR) {
                console.log(data);
            },
        201: function (data, textStatus, jqXHR) {
                 log(data);
            },
        400: function(data, textStatus, jqXHR) {
                log(data);
            },
    },
});

the 400 is used when the validation in backend (Pyramid) fails. Now from Pyramid how do I return HTTPBadRequest() response together with a json data that contains the errors of validation? I tried something like:

response = HTTPBadRequest(body=str(error_dict)))
response.content_type = 'application/json'
return response

But when I inspect in firebug it returns 400 (Bad Request) which is good but it never parses the json response from data.responseText above.


Solution

  • Well you should probably start off by serializing the error_dict using a json library.

    import json
    out = json.dumps(error_dict)
    

    Given that you don't give any context on how your view is setup, I can only show you how I would do it:

    @view_config(route_name='some_route', renderer='json')
    def myview(request):
        if #stuff fails to validate:
            error_dict = # the dict
            request.response.status = 400
            return {'errors': error_dict}
    
        return {
            # valid data
        }
    

    If you want to create the response yourself, then:

    response = HTTPBadRequest()
    response.body = json.dumps(error_dict)
    response.content_type = 'application/json'
    return response
    

    To debug the issue, stop going based off of whether jQuery works and look at the requests yourself to determine if Pyramid is operating correctly, or if it is something else that's going on.

    curl -i <url>
    

    Or even just open up the debugger in the browser to look at what is being returned in the response.