Search code examples
phpcurlpostrequestgodaddy-api

Using curl to post an array to the godaddy api


I am trying to post a bunch of domains to the godaddy api in order to get information about pricing and availability. However, whenever I try to use curl to execute this request, I am returned nothing. I double checked my key credentials and everything seems to be right on that end. I'm pretty confident the issue is in formatting the postfield, I just don't know how to do that... Thank you to whoever can help in advance!

$header = array(
  'Authorization: sso-key ...'
);


$wordsArray = ['hello.com', "cheese.com", "bytheway.com"];
$url = "https://api.godaddy.com/v1/domains/available?checkType=FAST";


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false); 
curl_setopt($ch, CURLOPT_POST, true); //Can be post, put, delete, etc.
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $wordsArray);

$result = curl_exec($ch);  
$dn = json_decode($result, true);
print_r($dn);

Solution

  • There are two problems in your code:

    1. Media type of sent data must be application/json (by default this is application/x-www-form-urlencoded), and your PHP app must accept application/json as well:
    $headers = array(
        "Authorization: sso-key --your-api-key--",
        "Content-Type: application/json",
        "Accept: application/json"
    );
    
    1. Post fields must be specified as JSON. To achieve this, use the json_encode function:
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($wordsArray));
    

    Full PHP code is:

    $headers = array(
        "Authorization: sso-key --your-api-key--",
        "Content-Type: application/json", // POST as JSON
        "Accept: application/json" // Accept response as JSON
    );
    
    
    $wordsArray = ["hello.com", "cheese.com", "bytheway.com"];
    $url = "https://api.godaddy.com/v1/domains/available?checkType=FAST";
    
    
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($wordsArray));
    
    $result = curl_exec($ch);
    
    $dn = json_decode($result, true);
    print_r($dn);