Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Say hello to redesigned Cloudways, an empowering Startup Program, enhanced Staging, a new Let’s Encrypt Wildcard SSL certificate feature, and more. READ MORE

How to Make Your Laravel Applications Interact With Cloudways API

Updated on October 6, 2016

5 Min Read
Reading Time: 5 minutes

Hey guys, I’m back with some good news for you; Cloudways has finally launched its API for developers to play with. This is a level up for all the developers, giving them more flexibility and more options. Today, we’ll be playing with our Laravel App on Cloudways to interact with Cloudways APIs. This is to give you a brief introduction on using these APIs. So let’s start.

How to Make Your Laravel Applications Interact With Cloudways API

We will use the basic UI which will enable us to access Cloudways API. I will guide you through the whole process, so get yourself a fresh Laravel App on your Cloudways Server and just follow the steps below:

Step-1: Getting your .env file ready

You will see a .env file into your/application/<app_name>/public_html/

$vim .env

Add these following variables into your .env file. You can fetch the API_KEY from here.

API_EMAIL="<your_email>"
API_KEY="<your_key>"
BASE_URL="https://api.cloudways.com/api/v1"

Save and Exit

We will implement the following 7 functionalities:

  • List Servers on our Platform
  • Create Server
  • Stop Server
  • Restart Server
  • Restart Varnish
  • Restart Nginx
  • Server Settings

So let’s prepare our routes now:

Step-2: Making our endpoints

Laravel 5.3 has changed a bit when it comes to routes. It could’ve been found in app/Http/ in Laravel 5.2, but now they have been placed in public_html/routes/

So let’s open up our web.php route file.

$vim public_html/routes/web.php

And insert these lines into the file:

Route::get('/', function () {
    return view('welcome');
});

Route::get('/createServer',"Server@createServer");
Route::get('/listServer',"Server@listServer");
Route::get('/stopServer',"Server@stopServer");
Route::get('/restartServer',"Server@restartServer");
Route::get('/restartVarnish',"Server@restartVarnish");
Route::get('/restartNginx',"Server@restartNginx");
Route::get('/listServerSettings',"Server@listServerSettings");

Each of our route uses method GET and Calls up the function listServer, stopServer etc. of the controller Server. Let’s make up our controller.

Step-2: Making up our controller

Here goes all our logic, accessing API, and declaring variables etc. Let’s make a file inside app/Http/Controllers/ and name it Server.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Server extends BaseController
{
   
}

This is how our basic controller looks like. Now, we’ll add our constructor:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Server extends BaseController
{
	#This is the mail function that access the api.
    public function callCloudwaysAPI($method, $url, $accessToken, $post = []){
        #Getting base URL from .env
        $baseURL = getenv('BASE_URL');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_URL, $baseURL . $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        #IF ACCESS TOKEN IS AVAILABLE THEN SKIP THE NEXT CALL ELSE GET TOKEN
        //curl_setopt($ch, CURLOPT_HEADER, 1);
        //Set Authorization Header
        if ($accessToken) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $accessToken]);
        }
        //Set Post Parameters
        $encoded = '';
        if (count($post)) {
            foreach ($post as $name => $value) {
                $encoded .= urlencode($name) . '=' . urlencode($value) . '&';
            }
            $encoded = substr($encoded, 0, strlen($encoded) - 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
            curl_setopt($ch, CURLOPT_POST, 1);
        }
        $output = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($httpcode != '200') {
            die('An error occurred code: ' . $httpcode . ' output: ' . substr($output, 0, 10000));
        }
        curl_close($ch);
        return json_decode($output);
    }

}

Here, we add up the main function that will access the Cloudways API and we setup all the headers necessary for each request. We will use this very function to make all the requests. If we don’t provide it the access token, it will fetch us an access token itself, or else will simply handle our request.

Let’s add our first function for creating a server on cloudways: this will create a default DO server. Let’s add this server before the ending bracket. You can find the complete code at the end of this tutorial.

public function createServer (){
        $accessToken = $this->accessToken();
        $addSeverResponse = $this->callCloudWaysAPI('POST', '/server', $accessToken, [
        'cloud' => 'do',
        'region' => 'nyc3',
        'instance_type' => '1GB',
        'application' => 'wordpress',
        'app_version' => '4.6.1',
        'server_label' => 'API Test',
        'app_label' => 'API Test',
        ]);
        
        $operation = $addSeverResponse->server->operations[0];
        echo '<pre>';
        print_r($addSeverResponse);
        echo  '</pre>';

    }

Let’s add a call for listing all the existing servers on our cloudways account:

public function listServer(){
        $accessToken = $this->accessToken();
        $addSeverResponse = $this->callCloudWaysAPI('GET', '/server', $accessToken,null);
        echo '<pre>';
        print_r($addSeverResponse->servers);
        echo  '</pre>';
    }

Now, we will add a simple call that will stop the server by providing the server ID. You can fetch the server ID from the listServer response. Let’s check that out:

public function stopServer(Request $request){
        $accessToken = $this->accessToken();
        $serverId = $request->input('serverId');
        $addSeverResponse = $this->callCloudWaysAPI('POST', '/server/stop', $accessToken, [
        'server_id' => $serverId
        ]);
        echo '<pre>';
        print_r($addSeverResponse);
        echo  '</pre>';
    }

You can see that we have fetched the server ID from the request we get from the UI. We’ll see that later on. A similar call can be implemented to restart the server:

public function restartServer(Request $request){
        $accessToken = $this->accessToken();
        $serverId = $request->input('serverId');
        $addSeverResponse = $this->callCloudWaysAPI('POST', '/server/restart', $accessToken, [
        'server_id' => $serverId
        ]);
        echo '<pre>';
        print_r($addSeverResponse);
        echo  '</pre>';
    }

Now, we’ll add two more functions that will call API to restart Varnish and Nginx, they are quite similar, let’s see:

public function restartVarnish(Request $request){
        $accessToken = $this->accessToken();
        $serverId = $request->input('serverId');
        $addSeverResponse = $this->callCloudWaysAPI('POST', '/service/state', $accessToken, [
        'server_id' => $serverId,
        'service' => 'varnish',
        'state' => 'restart'
        ]);
        echo '<pre>';
        print_r($addSeverResponse);
        echo  '</pre>';
    }

    public function restartNginx(Request $request){
        $accessToken = $this->accessToken();
        $serverId = $request->input('serverId');
        $addSeverResponse = $this->callCloudWaysAPI('POST', '/service/state', $accessToken, [
        'server_id' => $serverId,
        'service' => 'nginx',
        'state' => 'restart'
        ]);
        echo '<pre>';
        print_r($addSeverResponse);
        echo  '</pre>';
    }

In the end, we need to see what server settings we’re running our servers with. Here it goes:

public function listServerSettings(Request $request){
        $accessToken = $this->accessToken();
        $serverId = $request->input('serverId');
        $addSeverResponse = $this->callCloudWaysAPI('GET', '/server/manage/settings?server_id=' . $serverId, $accessToken, []);
        echo '<pre>';
        print_r($addSeverResponse);
        echo  '</pre>';
    }

Step-3: Make our Views
So, here was our controller, lets have a look into our views. I am using default Laravel Welcome view, which resides in resources/views/Welcome.blade.php. I’ll be editing a small part of the code to make it more usable. You can find the link to complete code at the end of this file.

<div class="content">
<div class="title m-b-md">
    Laravel Cloudways Api Example
</div>

<div class="links">
    <a href="http://phplaravel-14171-57029-159086.cloudwaysapps.com/listServer">List Servers</a>
    <a href="http://phplaravel-14171-57029-159086.cloudwaysapps.com/createServer">Create Server</a>
</div>
<div class="links">
    <form action="http://phplaravel-14171-57029-159086.cloudwaysapps.com/stopServer" method="GET">
     <br>
      Stop Server: <input placeholder="Server ID" type="text" name="serverId">
      <input type="submit" value="Stop">
     <br>
    </form>
    <form action="http://phplaravel-14171-57029-159086.cloudwaysapps.com/restartServer" method="GET">
     <br>
      Restart Server: <input placeholder="Server ID" type="text" name="serverId">
      <input type="submit" value="Restart">
     <br>
    </form>
    <form action="http://phplaravel-14171-57029-159086.cloudwaysapps.com/restartVarnish" method="GET">
     <br>
      Restart Varnish: <input placeholder="Server ID" type="text" name="serverId">
      <input type="submit" value="Restart Var.">
     <br>
    </form>
    <form action="http://phplaravel-14171-57029-159086.cloudwaysapps.com/restartNginx" method="GET">
     <br>
      Restart Nginx: <input placeholder="Server ID" type="text" name="serverId">
      <input type="submit" value="Restart Nginx.">
     <br>
    </form>
    <form action="http://phplaravel-14171-57029-159086.cloudwaysapps.com/listServerSettings" method="GET">
     <br>
      Server Settings: <input placeholder="Server ID" type="text" name="serverId">
      <input type="submit" value="Settings">
     <br>
    </form>

Let’s take a look at our UI:

laravel-cloudways-api-example

Let’s list some servers:

laravel-cloudways-api-example-2

We will get some responses like this. Now you can play with the cloudways API. Here’s the complete code. It’s the git repo, clone it, use it and feel free to add your contributions to it.

I hope you guys learned everything about accessing the Cloudways API. If you found anything difficult, don’t forget to visit the API Documentation for complete details. You can find all the documentation at Developers Portal. You can also leave a comment below and we’ll get back with a solution for you.

Share your opinion in the comment section. COMMENT NOW

Noor Ali

Noor Ali is an Associate Software Engineer at Cloudways. He loves to solve technical problems through programming and mathematics.

Start Growing with Cloudways Today.

Our Clients Love us because we never compromise on these

Get Our Newsletter
Be the first to get the latest updates and tutorials.

THERE’S MORE TO READ.