Difference between revisions of "Examples of using the API"

From EN Ikoula wiki
⧼vector-jumptonavigation⧽ ⧼vector-jumptosearch⧽
 
(18 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 +
<span data-link_translate_en_title="Examples of using the API"  data-link_translate_en_url="Examples of using the API"></span>[[:en:Examples of using the API]][[en:Examples of using the API]]
 +
<span data-link_translate_he_title="דוגמאות לשימוש ה-API"  data-link_translate_he_url="%D7%93%D7%95%D7%92%D7%9E%D7%90%D7%95%D7%AA+%D7%9C%D7%A9%D7%99%D7%9E%D7%95%D7%A9+%D7%94-API"></span>[[:he:דוגמאות לשימוש ה-API]][[he:דוגמאות לשימוש ה-API]]
 +
<span data-link_translate_ru_title="Примеры использования API"  data-link_translate_ru_url="%D0%9F%D1%80%D0%B8%D0%BC%D0%B5%D1%80%D1%8B+%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F+API"></span>[[:ru:Примеры использования API]][[ru:Примеры использования API]]
 +
<span data-link_translate_ja_title="API を使用しての例"  data-link_translate_ja_url="API+%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%A6%E3%81%AE%E4%BE%8B"></span>[[:ja:API を使用しての例]][[ja:API を使用しての例]]
 +
<span data-link_translate_ar_title="أمثلة لاستخدام API"  data-link_translate_ar_url="%D8%A3%D9%85%D8%AB%D9%84%D8%A9+%D9%84%D8%A7%D8%B3%D8%AA%D8%AE%D8%AF%D8%A7%D9%85+API"></span>[[:ar:أمثلة لاستخدام API]][[ar:أمثلة لاستخدام API]]
 +
<span data-link_translate_zh_title="使用该 API 的示例"  data-link_translate_zh_url="%E4%BD%BF%E7%94%A8%E8%AF%A5+API+%E7%9A%84%E7%A4%BA%E4%BE%8B"></span>[[:zh:使用该 API 的示例]][[zh:使用该 API 的示例]]
 +
<span data-link_translate_ro_title="Exemple de utilizare a API"  data-link_translate_ro_url="Exemple+de+utilizare+a+API"></span>[[:ro:Exemple de utilizare a API]][[ro:Exemple de utilizare a API]]
 +
<span data-link_translate_pl_title="Przykłady użycia interfejsu API"  data-link_translate_pl_url="Przyk%C5%82ady+u%C5%BCycia+interfejsu+API"></span>[[:pl:Przykłady użycia interfejsu API]][[pl:Przykłady użycia interfejsu API]]
 +
<span data-link_translate_de_title="Beispiele für die Verwendung der API"  data-link_translate_de_url="Beispiele+f%C3%BCr+die+Verwendung+der+API"></span>[[:de:Beispiele für die Verwendung der API]][[de:Beispiele für die Verwendung der API]]
 +
<span data-link_translate_nl_title="Voorbeelden van het gebruik van de API"  data-link_translate_nl_url="Voorbeelden+van+het+gebruik+van+de+API"></span>[[:nl:Voorbeelden van het gebruik van de API]][[nl:Voorbeelden van het gebruik van de API]]
 +
<span data-link_translate_it_title="Esempi di utilizzo dell'API"  data-link_translate_it_url="Esempi+di+utilizzo+dell%27API"></span>[[:it:Esempi di utilizzo dell'API]][[it:Esempi di utilizzo dell'API]]
 +
<span data-link_translate_pt_title="Exemplos de como usar a API"  data-link_translate_pt_url="Exemplos+de+como+usar+a+API"></span>[[:pt:Exemplos de como usar a API]][[pt:Exemplos de como usar a API]]
 +
<span data-link_translate_es_title="Ejemplos de uso de la API"  data-link_translate_es_url="Ejemplos+de+uso+de+la+API"></span>[[:es:Ejemplos de uso de la API]][[es:Ejemplos de uso de la API]]
 
<span data-link_translate_fr_title="Exemples d'utilisation de l'API"  data-link_translate_fr_url="Exemples_d%27utilisation_de_l%27API"></span>[[:fr:Exemples d'utilisation de l'API]][[fr:Exemples d'utilisation de l'API]]
 
<span data-link_translate_fr_title="Exemples d'utilisation de l'API"  data-link_translate_fr_url="Exemples_d%27utilisation_de_l%27API"></span>[[:fr:Exemples d'utilisation de l'API]][[fr:Exemples d'utilisation de l'API]]
 
<br />
 
<br />
  
This article has been created by an automatic translation software. You can view the article source [[:fr:Exemples d'utilisation de l'API|here]].<br /><span data-translate="fr"></span>
+
{{#seo:
 
+
|title=using the API
 
+
|title_mode=append
<!-- Début de l'article. Placez votre texte ci-après et n'hésitez pas à personnaliser les chapitres selon votre besoin -->
+
|keywords=these,are,your,keywords
 
+
|description=How to use the API through some concrete and functional examples.
 +
|image=Uploaded_file.png
 +
|image_alt=Wiki Logo
 +
}}
  
  
 
==Introduction == <!--T:1-->
 
==Introduction == <!--T:1-->
How to use the API through some concrete and functional examples.
+
How to use the '''API''' through some concrete and functional examples.
  
 
==Functions for the examples == <!--T:2-->
 
==Functions for the examples == <!--T:2-->
Line 211: Line 227:
 
==Common errors == <!--T:21-->
 
==Common errors == <!--T:21-->
 
;Permission Denied  
 
;Permission Denied  
: Means that the user used in the API does not have the right to access the requested information or perform the desired action  
+
: Means that the user used in the ''API'' does not have the right to access the requested information or perform the desired action  
 
;Unable to decrypt password  
 
;Unable to decrypt password  
 
: Means that the parameter '''crypted_password ''' has been poorly encrypted or corrupted  
 
: Means that the parameter '''crypted_password ''' has been poorly encrypted or corrupted  

Latest revision as of 14:50, 9 September 2021

en:Examples of using the API he:דוגמאות לשימוש ה-API ru:Примеры использования API ja:API を使用しての例 ar:أمثلة لاستخدام API zh:使用该 API 的示例 ro:Exemple de utilizare a API pl:Przykłady użycia interfejsu API de:Beispiele für die Verwendung der API nl:Voorbeelden van het gebruik van de API it:Esempi di utilizzo dell'API pt:Exemplos de como usar a API es:Ejemplos de uso de la API fr:Exemples d'utilisation de l'API


Introduction

How to use the API through some concrete and functional examples.

Functions for the examples

// Chemin local vers la clé publique téléchargée sur http://api.ikoula.com/downloads/Ikoula.API.RSAKeyPub.pem
define('API_PUB_KEY_PATH', dirname(__FILE__) . '/Ikoula.API.RSAKeyPub.pem');

<!--T:3-->
// Fonction de chiffrement du mot de passe via la clé publique Ikoula
function opensslEncryptPublic($password)
{
	// Vérification de la présence de la clé publique
	if(file_exists(API_PUB_KEY_PATH))
	{
		if(!empty($password))
		{
			// on récupère la clé public
			$publicKey = openssl_pkey_get_public('file://'.realpath(API_PUB_KEY_PATH));

			<!--T:4-->
// S'il n'y as pas eu d'erreurs lors de la récupération de la clé publique, on continue
			if ($publicKey !== FALSE)      
			{
				// Si chiffrement clé publique OK
				if(openssl_public_encrypt($password, $crypted, $publicKey) === TRUE)   
				{
					// Renvoie du mot de passe crypté
					return $crypted;       
				}
				else
				{
					return NULL;
				}
			}
			else
				return NULL;
		}
		else
			return NULL;
	}
	else
	{
		echo("Erreur - la clé publique n'est pas présente.\n");
		return NULL;
	}
}

<!--T:5-->
// Fontction de création de la signature en fonction des paramètres présents
function createSignature($params=array())
{
    $signature = null;

    <!--T:6-->
// Si il y a au moins un paramètre
    if (count($params) > 0)
    {
        //debug('create signature');
        //debug($params);
        
        // Triage des paramètres dans le sens croissant
        ksort($params);
        
        // Encodage des paramètres
        $query = http_build_query($params);

        <!--T:7-->
// Encodage des signes "plus "+"
        $query = str_replace("+", "%20", $query);

        <!--T:8-->
// Transformation de la chaîne de caractères en minuscule
        $query = strtolower($query);

        <!--T:9-->
$public_key = "";
        // Si le fichier existe, on va récupérer la clé
        if (file_exists(API_PUB_KEY_PATH))
        {
            $public_key = trim(
                    str_replace(
                            array("\n", '-----BEGIN PUBLIC KEY-----','-----END PUBLIC KEY-----'), 
                            array('', '', ''), 
                            file_get_contents(API_PUB_KEY_PATH)
                        )
                    );
        }

        <!--T:10-->
// Hashage des paramètres
        $hash = hash_hmac("SHA1", $query, $public_key, true);

        <!--T:11-->
// Encodage en base64
        $signature = base64_encode($hash);
    }

    <!--T:12-->
return $signature;
}

<!--T:13-->
// Fonction facilitant l'envoie des requêtes vers l'API Ikoula
function send_request ($rest, $url_param, $params=array())
{
	// initialisation de CURL
	$ch = curl_init();
	if($ch)
	{
		// Si on a des info on utilise l'api REST sinon on utilise l'api standard (WebService)
		if($rest)
			$url = "https://api.ikoula.com/rest/" . $url_param;
		else 
			$url = "https://api.ikoula.com/?r=" . $url_param;

		
		<!--T:14-->
// si on est en REST on rajoute le type d'appel (POST,DELETE,PUT,GET,...) sinon on passe en POST
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, ($rest)?$rest:"POST");
		// Si il y a des paramètres on les rajoute dans la requête
		if(is_array($params) && count($params) > 0)
		{
			$params_str = http_build_query($params);
		}
		if($rest=='POST')
		{
			// on rentre le nom de paramètre présent dans la requête
			curl_setopt($ch,CURLOPT_POST, true);
			curl_setopt($ch,CURLOPT_POSTFIELDS, $params_str);
		}
		else
		{
			$url .= (strpos($url,'?') === false ? '?' : '&').$params_str;
		}
			
		// On ajoute l'url
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($ch, CURLOPT_HEADER, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		// on vire les en-tête HTTP pour avoir directement le retour
		curl_setopt($ch, CURLOPT_HEADER, false);
	   
		// exécution de la requête
		$data = curl_exec($ch);
	   
		// fermeture de l'objet
		curl_close($ch);

		<!--T:15-->
// retourne la réponse
		return($data);
	}
	return null;
}

API calls

//login
$login = 'mail@test.com';
//on crypte le mot de passe
$crypted_password = base64_encode(opensslEncryptPublic('MOT_DE_PASSE_A_CRYPTER'));

<!--T:17-->
//liste des VM - retour en JSON

<!--T:18-->
//liste des paramètres que l'on souhaite envoyer à l'API (pour générer la signature)
$parameters = array('login' => $login, 'crypted_password' => $crypted_password, 'format' => 'json');
//on génère la signature
$signature = createSignature($parameters);
//on ajoute la signature dans les paramètres à envoyer lors de l'appel à l'API
$parameters['signature'] = $signature;
//on fait l'appel API
$data = send_request(false,'wsflex/vmlist',$parameters);
print_r($data); //appel WebService
$data2 = send_request('GET','vm/list',$parameters);
print_r($data2); //appel REST

<!--T:19-->
//informations d'une VM - retour en XML

<!--T:20-->
//liste des paramètres que l'on souhaite envoyer à l'API (pour générer la signature)
$parameters = array('login' => $login, 'crypted_password' => $crypted_password, 'format' => 'xml', 'subscr_id' => 12345);
//on génère la signature
$signature = createSignature($parameters);
//on ajoute la signature dans les paramètres à envoyer lors de l'appel à l'API
$parameters['signature'] = $signature;
//on fait l'appel API
$data = send_request(false,'wsflex/vminfo',$parameters);
print_r($data); //appel WebService
$data2 = send_request('GET','vm/'.$parameters['subscr_id'],$parameters);
print_r($data2); //appel REST

Common errors

Permission Denied
Means that the user used in the API does not have the right to access the requested information or perform the desired action
Unable to decrypt password
Means that the parameter crypted_password has been poorly encrypted or corrupted
Invalid credentials
Means that authentication has failed, and that the user is not so recognized
Invalid or missing signature
Means that the signature is not present in the parameters received by the API, or that it is invalid


Other lifts of errors are possible but will be contextual depending on the desired functionality.



This article seemed you to be useful ?

0



You are not allowed to post comments.