Developing with an API
Once you've got the basics down, here's a few sample functions to make developing a little easier.
This function will build your API queries for you:
<?php
function getApiData($methodName, $params = array()){
// function buildBaseQuery formats the elements of api call that doesn't change
$query = buildBaseQuery($methodName);
foreach($params as $key => $data){
$query .= '&'.$key.'='.rawurlencode($data);
}
return json_decode(file_get_contents($query), true);
}
function buildBaseQuery($methodName){
$url = 'http://amazonpepr.com/api/?';
$apiUsername = 'insert_api_username_here'; // insert api username here
$apiKey = 'insert_api_key_here'; // insert api key here
// $results = 'xml'; // Commented out to demonstrate the XML option
$results = 'json';
$method = 'method='.$methodName;
$baseQuery = $url.'api_username='.$companyUsername.'&api_key='.$apiKey.'&results='.$results.'&'.$method;
return $baseQuery;
}
?>
Fill out the API username, API key, and your preferred results format in the buildBaseQuery() function, then put these functions somewhere accessible. Your API calls now look something like this:
<?php
$results = getApiData('get_metadata', array('isbn' => $isbn));
if($results['success']){
// Success message here
echo 'Success! '.$results['message'];
$metadata = $results['metadata'];
} else {
// Failure message here
echo 'Failure: '.$results['message'];
}
?>