Search code examples
apivalidationresponse

Which one should validate the response data? Sender(Backend) or Receiver(Client)?


// Data flow
CMS -> DB -> REST API -> Client

We are currently building a kiosk system. CMS sets the product's data, and Clients request the data from the REST API.

While CMS and DB should validate all data before INSERT, UPDATE, or DELETE, there might be things we could miss. So it would be safe to think that some data can go wrong (for example, min_quantity > max_quantity).

From REST API -> Client part, which one should deal with the bad data from DB? The team decided that REST API should respond as is, without any validation or sanitization, otherwise, it would be hard to debug. And Client should deal with the wrong data somehow. I'm worried about this decision, but I'm not sure why.


Solution

  • If the data has made it into your database the assumption would be that it was validated on its way in, ensuring that what you then return from the database is clean.

    When you make a get request to an API, the purpose of the endpoint is to get the requested data and return it to the caller, this should be its only concern, if the data it gives is wrong for the client it is for the client to decide why it is wrong and handle it.

    When your pipeline runs in the other direction (client -> API), you can perform multiple steps of validation in order to ensure data cleanliness. You can validate the front end inputs on submission, and then as the request is received by the API you can parse the data to ensure it conforms to your data standards. And it is likely your database design will give some inherent constraints also.