Home > Software engineering >  How do I create multiple associated records with a single POST request?
How do I create multiple associated records with a single POST request?

Time:07-12

The resource here is a Log type that will create 5 different records, one for weather, location etc... they will all share associations.

It's my understanding that convention would be to create a post for each resource but if these resources require the foreign key of other records I can't figure out how I would keep track of all the id's of the records created relating to that log.

Right now I'm sending all the data needed to create all the resources in a single request and if one errors out none would be created as I would use a transaction. Is that convention?

CodePudding user response:

convention would be to create a post for each resource

This convention works great when you have a simple model when one object is affected by one user action. That model is quite common and implemented in every REST book/article.

Reality is more complicated, and your question is a great example of that. Implementing PUBLIC API per table is known and unfortunately widely spread antipattern:

https://martinfowler.com/bliki/AnemicDomainModel.html

Rule of thumb, build your solution around your business problem, not around a technical framework or pattern.

Right now I'm sending all the data needed to create all the resources in a single request

That sounds like a great solution. One business action -> one API call -> one DB transaction. It is nice and simple. Do not make it more complicated if it is not necessary.

  • Related