Have you ever thought about using our API (or any other API), but didn’t know where to start? Or what you could actually do with it? In this post, we will take a closer look at our API and try to make a real-world working example so anyone that’s interested could have a better understand its’ benefits.
We’ll be using PHP as our primary scripting language with some help from jQuery and Bootstraps. In this example, we’ll try to make a simple server monitoring tool with basic information and a few functions – reboot, start and stop a virtual machine. If you don’t have a custom monitoring and control systems in place for your machines and don’t want to login to the Client Area every time you want to perform an action, this custom simple solution could just for you.
You can reference the API in our documentation. Let’s begin!
index.php – The Frame
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script type="text/javascript"> $(function(){ setInterval(function() { $.get("practical.php", function(data) { $('#data').html(data); }); }, 1000); }); </script> </head> <body> <div class="container text-center" id="data"></div> </body> </html>
This is the homepage file for the app we’re writing. For simplicity, we’re embedding jQuery for basic HTTP requests and Bootstrap to give it a nicer look than plain HTML. Other than that the page has a simple jQuery script:
<script type="text/javascript"> $(function(){ setInterval(function() { $.get("practical.php", function(data) { $('#data').html(data); }); }, 1000); }); </script>
This script requests raw html data from practical.php file and writes the contents to the container div every second. You can adjust the interval that better suits your needs – just remember it’s in milliseconds. You can further add elements to the page if you need.
practical.php – The Engine
In this file we’ll be using example code snippets taken from API documentation and applying to a real world situation. You can download all files and have a better look at them, here we’ll discuss the principle functions of the file.
First, let’s define the API key for all our requests. You can find your API key in the Client Area > API section:
$api_key = "b310341902c95966493b16e90767d3bc6b73cdd4";
We use cURL to make a HTTP request to the /vms endpoint to get the details of all owned machines. The returned data is in JSON format, therefore to be able to work with it, we need to decode it:
$obj = json_decode(curl_exec($ch), true);
These two functions execute the cURL request, decode the returned data and put it into the $obj array so we can begin picking the parts we need.
Now we check whether the request was successful:
if($obj['status'] = "success") { ... } else { print 'Failed to connect'; }
If the status was ‘success’ it means we can continue. We’ll be using foreach() loop to list all owned machines automatically, like this:
foreach($obj['data']['vms'] as $vm) { ... }
This way, one by one, we put the data of every single machine into the $vm array object. Now if you try this script, it should output the machine names one by one:
print "<h3>" . $vm['displayname'] . "</h3>";
And that is the basic logic to use and display any information for all machines you own. Everything else is up to personal preferences what and how you want to display. You can either do it yourself or use the example files we provided and modify them to your needs. For example, you can make it look like this:
Now if you not only want to monitor the services but also have some control over them it is all possible via API.
actions.php – The Function
In the actions.php file you can find some basic functions we scripted – reboot, start and stop your VM. Again the principle is the same – we’ll be using cURL and appropriate API endpoints, only this time, we’ll do it via POST.
$api_key = "b310341902c95966493b16e90767d3bc6b73cdd4"; $c = curl_init(); $headers = array(); $headers[] = "X-Auth-Token: $api_key"; $request = $_GET['req']; $id = $_GET['id']; if($request == "reboot") { curl_setopt($c, CURLOPT_URL, "https://api.host1plus.com/latest/manage/vps/vms/$id/reboot"); } curl_setopt($c, CURLOPT_VERBOSE, 0); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); curl_setopt($c, CURLOPT_POST, 1); curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($c, CURLOPT_HTTPHEADER, $headers); curl_exec($c); curl_close($c);
In this example, we GET the action required and id of a virtual machine. If the actions is to reboot the script executes cURL request to the /reboot endpoint. Now let’s go back to pracical.php file and implement this feature. The button:
print "<button type='button' class='btn btn-default btn-xs' onclick='reboot(". $vm['serviceId'] .")'>Reboot</button>";
And some jQuery magic:
<script> function reboot(id) { $.ajax({ type: 'GET', url: 'actions.php', data: 'req=reboot&id=' + id, }); } </script>
So we added a button with an onclick event which will make a request to the actions.php file with given parameters. You can add few more functions and have maybe have something like this:
Now we can monitor our servers and interact with them as well.
Conclusion
Even if you’re not the most experienced programmer in the world, many of the API functions are really easy to work with, as we demonstrated above. But always remember to keep your access to these scripts secure – either just host locally with no public access or have an authentication in place. Good luck and have fun scripting!
Download example filesThe post Practical Guide to API appeared first on Host1Plus Blog.