My REST API returns JSON.
I'm currently returning text/plain as the MIME type, but it feels funny. Should I be returning application/x-javascript
or some other type?
The second question is with regard to the HTTP status code for error conditions. If my REST API is returning an error state, I am returning as JSON
{ result: "fail", errorcode: 1024, errormesg: "That sucked. Try again!" }
Should the HTTP status code remain at 200 OK
?
text/plain was typically used for JSON, but according to IANA, the official MIME type for JSON is application/json .
A media type (also known as a Multipurpose Internet Mail Extensions or MIME type) indicates the nature and format of a document, file, or assortment of bytes. MIME types are defined and standardized in IETF's RFC 6838.
REST APIs should accept JSON for request payload and also send responses to JSON. JSON is the standard for transferring data. Almost every networked technology can use it: JavaScript has built-in methods to encode and decode JSON either through the Fetch API or another HTTP client.
The REST architecture allows API providers to deliver data in multiple formats such as plain text, HTML, XML, YAML, and JSON, which is one of its most loved features.
The JSON spec suggests application/json
, and that seems to be supported by the IETF and IANA registry.
On the second question, I think if the message handling fails in some way you should return a structured and standard error response as a JSON message; only if there is a failure to deliver the message to the backend handler for some reason should you consider an HTTP error code.
Update 2014-06-27: The days where clients (browsers) only worked with a 200 response are long past and the prevailing advice for RESTful APIs is to use HTTP response codes appropriate for the response, 2xx for successful responses (e.g. 201 Created for PUT; 204 No Content for DELETE) and 4xx and 5xx for all error conditions, including those from the API itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With