¿Enviar respuesta REST en texto sin formato o JSON?

When creating a REST API, if I return data in JSON format for GET requests, is it a good practice to also send responses for POST, PUT, DELETE, and error messages in JSON too or plain text will suffice?

Por ejemplo:

For POST request where I need to return the new ID of the newly added record (i.e. just the new auto increment value in database), should the response still be in JSON or just plain text like "1" or "2" for example.

Same goes for PUT or DELETE request where I need to say "OK" or "Accepted", as well error messages like "Bad Request", "Not Found", etc.

Plain text or JSON?

preguntado el 31 de julio de 12 a las 14:07

I'd say JSON just to get things consistent, even if you return simple values now, that may change. -

3 Respuestas

Use the client-provided Accept encabezamiento to let the client control what content type they want. If no header is provided, then use a sensible default and siempre Incluir un Content-Type encabezamiento in the response. See the Content Negotiation section of RFC2616 para más información.

Respondido 07 Oct 21, 06:10

The choices are still up to me right? (e.g., I only want JSON or plain text, no XML) or XML is also required? - IMB

Nada es realmente es requerida. The client can ask for Accept: application/foo and you can respond with Content-Type: text/json. La Accept header is a preference from the view of the client and the Content-Type header is an assertion that the enclosed entity body meets the requirements of a specific MIME type. - D.Shawley

Theoretically, returning just "1" is valid JSON. It's just not a array or associative mapping.

For OK and Accepted, you can just use the HTTP status codes for those. No body is really necessary.

Respondido 31 Jul 12, 14:07

Según RFC4627, JSON-Text is defined as either an array or an object. - D.Shawley

It depends entirely on the ability the client has.

Of course, you don't actually have to choose one or the other: you can use content-type negotiation to return a different representation depending on the user-agent's acceptance list.

Respondido 31 Jul 12, 14:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.