Reputation: 6783
If using JSON, we return JSON. If using XML, we return XML. Would it be acceptable to return form-encoded data for requests where we accept form-encoded data ("application/x-www-form-urlencoded")?
Also, in the case of errors, what do most implementations do? I see many different variations on the theme.
Upvotes: 0
Views: 92
Reputation: 99687
No, there's no reason to.
But a client can request a specific format with the Accept: header. If the server doesn't support the format, it should return 406 Not Acceptable. The server can just pick a default if there's no Accept: header at all, or the client used * as a fallback.
Upvotes: 3
Reputation: 106077
Returning form-encoded data, while not a terrible approach, is something I've never seen in the wild. Best, I think, to stick to more common formats. Most APIs choose a default format to send (usually XML or JSON) when none is specified by the request.
As for errors, the main principle of REST is using the methods HTTP already supplies, so firstly return the appropriate error status code (in the 400s and 500s) along with an error message in the response body.
There's no standard format for the body of an error response—it could be as simple as:
{ "error" : "Invalid articled ID" }
..or more involved, like Flickr's:
{ "stat" : "fail",
"code" : "97",
"message" : "Missing signature"
}
..and its XML equivalent:
<?xml version="1.0" encoding="utf-8" ?>
<rsp stat="fail">
<err code="97" msg="Missing signature" />
</rsp>
Obviously developers using your API will appreciate more verbose error messages. Mainly I think you should seek consistency in your API—if you have a parameter named Message
in one place don't have one named message
in another place.
As an aside, I've dealt with an actual third-party production API that not only made the above faux pas but returned results as pipe (|
) separated data enclosed in XML. Literal pipes in values were escaped by another pipe (||
). I'll leave the further complications we discovered up to your imagination. The moral, anyway, is to use structures and techniques that developers are already used to, and more than that be consistent in the choices you make.
Upvotes: 2