php_nub_qq
php_nub_qq

Reputation: 16015

Correct response code for an invalid POST request

I just noticed something that is probably not correct in my application. I have, at many points, post forms that require certain input parameters in order to proceed with the insertion of the data. For example in order to add a user to you contacts list, first the user has to exist, and I do this quite simply

$db = \Database::connection();
$user = new \Models\User();
$user->getById($data['id'], $db);

if ($user->id) {
    if (\Models\User::auth()->addContact($user, $db)) {
        return \Response::json(['text' => 'Contact added']);
    } else {
        throw new \Exception('User not found', 404);
    }
}

Ignoring all other possibilities for errors and just focusing on the user not found one, I just noticed that I am returning a 404 code, which I am having my doubts about. At the time I was writing this code I have most certainly been provoked by the not found part in the message and automatically assumed that it is a 404 error. However now when I think about it a 404 error is actually "Resource not found", how can a resource be not found when I'm not asking for a resource, is my logic.

Is it correct to return a 404 error to a POST request or I should switch to 400?

Upvotes: 0

Views: 2734

Answers (1)

justAnotherUser
justAnotherUser

Reputation: 181

The resource being updated is a users contact list - something like User/[userid]/ContactList ? This resource is being identified correctly but the User being added to the contact list is invalid.

In the http rfc 404 is "The server has not found anything matching the Request-URI..." I would find it surprising behavior to get this error on the basis that the resource to be updated has been found. If you were to return a 404 then it should include a message body indicating exactly which resource wasn't found.

A 400 means "the request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications". I'd argue that the syntax is correct, so a 500 (internal server error) coupled with an explanation in the response body is more appropriate.

Upvotes: 1

Related Questions