mvera
mvera

Reputation: 946

HTTP REST how to create a new ressource when the final URL isn't known

I'm specifying a rest system with ressources that can be viewed, created, edited or deleted. I'm trying to respect rest and http methods semantics.

If a resource is identified by http://mydomain.org/oid_bar, I can manage it with these methods: - PUT creates or updates this resource - DELETE deletes this resource - GET returns this resource

But if you need to create a new resource for which you don't know yet the oid, how do you proceed ? This case is really common when you add an object to a database and the primary key is auto generated by the database. In my case my backend is a database.

I thought about a solution with a ressource http://mydomain.org/next_free_oid that returns the next free oid and increments its value. This ressource would only respond to a POST request. With the returned oid I can send a PUT request to the target URL.

Another solution would be to send a POST request to http://mydomain.org/. This request would create a resource with a generated oid and return the oid.

A variant of the previous solution is sending a POST request to http://mydomain.org/create_object

The third solution is my prefered one. But is it compliant with HTTP/REST to use an URL as a service ?

Every comment is welcome.

Regards, Mickaël

Upvotes: 2

Views: 81

Answers (2)

Nicholas Shanks
Nicholas Shanks

Reputation: 10981

Also, don't mint URIs with verbs in them like http://mydomain.org/create_object - your URI should represent a noun, such as an edit form, rather than a verb indicating "send data here to perform this action". For your verbs, choose the apropriate HTTP method. [RFC2616]

Upvotes: 0

beyond-code
beyond-code

Reputation: 1422

The convention is a POST to http://mydomain.org/

You should then return a status code 201 Created, and set the location header of the response to point to the newly created resource.

I am trying to find some links to back myself up...

EDIT: You can also opt to return the newly created resource if you wish, but setting the location header is still a good idea.

Try the following link, although it is hard to see the wood for the trees:

http://jcalcote.wordpress.com/2008/10/16/put-or-post-the-rest-of-the-story/

I personally reccomend getting the RESTful Web Services Cookbook as it explains things very simply and easily.

Upvotes: 3

Related Questions