Reputation: 1360
I want to implement a rest service that takes in an object and returns if the object is eligible to be processed with certain parameters. The problem is that depending on whether the object is eligible or not the structure of the response is very different. As an example in case the object should be processed it is associated with a processing type and priority. When it is not eligible the reason for this is returned. Which is the cleanest way of returning different structures for the same request. There are three options I could think of but feel free to add additional options.
Option A:
Return data as envelope containing with field that is structured
{
"eligible": bool,
"data": {
// Data depending on whether elbile or not
}
}
Option B:
Use different HTTP status code and structure json accordingly. This is somehow unclean, since it is not really an error in the request but a valid response.
Option C:
Use different fields for the data send in case of eligible or not and let one field be null.
{
"eligible": bool,
"dataEligible": {
"processingType": "",
"priority": 0
}
"dataNonEligible": {
"reason": "",
}
}
Upvotes: 3
Views: 497
Reputation: 23029
I think this would be good use-case for 422 Status Code. It is not official ISO yet, but a lot companies (i.e. Twitter) is using it.
Basically it is what happens for you - the resource could not be processed, altough server understand the request and it is correct syntax.
The option C also look reasonable, therefore use the one which is the most appropriate for your needs. I would not recommend A, as different format for same request is huge problem for consumers with static-typed languages (i.e. Java)
Upvotes: 1