415 Unsupported Media Type

  • You are here: Free PHP » Uncategorized » 415 Unsupported Media Type

When a server receives a request with a body it doesn’t understand, it should return 415 Unsupported Media Type. Most commonly this is a good response for for example a POST or PUT request with an unknown Content-Type header.

The specification says that aside from inspecting the Content-Type header, the server may also return this after inspecting the body.

What this means is that if the client sent a request with a supported Content-Type, it may still return 415 if the contents of the request body were not supported by the server.

For example, a server might support specific JSON bodies, but the contents of the JSON payload didn’t validate, perhaps because it was missing a required property.

However, for the latter case it might be better to use 422 Unprocessable Entity. The description in the standards for 422 is slightly contradicting with the one for 415, but 422 seems to be more specifically for cases where the Content-Type was correct, the request was parsable, but semantically incorrect.

I would suggest the following approach to deciding the right status code:

  • If the Content-Type was not supported, use 415.
  • Else: If the request was not parsable (broken JSON, XML), use 400 Bad Request.
  • Else: If the request was parsable but the specific contents of the payload were wrong (due to validation or otherwise), use 422

Example

POST /new-article HTTP/1.1
Content-Type: text/html

<h1>Another day, another blog post</h1>
HTTP/1.1 415 Unsupported Media Type
Content-Type: application/json

{"error": "This endpoint only supports text/markdown for new articles"}

References

Powered by Gewgley