I write a lot of software to interact with APIs. These APIs provide data usually in the form of an XML or JSON document. These documents are suppose to follow a spec and structure.

In practice however, this can be difficult to code for. Specs may change, fields may be renamed, moved, dropped, or made circumstantial.

Is it good or bad practice to always verify that a data field exists. Such as the following.

$first_name = isset($data['first_name']) ? $data['first_name'] : '';

This can make code much more difficult to read, and may need even more code in certain circumstances (such as when parsing XML attributes or XML with cdata used). Then there's also the case of validating the correct datatype.

Is it appropriate to trust an API spec, or should code check every data object that it itself didn't create?


Trust the API spec until you have reason not to trust it.

If the API says that a field is mandatory, but you can retrieve data from the service where that field isn't always populated, then it is "appropriate" to treat that field as optional (for reading purposes), even though the spec says it is mandatory.

For writing purposes, you can still respect the original contract, though the system may not actually enforce it. The point is, you can hang your hat on the API spec all day long, but if the system doesn't behave that way, and you don't control it, well, there it is.

  • 1
    Agreed, although this "liberal in what you accept" policy basically broke the web - ok, not the same scale, but still. If you see a misbehaving service and have a spec at hand, and before you code workarounds, ask the service provider if they can either fix their service or update the spec. Only if they don't respond or are not willing to fix, then you may implement your own interpretation. – Tibo Sep 15 '16 at 8:26

Usually when working with third party data providers what you'd want to do is use a data mapper. This way, whenever the response body changes, you only have to change your code in one place - the mapper.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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