Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a REST API wrapper validate inputs before making a request?

Suppose that the server restricts a JSON field to an enumerated set of values.

e.g. a POST request to /user expects an object with a field called gender that should only be "male", "female" or "n/a".

Should a wrapper library make sure that the field is set correctly before making the request?

like image 337
Guybrush Threepwood Avatar asked Sep 17 '26 22:09

Guybrush Threepwood


2 Answers

Pro: Makes it possible for the client to quickly reject input that would otherwise require a roundtrip to the server. In some cases this would allow for a much better UX.

Con: You have to keep the libary in sync with the backend, otherwise you could reject some valid input.

With a decent type system you should encode this particular restriction in the library API anyway. I think usually people validate at least basic stuff on the client and let server do further validation, like things that can’t be verified on the client at all.

like image 176
zoul Avatar answered Sep 21 '26 02:09

zoul


This is a design choice - the enum type constraint should be documented in the public API of the server and it's part of its contract.

Clients are forced to obey the contract to make a successful request, but are not required to implement the validation logic. You can safely let the clients fail with "Bad Request" or other 4xx error.

Implementing the validation logic on both sides couples the client and the server - any changes to the validation logic should be implemented on both sides. If the validation logic is something closer to common sense (e.g. this field should not be empty) it can safely be implemented on both sides. If the validation logic is something more domain specific, I think it should be kept on the backend side only.

You have to think about the same trade-offs with a wrapping library (which can be looked at as a client of the server API). It depends on what the role of the wrapping library is - if the wrapping library should expose the full API contract of the server - than by all means the validation logic can be duplicated in the wrapping lib - other wise I would keep it to the backend.

like image 25
hovanessyan Avatar answered Sep 21 '26 00:09

hovanessyan