How to call do api with php?

December 25, 2015 960 views

In the manual

curl -X GET -H 'Content-Type: application/json' \
-H 'Authorization: Bearer '$TOKEN'' \

This will return the requested action object:

"action": {
"id": 36805022,
"status": "completed",
"type": "snapshot",
"startedat": "2014-11-14T16:34:39Z",
at": "2014-11-14T16:38:52Z",
"resourceid": 3164450,
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.


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.

//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 
Have another answer? Share your knowledge.