How to PHP cURL to SurveyMonkey API?

1.6k views Asked by At

I am trying to use PHP cURL to retrieve some data from SurveyMonkey's API and I keep getting a 500 error.

Here is my code:

  $requestHeaders = array(
    'Content-Type: application/json',
    'Authorization: Bearer ' . $accessToken,
  );

  $baseUrl = 'https://api.surveymonkey.net';
  $endpoint = '/v2/surveys/get_survey_list?api_key=XXXXXXXXXXXXXX';

  $fields = array(
    'fields' => array(
      'title','analysis_url','date_created','date_modified'
    )
  );

  $fieldsString = json_encode($fields);

  $ch  = curl_init();
  curl_setopt($ch, CURLOPT_URL, $baseUrl . $endpoint);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsString);

  $result = curl_exec($ch);

  curl_close($ch);

The response I get is

{
    "status": 500,
    "request_id": "e0c10adf-ae8f-467d-83af-151e8e229618",
    "error": {
        "message": "Server busy, please try again later."
    }
}

This works perfectly on the command line:

curl -H 'Authorization:bearer XXXXX' 
     -H 'Content-Type: application/json' https://api.surveymonkey.net/v2/surveys/get_survey_list/?api_key=XXXXXXXX 
--data-binary '{"fields":["title","analysis_url","date_created","date_modified"]}'

Thanks!

1

There are 1 answers

2
Elliot B. On BEST ANSWER

You were close, but there are a couple small mistakes.

First, while you do specify the Content-Type correctly (application/json), you have not specified the Content-Length.

Make this change to $requestHeaders and move it below the creation of $fieldsString:

$requestHeaders = array(
     'Content-Type: application/json',
     'Authorization: Bearer ' . $_GET['code'],
     'Content-Length: ' . strlen($fieldsString)
);

Second, you have set CURLOPT_POST to true. This will force CURL to treat your request as a form POST which has a content-type of application/x-www-form-urlencoded. This will create a problem because SurveyMonkey is expecting the content-type application/json.

Remove this:

curl_setopt($ch, CURLOPT_POST, true);

and replace it with this:

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");