What is the most appropriate HTTP status code to return if a required header is missing?
Asked Answered
B

2

64

I read What HTTP status response code should I use if the request is missing a required parameter? but it did not specifically ask about headers and there didn't seem to be a consensus.

The context of this question assumes successful authentication. I'm currently favoring either a 400 (though that doesn't feel right because this isn't really a case of "malformed syntax") or 403. Given 403's description:

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity.

This makes the most sense to me.

Can someone please enlighten me? Thanks.

Bobine answered 14/5, 2012 at 2:26 Comment(0)
C
86

400 Bad Request

It's a user error in the request. Unlike with a 403, the client should be allowed to repeat their request, but only after modification:

10.4.1 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.

Edit

As Mark Reed points out in the comments, a 403 says, "There is nothing wrong with what you sent me. You have proper authorization and the syntax was valid. I just don't want to do what you ask."

The part that you have in bold simply says, if the server so chooses, it can tell the client exactly why it doesn't want to fulfill the request.

Comptometer answered 14/5, 2012 at 2:31 Comment(3)
Definitely 400. If there's anything wrong with the request that doesn't depend upon the server state, it's a 400. If the only thing wrong is on the server side ("That's a perfectly cromulent request as far as you know, but I'm not in the mood"), then you use 403.Cutlery
What about 412 (precondition failed)?Natation
AFAIK HTTP 412 Precondition Failed is reserved to be used with If-Match and If-Unmodified-Since headers only.Ziegfeld
T
0

422 Unprocessable Content could be suitable, according to this documentation.

There are two stages for the server to ingest a request: receival and process, and 422 should be thrown whenever the request can be received (meaning the type and syntax can be understood) by the server but cannot be processed. So if the missing header item can still be received by the server but fails the processing logic, it sounds pretty like a 422 error.

Toggery answered 21/6, 2024 at 15:28 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.