Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a REST API method fails, should I return a 200, 400, or 500 HTTP status message?

When a user submits invalid data to my API (usually via Javascript + JSON), I am wondering which HTTP response code I should reply with.

Should I return a HTTP 200 response with the errors - or should my server respond with a 400 or 500 error since the request actually failed my validation because of some bad data?

It seems like a 400 error is the way to go since "The 4xx class of status code is intended for cases in which the client seems to have erred" - wikipedia

However, one thing to keep in mind is that most people use a framework like jQuery which requires you to specify an alternate callback when AJAX requests respond with any status code other than a 200.

like image 600
Xeoncross Avatar asked Feb 19 '12 00:02

Xeoncross


1 Answers

400 Bad Request The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

use statusCode in jquery ajax calling:

<html>
<head>
<title>jquery testing</title>
<script type="text/javascript" src="jquery-1.6.2.min.js"/>"></script>
<script language="javascript">
$(document).ready(
    function(){
        $('#linkClick').click(
            function(){
                    $.ajax({
                        url: 'a.html',
                        data: {},
                        type: 'get',
                        dataType: 'json',
                        statusCode: {
                            404:function() { alert("404"); },
                            200:function() { alert("200"); },
                            201:function() { alert("201"); },
                            202:function() { alert("202"); }
                        },
                        success: function(data) {
                            alert( "Status: " + data);
                        }
                    });
                }); 
        }
        );
</script>
</head>
<body>
<a href="#" id="linkClick">click</a>
</body>
</html>
like image 144
horaceman Avatar answered Oct 23 '22 23:10

horaceman