Should an API Validate Data Even When Another Service Already Does?
Asked by
MellowPine42
Our team is adding a new database field populated from a call to another service. Some teammates think we can trust that service to validate the value before returning it, while I think our API should still check for malformed, unexpected, or out-of-range data before storing it. How should validation responsibilities be divided between services, especially when the other service is internal? Am I being overly cautious by validating at our own boundary and protecting the database from bad data?
Answers
Persistent data deserves the strongest protection because repairing or migrating incorrect records is expensive. The service responsible for saving the value should enforce the guarantees required by its own database and users. That does not mean it must verify every fact in the worldโonly the constraints it actually owns.
Reply to this answer
If this is an internal service, you can avoid blindly duplicating every upstream rule, but you still should not assume its output is always perfect. Define the contract clearly, return useful errors when the contract is violated, and make the consumer resilient to new or unexpected values. Internal callers can still make mistakes or evolve independently.
Reply to this answer
It depends on what kind of validation you mean and which service owns the rule. The upstream service should usually handle business rules that belong to it, so duplicating those rules everywhere can create conflicts and maintenance problems. But your service should still enforce the guarantees it needs in order to functionโfor example, checking that a required identifier exists and has the expected format before storing the record.
Reply to this answer
A useful split is structural validation versus business validation. The API can check types, required fields, allowed enum values, lengths, ranges, and schema compliance. The service that owns the business rule can decide whether the value is semantically valid. Database constraints should provide another layer of protection for important invariants.
Reply to this answer
Validate data at every service boundary, particularly anything that will be persisted. The upstream service could have a bug, be compromised, return an unexpected value, or change its contract. Your checks do not need to duplicate every business rule, but they should protect your API and database from malformed, unsupported, or dangerous input.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions