Search code examples
resthttpresponseasp.net-core-webapihttp-response-codeshttpresponsemessage

What HTTP status code should a Web API return after successful completion, if it performed both UPDATES and INSERTS?


This is a follow up question on my earlier post at PUT or POST HTTP verb when calling API endpoint which performs both UPDATE and INSERT?

I have a RESTful Web API (written in ASP .Net Core 2.1) which receives a "change-log" from the consuming client app. This is a JSON class containing all the modifications to the database that were performed on the client app while it was working in offline mode. Once the client app goes online, it synchronizes its database with an online/live database by sending the API all the changes that have happened since the last sync. So it sends the API a change-set/change-log with a bunch of UPDATE, INSERT and DELETE lists for the various tables/objects.

On the API side, I don't actually delete anything from the live database - I simply flag things as deleted (so I set a boolean field to true, i.e. deleted = true). So technically, the API only performs INSERTS and UPDATES on the database

What status code should the action method of the API return upon successful completion? Since it is doing a combination of both INSERTS and UPDATES, should it return a 201 Created? Or simply a 200 OK? Or a 200 OK if only updates were performed, else a 201 if any inserts were performed? Also, in the response body, since I'm not actually planning on returning any ID's or objects in the body (since multiple objects wouldve been updated and inserted), I would like to return just plain text saying how many objects were updated, how many were inserted and how many were flagged as deleted. Is this possible, or even a good idea?

Thanks


Solution

  • To me, this doesn't sound like a REST api. If you are updating and creating multiple resources at once via one endpoint, it kind of goes against REST principles.

    Given that this is more of a RPC-like call, I would return 200 OK simply indicating that the operation was successful.

    However, there is a way to turn this into something that's more REST-like.

    If you have multiple resources, the underlying data in those resources could be combined and represented in a single resource, a sort of 'collection' resource.

    Lets say that that resource is hosted at /clientstate/<client-id>. Doing a GET returns the entire 'clientstate' resource.

    Then to update this resource, you would use PUT to replace the entire client state. To the client it's completely irrelevant that there's multiple database records tied to a single resource.

    If you use PUT to replace this entire client-state, then the appropriate response code should still be 200 OK. Or perhaps 204 No Content if you're not returning anything interesting afterwards.

    I'd advise against re-purposing 207 Multi-Status.