Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use a POST request on /resources/ or PUT request on /resources/id/ to create a new object?

Tags:

rest

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?

like image 993
the_drow Avatar asked Jan 17 '23 22:01

the_drow


1 Answers

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.

like image 196
fumanchu Avatar answered Jan 31 '23 09:01

fumanchu