Home > Blockchain >  How to update multiple different entities in one REST API request?
How to update multiple different entities in one REST API request?

Time:04-16

I have following entities: Game, Team, Player, Contract, with the following relationships: One Team, has many Players, which have many Contracts. Also Team has many Games. API already handles standard CRUD operations for each entity alone, but I'm planning to create one request to insert/update whole tree. Here's how:

It would be insert/update Game and in the json body (beside the game info) I would attach two corresponding teams, along with their players and players contracts. All in one json. In the request I will check with the database, and potentially insert/update sub-entities (for example if the team doesn't exists I will insert it, otherwise update it).

My questions:

  1. Is it a good practice to do bulk request on multiple different entities?
  2. What should be the method type? POST or PUT?
  3. What should be return status? (I thought since it's a transaction, it's either all good or fail, thus 201 would be appropriate. I'm only not sure, because there could be some updates along the way, so I wanted to ask)

Thanks!

PS. Optional to read: Why? It's huge improvement from the client perspective, because there are a lot of foreign keys (specially if the tree gets bigger, with statistics etc), and API can do it all in one transaction. For example: When adding new game with new team, with new players and new contracts, to be able to insert game, I need FK of the team, contracts need FKs of the player and the team. So doing it one by one, I would need to send POST then wait for returned FK, so that I can send more request. If something fails along the way, there is an issue reverting all the changes.

CodePudding user response:

There is no problem doing that, actually is pretty normal.

1 - If it is part of your business rules, go for it, there is nothing saying that it is wrong, actually is a good practice to do everything you need inside a single request (queue things, save a bunch of entities, whatever), this avoids business rules leaking to the front-end and additional work like perform fallbacks if anything goes wrong at the previous request.

2 - Depends, if the main action is to add something, then POST, else PUT fits nicelly

3 - If you are creating a resource 201 is the one to go, if you are updating something, 204-No Content (the server processed the request but there is nothing to return to you)

  • Related