Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What MIME type if JSON is being returned by a REST API?

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?

like image 229
ashitaka Avatar asked Jan 01 '09 03:01

ashitaka


People also ask

Which is the MIME type for JSON?

text/plain was typically used for JSON, but according to IANA, the official MIME type for JSON is application/json .

What is MIME type in REST API?

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.

Does REST API return JSON?

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.

Is JSON API a REST API?

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.


1 Answers

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.

like image 149
Lawrence Dol Avatar answered Oct 17 '22 06:10

Lawrence Dol