While working on a little PHP project involving the use of the DigitalOcean V2 API to create and manage droplets.

The DigitalOcean V2 API is a fully RESTful API. This made interacting with it very easy.

Looking at the documentation for the API, you can see some example usage being done by using cURL. Just send the required http request to the correct url and retrieve the JSON data.

Guzzle

When using PHP, cURL requires setting the correct options on each request, so it is not really good to be repeating this for each call you want to make to the API. Enter Guzzle.

Taken from the Guzzle website.

Guzzle is a PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services.

Guzzle supports both basic HTTP authentication and OAuth authentication. I will only be going over the basic authentication as I was unable to get the OAuth setup to work with the DigitalOcean API.

Installing Guzzle

Guzzle can be installed using composer.

Add the following requirements to your composer.json file.

{
    ...
    "require": {
        ...
        "guzzlehttp/guzzle": "4.*"
        ...
    }
}

Once installed, you can begin to use guzzle.

Make sure that you have included composers vendor/autoload.php file in your project.

Creating a Client

Guzzle works by creating a client that runs any calls on the API and returns a response object of the data and http status (along with other things).

Creating a client is nice and easy.

<?php
use GuzzleHttp\Client;

$digitalOcean = new Client([
    'base_url' => 'http://api.digitalocean.com/v2/
]);

We now have a client that can run our requests. You will notice the base_url option when creating an instance of the client. This is optional, but helps when the client is only going to be using a single base url.

Querying the API

Now we have a client created, we can use it to run requests against the API. This is as simple as calling a method with the same name as the HTTP request you wish to run on the API. For example, calling the $client->get('path') method would send a HTTP GET request.

HTTP Basic Authentication

Using HTTP Basic authentication is very easy with Guzzle. Just pass in your authentication paramaters to the method you are calling.

$request = $digitalOcean->get('droplets', ['auth' => ['username', 'password']]);

This works slightly differently with the DigitalOcean API, as there is no password.

$request = $digitalOcean->get('droplets', ['auth' => [$apiToken, ':']]);

DigitalOcean requires that we send our API token as the username, and a colon : as the password.

Note that we can also pass this information into the client when we create it.

$digitalOcean = new Client([
    'base_url' => 'http://api.digitalocean.com/v2/',
    'defaults' => [
        'auth' => [
            'username',
            'password'
        ]
    ]
]);

Retrieving Data

Guzzle includes methods to process any data returned from the API in JSON or XML format. It is also able to return the body of the response if you are not expecting JSON or XML.

// Authentication is set in the client.
$request = $digitalOcean->get('droplets');

// Retrieve the status code of the request.
$statusCode = $request->getStatusCode();

// Check that the request is successful.
if ($statusCode >= 200 && $statusCode < 300) {
    $json = $request->json(); // Returns JSON decoded array of data.
    $xml = $request->xml(); // Returns XML decoded array of data.
    $body = $request->getBody(); // Returns the raw body from the request.
}

Now we could loop through the returned array of data, or process the body how ever we want.

Retrieving All Droplets

Lets use what we have learnt from above and retrieve a list of our droplets from the DigitalOcean API.

First, create the client.

<?php
use GuzzleHttp\Client;

$digitalOcean = new Client([
    'base_url' => 'http://api.digitalocean.com/v2/',
    'defaults' => [
        'auth' => [
            'myapitoken',
            ':'
        ]
    ]
]);

Now, run a request on the droplets path.

$request = $digitalOcean->get('droplets');

As we know the DigitalOcean API returns JSON, we can run the json() method on the returned data.

$droplets = $request->json();

Now we can loop through the array of data and output the names of our droplets. (As well as much more information, see the API Documentation.)

$status = $request->getStatusCode();

if ($status >= 200 && $status < 300) {
    foreach ($droplets as $droplet) {
        var_dump($droplet['name']);
    }
}

If you have 3 droplets, with the names Droplet1, Droplet2 and A-Droplet, you should see some data similar to below.

string 'Droplet1' (length=8)
string 'Droplet2' (length=8)
string 'A-Droplet' (length=9)

Note: I have XDebug Installed to recieve this var_dump output.

Sending Data

Using the same approach as above, we can now request data from other areas of the API. But what if we want to send data to the api? Well, this is also nice and easy.

To do this, we just pass the data into the options for the method being called.

So to create a droplet, we would do the following.

$request = $digitalOcean->post('droplets', [
    'json' => [
        'name' => 'MyNewDroplet',
        'region' => 'ams2',
        'size' => '512mb',
        'image' => 449676388 // Image ID's can be found by using the Images API.
    ]
]);

$droplet = $request->json();

When run, this will create a new 512mb droplet in the amsterdam2 region with the name of MyNewDroplet using the image id provided. It will also return any data for the new droplet. $droplet will have the same data as running a get request to droplets/{dropletid} when you have the id of the newly created droplet.

Other API Actions

Using what we have learnt above, we can now use the DigitalOcean V2 RESTful api to its full extent. We should also be able to use most other RESTful API's, such as Facebook or Twitter.

Resources Used

As usual, if you have any questions or comments, feel free to leave them in the comments section below.

© 2017. All Rights Reserved.