4

Synchronizing data once user gets online involves both Insert and Update (Upsert) and I'm sending both kinds of records in a single request (array) and then server iterates through records to determine insert or update.

My question is whether to use POST or PUT?

Also how a response from the server (JSON) should like in it's body? the data sent is an array, for example

{
  "ids" : "15,16,17",
  "success" : true
}

Edit:

And what should be the response code, it has both create and update operations:

200 OK
201 Created
user2727195
  • 7,122
  • 17
  • 70
  • 118

1 Answers1

8

REST is not CRUD. Mapping HTTP methods to CRUD operations is a convention introduced by some frameworks, but it has nothing to do with REST. Read this answer for some clarification on that.

A PUT is a complete replacement that ignores the current state of the resource. Think of the mv command in a shell. If there's nothing on the destination, it creates it. If there's something, it replaces completely, ignoring whatever is in there. That's how a PUT should work. Ideally, your application should have an uniform implementation of PUT that works in the exact same way with any URI that supports the method..

A POST submits the payload to be processed by the target resource under predefined rules. This means you can use POST for any operation that isn't already standardized by the HTTP protocol.

In your case, it's clearly not a complete replacement, so it's not a case for PUT. Use POST.

Community
  • 1
  • 1
Pedro Werneck
  • 40,902
  • 7
  • 64
  • 85
  • Great explanation and the answer link, finally what status code (200, 201) makes sense for sync operation – user2727195 Apr 22 '15 at 16:13
  • finally just to clear PUT vs. PATCH, suppose a table student (id, name), if I update the name of the student where id = 1, it's a PATCH. If I completely replace the whole row (1, 'abc',) to (2, 'xyz') it's a PUT operation. right? – user2727195 Apr 22 '15 at 16:17
  • If a new resource is created, use 201. Regarding the methods, you are correct, but keep in mind that ideally your application should support both methods and it's up to the clients to decide what to use, PUT or PATCH. – Pedro Werneck Apr 22 '15 at 16:40
  • ok, regarding status code 201, it's also possible that sent records ended up in update operation for all, or it's also quite possible that both insert and update happens or only insert happens. 201 may not always be the case, and I expect server end not to track as they'd be using UPSERT SQL statements. Do you suggest 200 OK in such case? – user2727195 Apr 22 '15 at 16:55
  • 1
    If a resource is created, use 201, if not, use 200. Response code should not be fixed depending on method or resource. It depends on the actual results. – Pedro Werneck Apr 22 '15 at 17:10