Author: Shahroze Nawaz
Posted on: 2017-05-23
Package: Cloudways API Class
Read this article to learn how to manage a cloud hosting structure from PHP using Cloudways API.
Accessing Web APIs via HTTP
If you are familiar with a REST API, you must know about HTTP calls created for getting and posting data from a client to the server.
What if you wish to create a REST API client in PHP? Your answer could be to go with CURL. CURL is the most widely used method to make HTTP calls but it imposes several complicated steps.
Let's see a simple CURL request in PHP:
$url = "https://api.cloudways.com/api/v1"; $resource = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Accept: application/json, Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
You need to call the curl_setopt() method to define the header and the particular HTTP request method like GET, POST, PUT, etc. It does not look simple. So, what is a better robust alternative?
Here comes Guzzle. Lets see how Guzzle creates a request:
$client = new GuzzleHttp\Client();
$res = $client->request("GET", "https://api.cloudways.com/api/v1", [
"headers" => [
"Accept" => "application/json",
"Content-type" => "application/json"
You can see that it is simple. You just need to initialize the Guzzle client and pass a HTTP method and an URL. After that, pass the array of headers and other options.
Install the Guzzle Client
Guzzle is a simple PHP HTTP client that provides an easy way of creating calls and integration with Web services. It is the standard abstraction layer used to send messages to the server. Several prominent features of Guzzle are:
Send both synchronous and asynchronous requests.
It provides a simple interface for building query strings, POST requests, streaming large uploads and downloads, uploading JSON data, etc.
Allows the use of other PSR7 compatible libraries with Guzzle.
Allows you to write environment and transport agnostic code.
Middleware system allows you to augment and compose client behavior.
The preferred way of installing Guzzle is Composer. If you haven't installed Composer yet, download it from here
Now to install Guzzle, run the following command in SSH terminal:
composer require guzzlehttp/guzzle
This command will install the latest version of Guzzle in your PHP project. Alternatively you can also define it as a dependency in the composer.json file and add the following code in it.
After that, run the composer install command. Then you need to include the autoloader and add some more files to use Guzzle:
The installation process is over. Now it's time to work with a real example of making HTTP calls with an API. For the purpose of this article, I will work with Cloudways API
What You Can Do With the Cloudways API?
Cloudways is a managed hosting provider for PHP, Magento, WordPress and many other frameworks and CMS. It has an API that you could use for performing CRUD operations on servers and applications.
Check out popular use cases of the Cloudways API to see how you could integrate it into your projects.
In this article, I am going to make HTTP calls to perform specific operations on the Cloudways servers.
Send the HTTP Requests
As I mentioned before, sending HTTP requests in Guzzle is very easy. You only need to pass the base URI, HTTP method and headers.
If there is an authentication layer in the external API, you can also pass these parameters. Similarly, Cloudways API needs email address and an API key to authenticate users and send the response. You need to sign up for a Cloudways account to get your API credentials.
Let's start by using the CloudwaysAPI.php file to set up Guzzle to make HTTP calls. I will also use the class methods for making HTTP calls from them.
The URL of the API does not vary, so I will use the const qualifier with it. After that I will concatenate it with other URL suffixes to get the response. Additionally, I have declared variables $auth_key, $auth_email which will hold the authentication email and the API key. $accessToken will hold the temporary token which will be renewed every time.
Create a Post Request to Get Access Token
The access token will be generated from the URL https://api.cloudways.com/api/v1/oauth/access_token every time I access the API. This will be set in $url with additional data array which holds auth credentials.
Later on, I created a POST request with the base URL and query string. The response will be decoded and the access token is saved to be used from all the methods.
The POST request for getting the access token is completed. Additionally, If you observed in the exception handling, I declared a method StatusCodeHandling($e), which will take care of the response codes (HTTP codes like 404, 401, 200 etc), and throw a related exception.
The main client class is now completed. I can extend it to create more HTTP requests for different cases.
Create a GET Request to Fetch All Servers
Once the User is authenticated, I can fetch all my servers and applications from Cloudways. /server is the suffix concatenated with the base URI. This time, I will attach the accessToken with Authorization string in Guzzle header to fetch all servers in JSON response. To do this, I created a new method called getServers.
Now create index.php file and include CloudwaysAPIClient.php at the top. Next, I declare my API key and email, passing it to the class constructor to finally get the servers.
$api_key = 'W9bqKxxxxxxxxxxxxxxxxxxxjEfY0';
$email = 'firstname.lastname@example.org';
$cw_api = new CloudwaysAPI($email,$api_key);
$servers = $cw_api->getServers();
Lets test it in Postman to verify that the information and right response codes are being fetched.
Note: For a Windows local development environment you need to add cert.pem file to PHP folder in XAMPP and add "curl.cainfo ="C:\path\to\cacert.pem" to php.ini file
Create Delete Request To Delete a Server
Similarly you can also delete your cloud server by passing the $serverid to the deleteServer method.
Launching Applications on Server
You can also get, create and delete PHP applications on the server by passing the required parameters. For getting all apps simply use the "/app" URL.
For Creating an application in any of the server you need to pass 4 parameters $serverid, $application, $app_version, $app_name:
These are some major use cases to consume the Cloud API in PHP with guzzle you can also create methods for the following use cases:
1. CloudwaysBot Api
2. Git Api
3. SSH Keys Management Api
4. Security Api
Downloading and using the Cloudways API Client Class
The Cloudways client API class can be downloaded and installed from a ZIP archive or using the Composer tool using the instructions also available in the download page.
If you liked this articles share it with other developer colleagues. If you have questions post a comment here.
You need to be a registered user or login to post a comment
1,451,806 PHP developers registered to the PHP Classes site.
Be One of Us!
Login Immediately with your account on:
No comments were submitted yet.