Reputation: 6793
I'm trying to wrap my head around how to design a RESTful API for creating object graphs. For example, think of an eCommerce API, where resources have the following relationships:
Order (the main object)
The Order resource usually makes sense along with it's associations. In isolation, it's just a dumb container with no business significance. However, each of the associated objects has a life of it's own and may need to be manipulated independently, eg. editing the shipping address of an order, changing the contact info against an order, removing a line-item from an order after it has been placed, etc.
There are two options for designing the API:
POST /orders
POST /orders/123/addresses
, PUT /orders/123/line-items/987
, etc.While the second option is simpler to implement at the server-side, it makes the client do extra work for 80% of the use-cases.
The first option has the following open questions:
Location
header can communicate only one URL, however the server would've potentially created multiple resources.What's the RESTful + pragmatic way of dealing with this?
Upvotes: 1
Views: 719
Reputation: 5480
How I handle this is the first way. You should not assume that a client will make all the requests it needs to. Create all the entities on the one request.
Depending on your use case you may also want to enforce an 'all-or-nothing' approach in creating the entities; ie, if something falls, everything rolls back. You can do this by using a transaction on your database (which you also can't do if everything is done through separate requests). Determining if this is the behavior you want is very specific to your situation. For instance, if you are creating an order statement you may which to employ this (you dont want to create an order that's missing items), however if you are uploading photos it may be fine.
For returning the links to the client, I always return a JSON object. You could easily populate this object with links to each of the resources created. This way the client can determine how to behave after a successful post.
Upvotes: 1
Reputation:
Both options can be implemented RESTful. You ask:
How does one communicate the URL for the newly created resource? The
Location
header can communicate only one URL, however the server would've potentially created multiple resources.
This would be done the same way you communicate links
s to other Resources in the GET
case. Use link
elements or what ever your method is to embed the URL of a Resource into a Representation.
Upvotes: 0