Load external JSON regularly

I am currently using an API that returns a JSON object. I pay for a hit, so I would like to minimize my hits. I am using this object to fill in images and text on my page. The returned object is very similar to itunes remote search.

A simplified version of my code is this:

<img id="test" src="" alt="Image" />

<script>
    $.getJSON( "https://itunes.apple.com/lookup?id=284910350", function( data ) {           
        document.getElementById('test').setAttribute("src", data.results[0].screenshotUrls[0]);
    });
</script>

      

Every time users open this page a request is sent to the server and a request is added to my account (obviously). I would like to temporarily store the object on my own server so that I can query the data once and provide the user with a "local" version. What's the best way to do this? Is it possible for the file to be updated every week or so automatically?

Thanks in advance!

+3


source to share


1 answer


This is a lightweight cron job. Assuming you can execute a bash script on your server:

1 - On your server, put a bash script called fetchItune.sh

. The content of this script basically stores some curl requests for the external API:

#!/bin/sh
curl -H "Accept: application/json" https://itunes.apple.com/lookup\?id\=284910350 -o /path/to/storage/data.json

      

You can get an idea of ​​this script for example. placing the list of endpoints in an array, or outputting to different files, etc., but mostly, just make sure they are valid HTTP requests that accept a JSON response.

2 - Set up a cron job to do it weekly. It can be as simple as putting this script in /etc/cron.weekly

if you are using an Ubuntu server. If not, search the server documentation. I'm sure there is a section on how cron works.



3 - From your JavaScript, request the server endpoint instead of the external API:

<script>
    $.getJSON( "/path/to/storage/data.json", function( data ) {           
        document.getElementById('test').setAttribute("src", data.results[0].screenshotUrls[0]);
    });
</script>

      

EDIT . You can write PHP script to request external API instead of bash script. The principle is the same. I am taking this directly from PHP curl documentation: http://php.net/manual/en/curl.examples-basic.php

<?php

$ch = curl_init("https://itunes.apple.com/lookup\?id\=284910350");
$fp = fopen("/path/to/storage/data.json", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

      

0


source







All Articles