I want to know how to design a RESTFUL api for creating a resource and its related resources at once.
For example, I want to create an order which contains a list of items using my RESTFUL API, for example:
{
order_id:1,
description: "XXX",
items: [
{item_id:1, price:30, ...},
{item_id:2, price:40, ...}
]
}
One way is giving two api
- post:
api/orders=> create a new order and return the order id - post:
api/orders/id/items=> create related items using the order_id
However, the order and items should be created together. So if the second api failed, it will create an order without any item inside and it is the situation I don't want to see. Actually, I want the backend server to do a transaction and create the order and items at once, it should be succeeded or failed together.
So, is it a good way to put the items in the body of request, and post only once to api/orders ? Or is there other better design for this situation?
Thank you!