Sahil Sharma
Sahil Sharma

Reputation: 4247

Can restful POST api send back two different resources in the API response based on request body parameter?

We have a website to connect buyer and seller of goods.

We are designing POST API to capture interest of buyers on any seller product. The API Uri and request body looks like:

/api/lead/
{
   "name":"xyz",
   "mobile": "00984343",
   "stockid":4
}

The API is POST since we will save this information in database.

Currently, if "stockid" is stock belonging to our premium customer, the API sends back seller details in API response body:

{
  "sellername":"abc",
  "sellermobile":"75654647",
  "selleraddress": "faje street, curl"
}

If "stockid" is stock belonging to our normal customer, the API sends back complete details of that product in API response body (and DO NOT send back seller details)

{
  "description": "good 2nd hand mobile",
  "purchasedate": "24 july,2017",
  "purchaseprice": "10000"
}

The same POST API is sending back 2 different types of resources (one is seller details, other is stock details) based on the stock id.

Is it restful to design API this way i.e. POST API sending back multiple types of responses based on some request body parameter?

Upvotes: 3

Views: 1899

Answers (1)

James Cube
James Cube

Reputation: 421

This practice looks questionable. Personally I would not do that.

Suggestion 1: return details of product for normal customer, and details of product plus seller details for premium one, as form of enrichment of response. With that both responses are mostly consistent and you still have functionality you want.

EDIT: added more suggestions I thought of.

Suggestion 2: since those responses are basically different, maybe they should be returned by different resources. In that case, don't return data during POST, just use id to make calls to something like api/seller/{stockid} and api/product/{stockid} which would return responses or No content if id is invalid for specific resource. Downside, you need to make many calls and it complicates architecture.

Suggestion 3: To avoid totally different response objects, which is confusing and makes harder for the client to map them, use some wrapper object that provides some "type" property and your object inside. Something like :

{
  "type" : "premium",
  "data" : {
     "sellername":"abc",
     "sellermobile":"75654647",
     "selleraddress": "faje street, curl"
  }
}

Not perfect, but in my opinion better than two totally different responses.

Upvotes: 1

Related Questions