What's the RESTful way to create an object? Should I use POST on the /resources/ URI and return the URI to the newly created resource in the response or should I use PUT on the /resources/id/ URI? A GET request for /resources/id/ would surely return a 404 but should PUT return a 404 as well? Should both methods be used to create a new object?
Generally, you will use either or both depending on whether or not you want the client (and therefore the user) to define the URI or not. If the client POSTs to resources/
then the server gets to determine the URI for the resource. If the client PUTs to resources/{id}/
then the client is determining the URI for the resource.
One exception is if creation involves links, states, and other items that are not then properly considered part of the resource--you generally cannot PUT these extra "constructor args" if you will, since they are not part of the resource state. Instead, you must POST in that case.
Even if you use POST for creation, you still might then want to expose PUT for updates. It depends on the resource.
If you don't allow a PUT to create then yes, you should return 404 in that situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With