elearn
By:
elearn

How to call do api with php?

December 25, 2015 12k views
PHP

In the manual
https://www.digitalocean.com/community/tutorials/how-to-use-and-understand-action-objects-and-the-digitalocean-api

curl -X GET -H 'Content-Type: application/json' \
-H 'Authorization: Bearer '$TOKEN'' \
"https://api.digitalocean.com/v2/actions/36805022"

This will return the requested action object:

{
"action": {
"id": 36805022,
"status": "completed",
"type": "snapshot",
"startedat": "2014-11-14T16:34:39Z",
"completed
at": "2014-11-14T16:38:52Z",
"resourceid": 3164450,
"resource
type": "droplet",
"region": "nyc3"
}
}

How to get the same output with pure php code?

1 Answer

There is already a library that you can call to interact with the DO v2 API.

You can find it below on GitHub and should be well documented.

https://www.digitalocean.com/community/projects/api-v2-client-in-php
https://github.com/toin0u/DigitalOceanV2

If you still want to write pure PHP code, you can use the curl libraries within PHP to make the calls.

Reference: http://php.net/manual/en/book.curl.php
cURL options: http://php.net/manual/en/function.curl-setopt.php
Examples: http://php.net/manual/en/curl.examples.php

A great example function translated from the CLI cURL you have in your question is provided below as well.

<?php
//setup the request, you can also use CURLOPT_URL
$ch = curl_init('https://api.digitalocean.com/v2/actions/36805022');

// Returns the data/output as a string instead of raw data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Good practice to let people know who's accessing their servers. See https://en.wikipedia.org/wiki/User_agent
curl_setopt($ch, CURLOPT_USERAGENT, 'YourScript/0.1 (contact@email)');

//Set your auth headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Authorization: Bearer ' . $TOKEN
    ));

// get stringified data/output. See CURLOPT_RETURNTRANSFER
$data = curl_exec($ch);

// get info about the request
$info = curl_getinfo($ch);

// close curl resource to free up system resources 
curl_close($ch)
?>
Have another answer? Share your knowledge.