Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use the same endpoint for "multiple" and "single" objects?

I have a .NET Core 5 project (Rest API) that includes a controller (TestController) with an endpoint (AddOrUpdate). The signature of the endpoint looks like this:

[HttpPost, HttpPut]
public virtual IActionResult AddOrUpdate(params TDatabaseModel[] entities).

By itself that one works, but now I always have to specify a list of TDatabaseModel’s in the JSON. Now I wanted to create another endpoint, which accepts only one TDatabaseModel, to prevent the creation of a list. The signature looks like this:

[HttpPost, HttpPut]
public virtual IActionResult AddOrUpdate(TDatabaseModel entity)

The problem now is that I get an exception as soon as I specify a single object (not a list) in the JSON body. The exception refers to the fact that the endpoints are "ambigous". I have also tried to make a list of TDatabaseModel’s out of the endpoint with "params", but even then it remains ambiguous.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My question: is there a way to pass both a single object and a list of objects WITHOUT using different endpoint routes? So I don’t want to end up using different routes (HttpPost:{{URL}}/single && HttpPost:{{URL}}/multiple). Is there any way to do that?

>Solution :

No, there is no way, either use always an array or use two endpoints.

Unfortunately, REST does not really have a representation for a batch operation (such as creating/updating multiple entities at once), so which option to go with is entirely opinionated.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading