In REST, Is Including discriminator inside JSON payload preferred to having separate endpoints

by dade   Last Updated January 26, 2018 17:05 PM

So imagine, I have an endpoint where subscription payment to a magazine can be made.

There could be different flavors of subscription. eg, weekly, fortnight, yearly, 5 years etc.

For each subscription, the JSON request to the subscription endpoint varies in slightly different ways. For example, perhaps with the 5 years subscription, you might want to ask for the residential address, but for the weekly subscription, perhaps you do not care. Thus validation (and also business logic) differs slightly based on the subscription type.

The question is, which is the preferred way to model the endpoints:

  1. Have one single endpoint: /subscription in the JSON that is sent, you have a discriminator property. That is: { name: "Joe", Age: 66, subscription_type: "weekly | monthly | fortnight | yearly | etc" } So that in the implementation of /subscription you have code that performs different validation to the JSON request and executes different business logic depending on the value of the subscription_type
  2. Have separate endpoints for the different subscription types. For example: /subscription/weekly, subscription/monthly etc and have the implementation of each of these endpoints to only care about the validation and business logic specific to their subscription type.

Any other option possible apart from these two I mentioned? Is there any best case practice for dealing with this kind of scenario?

Tags : rest


Answers 1


The second model, no doubt.

Is almost always a good idea to separate endpoints to be consistent on the entry values.

Have a endpoint that can accept different attributes if some another attribute was sent together is a bad idea, because it's:

  • Harder to understand
  • Harder to create a good documentation
  • Harder to maintain
  • Harder to create different versions of the resource (if it's your case).

Bonus

If you can save a subscription without the type information, I have a suggestion: think about sent the common information in a separated POST to /subscription/ and sent the specific information for each type in POST to each type, like: /subscription/{id}/weekly/, /subscription/{id}/monthly/, etc.

Dherik
Dherik
January 26, 2018 16:52 PM

Related Questions



Google CustomSearch API Image Search Not Working

Updated May 30, 2015 04:02 AM


RESTful way of requesting server generated resource

Updated March 31, 2016 08:02 AM