3 years ago

How to deal with inconsistent results when consuming an API

Posted 3 years ago by robsox

I am working on a project that gathers data from amazon's product search API but have found that the data is not always consistent (a description is not always returned for example) which leads to an error trying to access a nonexistent key. I have worked around it by having a number of if statements (see code below) but it's kind of a hack.

What is the best way to deal with APIs that don't always return the a constant set of values?

This is what I need to do in order to get the description (Editorial Review in amazon language) which will likely turn into a nightmare later on.

 if (array_key_exists('EditorialReviews', $product)) {
            if (array_key_exists('EditorialReview', $product['EditorialReviews'])) {
              if (array_key_exists('Content', $product['EditorialReviews']['EditorialReview'])) {
                // dd($product['EditorialReviews']['EditorialReview']['Content']);
                $newProduct['description'] = strip_tags ($product['EditorialReviews']['EditorialReview']['Content']);
              } elseif (array_key_exists('0', $product['EditorialReviews']['EditorialReview'])){
                  if (array_key_exists('Content', $product['EditorialReviews']['EditorialReview']['0'])) {
                      $newProduct['description'] = strip_tags ($product['EditorialReviews']['EditorialReview']['0']['Content']);

        } else {
            $newProduct['description'] = '';

Thanks, Rob

Please sign in or create an account to participate in this conversation.