0

Let say I have data model called User and another Called UserType. And I can only delete an UserType if the type is not used in any User entry in the user table.

Now when I fetch the UserType details do I fetch the constraints also that this UserType is used in some user creation or not?

What would be a right approach according to REST best practice?

Mustafa Mamun
  • 2,591
  • 2
  • 14
  • 17

1 Answers1

1

If you are using a relational database I would let the database engine do this work for you with foreign key constraints. When trying to perform this operation the database engine would then throw an exception. In your code catch that exception, and return the appropriate response code (400, 405, 406, 409, 428, 500, 510 are all contenders) and error text specifying the reason (English - not the error message or stack trace - that's just leaking info to hackers) why it can't be deleted.

BlackSpy
  • 5,563
  • 5
  • 29
  • 38
  • I have the similar approach. But the idea is to be pro active and letting the user already know if the entity is delete able or not. My question is if it is a good idea to have this kind of information in the API response? It would be really nice if you can share some reference why it is a good idea to let the db to handle it – Mustafa Mamun Jun 23 '20 at 11:27
  • That all depends on the user interface, and you UX should guide you on that. If you want to grey out the button, then sure, include it as part of the payload. You can also use the concept of links, where dependent object urls are included in the payload. Then in your UI you only allow deletes if the list is empty, and if not, you have direct way to point the user to the offending resources. – BlackSpy Jun 23 '20 at 11:40
  • In previous projects, I've also implemented "/schema" extensions to all resources, which via reflection, send back the schema of an object so that the client can construct an edit form. There are no hard and fast rules on the structure of your payloads.Try to structure things so it's easy for your callers to understand and use. If you feel this extra info is littering your objects, you can use the same trick with the URL path to retrieve the info you need, but then its an extra request of course – BlackSpy Jun 23 '20 at 11:44
  • On the "Why lets the db handle it" : Its a built in feature of all relational databases. They were designed to handle these situations. Why write code for something you get for free? – BlackSpy Jun 23 '20 at 11:50