A kit is a set of functions easing the API use. Some kits propose basic functions, others may be more specific.
You will find below the basics to create your own API kit. Codes samples are proposed in PHP and rely on the functions you'll find in the PHP kit Iper_API.
Define the useful parameters, such as api_key, secret, format, and the api_url and auth_url URLs.
class Iper_API {
var $_conf = array(
'api_key' => '',
'secret' => '',
'api_url' => 'http://api.ipernity.com/api',
'auth_url' => 'http://www.ipernity.com/apps/authorize',
'format' => 'json'
);
var $_error_code = 0;
var $_error_msg = '';
}
Write a function to sign parameters. Inputs are:
$method (str) : the called method.$params (arr) : the parameters array.
private function signParams($method,$params) {
$keys = array_keys($params);
sort($keys);
$sig='';
foreach($keys as $k) { $sig.=$k.$params[$k]; }
$sig.=$method.$this->_conf['secret'];
return md5($sig);
}
This function builds an URL-encoded QueryString from a parameters array. There is a ready-to-use PHP similar function: http_build_query.
$params (arr) : the parameters array.
private function buildQueryString($params) {
$query=array();
foreach($params as $k=>$v) $query[]=$k.'='.urlencode($v);
return implode('&',$query);
}
This is the most important function. It handles the API requests, and returns eventual errors. Here are what this function does:
api_key to parameters,Inputs:
$method (str) : the called method.$params (arr) : the parameters array.Outputs:
false if the request failed.
public function request($method, $params=array()) {
// add the api_key
$params['api_key']=$this->_conf['api_key'];
// sign the request (optional)
$params['api_sig'] = $this->_signParams($method,$params);
// build API url
$url = $this->_conf['api_url'].'/'.$method.'/'.$this->_conf['format'];
// request the URL (using curl)
$curl=curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER,0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
// save the result
$data=curl_exec($curl);
// save curl infos
$info=curl_getinfo($curl);
// analyse network errors
if ( curl_errno($curl) )
{
$this->_error_code = 0;
$this->_error_msg = curl_error($curl);
return false;
}
curl_close($curl);
// parse the response (JSON example)
$response = json_decode($data,true);
if ( is_array($response) && isset($o['api']['status']) )
{
if ( $response['api']['status']!='ok' )
{
$this->_error_code = $response['api']['code'];
$this->_error_msg = $response['api']['message'];
return false;
}
else
{
return $response;
}
}
// response parsing failed.
else
{
$this->_error_code = 0;
$this->_error_msg = 'Could not parse the JSON response.';
return false;
}
}
That's all folks... for the moment! And don't forget to contact us if you want to share your own API kit!