Vijay
Vijay

Reputation: 363

URI Convention for Insert and Update - WCF Rest API

I have Users collection with User's. User - Id, FName, LName.

For insert, I pass User instance with Id, FName, LName. The service inserts the User if it's not present.

For update, I again pass User instance with all parameters. The service updates FName and LName for the User with the given Id.

I want to have insert and update as 2 separate methods in the service.

I can't have same URI's for both methods. Something like below:

    [WebInvoke(UriTemplate = "Users", Method = "PUT")]
    void  UpdateUser(User instance);

    [WebInvoke(UriTemplate = "Users", Method = "PUT")]
    void  AddUser(User instance);

Which is the best way to acheive this?

I don't agree with one post saying update URI to have something like :

    [WebInvoke(UriTemplate = "Users/{userId}", Method = "PUT")]
    void  UpdateUser(string userId, User instance);

Because, user id is already present in the Userinstance.

Though I agree that PUT method can perform insert and update. For some reason I need to keep them separate.

Upvotes: 1

Views: 3211

Answers (2)

WestDiscGolf
WestDiscGolf

Reputation: 4108

You can look at it a couple of ways

  • PUT - for updates, but if provided id doesn't exist then insert
  • POST - for creates, insert as many times as it likes even if you pass the same data in multiple times as it ignores the ids

So I'd say:

  • Add user : /Users with POST (however you could do this with a PUT instead theoretically).
  • Update user : /Users/{userId} with PUT

As it would then be to get the user info, /Users/{userId} with GET ... or to delete the user, /Users/{userId} with Delete.

Not sure if this helps or not, if not then let me know and I'll try again :-)

Upvotes: 1

Stever B
Stever B

Reputation: 4117

PUT, being an idempotent operation should create a new resource at the URL you are PUTting to or completely replace the existing resource (PUT this resource here). If you perform the same PUT to the same URL multiple times you will still end up with the same resource.

POST is not necessarily idempotent, because you are changing an existing resource. If your POST is doing something like adding items to an order and you POST the same data to the same url mutliple times you could end up with an order containing multiples of the same item.

Short answer, make your insert a PUT operation and the update a POST.

I think this SO Answer does a really good job of explaining it.

Upvotes: 3

Related Questions