According to the official API documentation, you can reboot a droplet with the following curl
request:
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer API_TOKEN_HERE" \
-d '{"type":"reboot"}' \
"https://api.digitalocean.com/v2/droplets/DROPLET_ID_HERE/actions"
To do the same thing with PHP you could use the following script:
<?php
// Update your API Token and Droplet ID here:
$api_token = 'YOUR_TOKEN_HERE';
$droplet_id = 'YOUR_DROPLET_ID_HERE';
$data = array("type" => "reboot");
$data_string = json_encode($data);
$ch = curl_init('https://api.digitalocean.com/v2/droplets/' . $droplet_id . '/actions');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . $api_token,
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
print_r($result);
?>
Quick rundown:
- We first specify our API key and our Droplet ID as variables
- We then specify the action that we would like to execute, in our case just a reboot
- Then by the help with
curl_init
we prepare our URL, note that you would need to install php-curl
in order to be able to do so
- With
curl_setopt
we build up our CURL request
- Lastly with
curl_exec
we trigger the POST request
- With the
print_r($result);
we print the result back
As an example I will use this Python module to manage digitalocean.com droplets:
https://www.digitalocean.com/community/tools/python-digitalocean
So just install it using php:
pip install -U python-digitalocean
Then the script would look something like this:
import digitalocean
manager = digitalocean.Manager(token="YOUR_TOKEN_HERE")
droplet = manager.get_droplet(droplet_id="YOUR_DROPLET_ID_HERE")
droplet.reboot()
For more information on how to use the DigitalOcean API with Python check the following tutorial:
https://www.digitalocean.com/community/tutorials/how-to-use-web-apis-in-python-3
This would be quite similar to the plain curl
command but the benefit is that we could add some variables, comments and etc.
#!/bin/bash
##
# Variables
##
API_TOKEN=YOUR_TOKEN_HERE
DROPLET_ID=YOUR_DROPLET_ID_HERE
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer ${API_TOKEN}" \
-d '{"type":"reboot"}' \
"https://api.digitalocean.com/v2/droplets/${DROPLET_ID}/actions"
If you have any other suggestions or examples, please feel free to share them here!
Regards,
Bobby