Skip to content

Instantly share code, notes, and snippets.

@cereal-s
Last active December 21, 2016 10:49
Show Gist options
  • Select an option

  • Save cereal-s/40d9f275cfe9629333597e24ef564217 to your computer and use it in GitHub Desktop.

Select an option

Save cereal-s/40d9f275cfe9629333597e24ef564217 to your computer and use it in GitHub Desktop.
NASA APOD API example with Memcached
<?php
/**
* Example of the NASA APOD API with Memcached
*
* @see https://api.nasa.gov/api.html#apod
* @see http://php.net/manual/en/class.memcached.php
*
* Since it is working with the `DEMO_KEY` rate limits
* are very low, and can be see in the RESPONSE headers, e.g.:
*
* X-RateLimit-Limit: 40
* X-RateLimit-Remaining: 31
*
* For more information see:
*
* @see https://api.nasa.gov/api.html#web-service-rate-limits
*/
require_once dirname(__DIR__) . '/vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;
try {
$media = ''; # initialize empty item
$entry = ''; # initialize empty item
$api_key = 'DEMO_KEY';
$apod_token = 'nasa_planetary_apod';
$cache = new Memcached;
$cache->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT);
$cache->addServer('127.0.0.1', 11211);
/**
* Check if the apod exists in the cache
*/
if( ! ($apod = $cache->get($apod_token)))
{
/**
* If the item is not found in the cache
* then make request to the remote resource
* and push it to the cache system
*/
if(Memcached::RES_NOTFOUND == $cache->getResultCode())
{
$client = new Client(['base_uri' => 'https://api.nasa.gov/'
, 'timeout' => 2.0
, 'connect_timeout' => 2.0]);
$response = $client->request('GET'
, '/planetary/apod'
, ['query' => ['api_key' => $api_key]]);
/**
* If the response code is OK then save
* the input to Memcached for 1 hour
*
* The contents will be in JSON format
*/
if(200 == $response->getStatusCode())
{
$apod = $response->getBody()->getContents();
$cache->set($apod_token, $apod, 3600);
}
}
}
/**
* Unserialize the JSON to make an Object
*/
$apod = json_decode($apod);
if(TRUE === is_object($apod))
{
$template = <<<'EOD'
<article>
<header>
<h2 class="text-center">Astronomy Picture of the Day</h2>
</header>
<figure>
<!-- media -->
%5$s
<figcaption>
<header>
<p>%1$s</p>
<h1>%2$s <small>&copy; %3$s</small></h1>
</header>
<main>
<p>%4$s</p>
</main>
<footer>
<p>More at <a href="%6$s">%6$s</a></p>
</footer>
</figcaption>
</figure>
</article>
EOD;
if('image' == $apod->media_type)
{
$media_template = <<< 'EOD'
<a href="%s"><img src="%s" alt="%s"></a>
EOD;
$media = sprintf($media_template, $apod->hdurl, $apod->url, $apod->title);
}
elseif('video' == $apod->media_type)
{
$media_template = <<< 'EOD'
<iframe width="960" height="540" src="%s"></iframe>
EOD;
$media = sprintf($media_template, $apod->url);
}
$date = (new IntlDateFormatter(Locale::getDefault(),
IntlDateFormatter::LONG,
IntlDateFormatter::LONG,
date_default_timezone_get(),
IntlDateFormatter::GREGORIAN))->format(new DateTime($apod->date));
$data = [$date
, mb_convert_case($apod->title, MB_CASE_TITLE, "UTF-8")
, $apod->copyright
, $apod->explanation
, $media
, 'http://apod.nasa.gov/apod/astropix.html'];
$entry = vsprintf($template, $data);
}
}
catch(RequestException $e) {
$entry = "<pre>[REQUEST]\n" . Psr7\str($e->getRequest());
if($e->hasResponse())
$entry .= "\n[RESPONSE]\n" . Psr7\str($e->getResponse());
$entry .= "</pre>";
}
catch(Exception $e) {
$entry = "<pre>[ERROR]\n" . $e->getMessage();
$entry .= "</pre>";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Nasa APOD API</title>
<style type="text/css">
* { margin:0; padding:0; box-sizing:border-box; } body { color:#474A48; background-color:#E8E9EB; } a { text-decoration:none; color:#2467af; } .main { width:1000px; margin:50px auto; padding:20px; background-color:#FFF; box-shadow: 4px 4px 2px #A2AEBB; } article > * { margin:.5rem 0 1rem; } figcaption > * { margin:1rem 0; } figcaption > main { margin:1rem 0 2rem; } h1, h2 {line-height:1.4; font-weight:300; font-size:1.6rem; font-family:Verdana, Arial, sans-serif;} h1 > small {display: block; font-size:.7em; line-height:1.5; } main > p { font-size:1.2rem; margin:20px 0;} footer {border-top:1px dashed #474A48; line-height:1.4; padding:.5rem .2rem; font-family:Verdana, Arial, sans-serif; font-size:.8rem;} .text-center {text-align:center;} </style>
</head>
<body>
<main class="main">
<?php
print $entry;
?>
</main>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment