Getting information from an external API using jsonp

By | 11 August, 2013

As you probably know, it is not possible to retrieve information from an external source located on a different domain to your client-side code directly using a traditional AJAX call. This is because of the cross-site scripting policy, which tries to protect websites from malicious script injection.
To overcome this situation there is a workaround which consists on using jsonp as data format. Basically the way it works is passing the name a callback function in our request that will end up as the name of json object return by the remote API. For instance we could query the BestBuy API using this jQuery statement.

var getProductsFromBestBuy = function () {
        $.ajax({
            type: 'GET',
            cache: true,
            url: '//api.remix.bestbuy.com/v1/products(active=true&manufacturer=microsoft)?show=sku,name,salePrice,longDescriptionHtml,manufacturer,categoryPath,image&apiKey=your_api_key&format=json&callback=?',
            dataType: 'json',
            success: function (response) {
                productsFromApi = mapProductsFromBestBuy(response.products);
                renderProducts("#results", productsFromApi);
            },
            error: function (message) {
                console.log(message);
            }
        });
    };

With the previous code we can then parse the data as we are used to do.
The finally we were trying to achieve is to use this new source of data to replace our local store. As a reminder we were building a sort of shopping website where users can buy products.
Thanks to having kept in mind concepts such as extensibility, we are now in a win-win situation of using this new data without having to change or throw away the previous code. Just writing a method which maps the products coming from BestBuy to our products structure.

var mapProductsFromBestBuy = function (products) {
        productsFromBestBuy = new Array();

        $.each(products, function (index, value) {
            var product = new Object();
            product.product_image = value.image;
            product.brand_name = value.manufacturer;
            product.product_name = value.name;
            product.product_price = value.salePrice;
            product.product_description = value.longDescriptionHtml;
            product.product_id = value.sku;

            if (typeof(value.categoryPath) !== 'undefined' && value.categoryPath.length > 0)
                product.category_name = value.categoryPath[0].name;

            productsFromBestBuy.push(product);
        });

        return productsFromBestBuy;
    };

As a final result everything works as it did before.



Facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Leave a Reply

Your email address will not be published.