I am trying to send POST requests to Digitalocean's API v2 with cURL and custom headers but it is not working. I don't get any response, or the output/response I get is only:
Response from API:
My php code is:
<?php
$TOKEN = "digitalocean api token";
$headers = array("Authorization: Bearer $TOKEN","Content-Type: application/json",);
$name = "Test"; //droplet name
$region = "nyc2"; //region
$size = "512mb"; //size
$image = "303022"; //replace it
$user_data = "#!/bin/bash apt-get install nginx -y";
$postData = array(
'name' => $name,
'region' => $region,
'size' => $size,
'image' => $image,
'user_data' => $user_data,);
$post_body = '';
foreach($postData as $key => $value) {
$post_body.= urlencode($key) . '=' . urlencode($value) . '&';
}
$post_body = rtrim($post_body, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, "https://api.digitalocean.com/v2/droplets");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_body);
$result = curl_exec($ch);
echo "Response from API: $result";
?>
Please tell me what's wrong in it? I have error reporting enabled.
$postDataarray tocurl_setopt($ch, CURLOPT_POSTFIELDS, $postData);? No need to process it that way. You're also missing acurl_closecall at the end, and you really should be passing the authentication stuff as CURL options, not in the headers array (see the manual for the options that allow you to do all this)http_build_queryfunction for that:curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));CURLOPT_POSTFIELDS: If value is an array, the Content-Type header will be set to multipart/form-data.