0

I am building an open source library to interact with a public API. The API validates all data passed to it and on failure properly returns a non-200 status code and usually a failure message causing my library to throw an Exception.

Some of my methods do check for required parameters, but mostly I have decided not to validate the data before passing it to the API.

Should a library for an API also be validating the data? If so, to what extent? Should it attempt to fully validate all data or just verify that required parameters are present/not empty?

1 Answer 1

1

The rule has two parts: on input, be an accepting loving grandmother: take what the caller gives you and don't be a stickler about the interface convention in places where it makes little difference; or where you can supply reasonable defaults. On output, follow the convention to the letter: be a strict pedant, a martinet.

So, in my opinion, the answer is yes, you should check your caller's input and give the API the best data you can. But this does not necessarily mean you should duplicate validations that the API is going to do anyway.

You have to use your head and think about what makes sense.

5
  • I’m confused because your answer seems to say validate the caller’s input, but don’t duplicate the API’s validation. The API validates all input so that would mean I should not validate the caller’s input in the library.
    – J Cobb
    Commented Sep 1, 2011 at 23:16
  • What are some of the things that the API is expecting? Commented Sep 2, 2011 at 1:57
  • The API allows you to create records such as clients, addresses, phone numbers, email addresses and to also update and retrieve them. All the create and update actions validate the data input, and the validations can vary based upon what is submitted, which is why I’m leaning towards not attempting to reproduce the API’s validations.
    – J Cobb
    Commented Sep 3, 2011 at 23:17
  • 1
    Right. If the API is checking for, say, a correctly-formatted email address, there's no point in your doing the same. But you might want to first check that your caller does actually give you all the required items and complain if not. Or check that no pointer is NULL or typeof(field) === 'undefined'. Further, and perhaps more important, you're in a position to tell the caller exactly what's wrong, rather than relying on a much-more-general non-200 response, which might be accompanied by a message like "ya-ya, you screwed up again! but I'm not saying how." Commented Sep 4, 2011 at 10:38
  • 1
    Also, if it takes a round-trip to the server to discover errors, then it's very worth while to check all you can so as to avoid that time-consuming process. Commented Sep 4, 2011 at 10:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.