Thinking in a RESTful way, is it correct to use POST to create in a single call a resource and its sub-resource?
In my application I have the resource /notices/{notice}
and sub-resource /notices/{notice}/photos/{photo}
. A {photo}
can't exists without a {notice}
, but a {notice}
doesn't have necessarily photos. Normally, I have to do first a POST to create a notice, then another POST to add a photo.
Now I want to allow the creation of a notice with a photo directly attached, enabling the creation of /notices/{notice}
and /notices/{notice}/photos/{photo}
with a single POST request to /notices/{notice}/photos/{photo}, with a multipart content describing both the resources (JSON for notice, binary for the photo). I think I will return the Location header only for the sub-resource.
Essentially, I want this to prevent Android clients to send two POST request to the server to upload a notice with a photo.
Is this correct? Or does it infringe REST principles? Should I consider to keep them separate and make two different requests? Or is it wrong to consider photos a separate entity from the notice? Should I keep only /notices/{notice}
as resource, using PUT to add photos?
Which is the best solution?
Although its essential in many cases, multiple edits/creates are not formally addressed by the RESTful architecture style.
Problem starts when you need to report failures on part of the collection, and the problem is worsen when they failures have different cause.
An it will effect choosing the right Hypermedia controls which are essential for the client to find a way forward in the given transaction/conversation.
so my suggestion is to have a nested cycle or POST requests rather than a sing POST to create nested Resources , so that it'd be easier and clearer to address each Resource state change.
Yes, there is nothing wrong with creating sub-resources at the same time you create the parent resource. It would even be OK to use
PUT
instead ofPOST
to do this, as everything under the parent URL is part of/belongs to the resource you are uploading.EDIT:
This I disagree with. I suggest POSTing to the collection resource's URL,
/notices
. You provide the notice and its photos as a single representation (request body). The back end will then create resources for both the notice and any constituent photographs.