For requests not sent by HTML forms, does HTTP limit the Content-Type of a request to application/x-www-form-urlencoded for non-file uploads, or is that MIME type “right”/standard/semantically meaningful in any other way?
For example, PHP automatically parses the content into $_POST, which seems to indicate that x-www-form-urlencoded is expected by the server. On the other hand, I could use Ajax to send a JSON object in the HTTP request content and set the Content-Type to application/json. At least some server technologies (e.g. WSGI) would not try to parse that, and instead provide it in original form to the script.
What MIME type should I use in POST and PUT requests in a RESTful API to ensure compliance with all server implementations of HTTP? I’m disregarding such technologies as SOAP and JSON-RPC because they tunnel protocols through HTTP instead of using HTTP as intended.
Short Answer
You should specify whichever content type best describes the HTTP message entity body.
Long Answer
The server is not “expecting”
x-www-form-urlencoded. PHP — in an effort to make the lives of developers simpler — will parse the form-encoded entity body into the$_POSTsuperglobal if and only ifContent-Type: x-www-form-urlencodedAND the entity body is actually a urlencoded key-value string. A similar process is followed for messages arriving withContent-Type: multipart/form-datato generate the$_FILESarray. While helpful, these superglobals are unfortunately named and they obfuscate what’s really happening in terms of the actual HTTP transactions.You should specify whichever content type best describes the HTTP message entity body. Always adhere to the official HTTP specification — you can’t go wrong if you do that. From RFC 2616 Sec 7.2.1 (emphasis added):
Any mainstream server technology will adhere to these rules. Thoughtful web applications will not trust your
Content-Typeheader, because it may or may not be correct. The originator of the message is free to send a totally bogus value. Usually theContent-Typeheader is checked as a preliminary validation measure, but the content is further verified by parsing the actual data. For example, if you’re PUTing JSON data to a REST service, the endpoint might first check to make sure that you’ve sentContent-Type: application/json, but then actually parse the entity body of your message to ensure it really is valid JSON.