Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest API UPDATE/DELETE - check if resource exists or not?

Tags:

rest

This is basically best practice question. In my Rest API (that I am currently working on) I have routes matching PUT and DELETE requests on URLs like /resources/{resourceID}. Behind the API lies SQL DB.

In general, executing a DELETE or UPDATE query on non-existing resource ID in SQL databases gives no error, only the affectedRows returns 0.

Now I have a question on how to perform such request properly:

  1. check if the resource with given ID exists prior to UPDATE or DELETE (which involves additional SQL query)
  2. trigger the UPDATE / DELETE query without checking for existence and inspect the result of SQL query and return HTTP 404 in case when affectedRows == 0?

I personally prefer the later one. But I can think of other DBMS (not SQL or not relational) where performing INSERT, UPDATE or DELETE queries may not return any information about affected rows. How to proceed in such cases?

like image 792
shadyyx Avatar asked Sep 01 '25 17:09

shadyyx


1 Answers

Once you are performing DELETE and UPDATE operations using the resource ID, I cannot see any problems on checking the number of affected rows. This should be enough to check whether your resource exists or not.

Basically:

  • For databases which the affected rows can be checked, just perform a DELETE or an UPDATE.
  • For databases which this feature is not available, perform a query first.
like image 117
cassiomolin Avatar answered Sep 04 '25 08:09

cassiomolin