Home > Enterprise >  Correct http status for invalid config in request body?
Correct http status for invalid config in request body?

Time:03-03

I am having trouble picking the correct HTTP Status for when an API is receives an attribute that maps additional data in the system but that additional data is not found. I was initially thinking 422 since it describes the use case but sounds like it is reserved for WebDAV. Then I was thinking maybe a 404 but I mentally associate that to a URL being incorrect. The other option was using error code 200 and have a failure message.

Example: the key nvdaKey is not a key configuration that the system knows about.

POST: pgpTool.com/encrypt

{
  "message": "my secret message",
  "keyConfigName": "nvdaKey"
}

CodePudding user response:

The IANA HTTP Status Code Registry currently lists HTTP Semantics as the authoritative reference for status code 422

The 422 (Unprocessable Content) status code indicates that the server understands the content type of the request content (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request content is correct, but was unable to process the contained instructions.

So if you think that's a winner, go for it.

403 Forbidden is also an option ("I understood your request, but I refuse to fulfill it").

Status codes are meta data in the transfer of documents over a network domain; the intended audience is general purpose HTTP components (browsers, caches, proxies....) Clients are supposed to be getting the semantics of the message from the body (in just the same way we expect humans reading the web to learn of errors by reading the returned web page, rather than by reading HTTP headers).

So apart from some purely mechanical concerns (caching, interpretation of headers) it is not necessarily critical that you produce precisely the right status code, so long as you get the class (Client Error / 4xx) correct.

Do note that a client that doesn't recognize a 422 is expected to treat the response as though it were a 400.

  • Related