Paginating in Constant Contact API

Some services of Constant Contact API return only a subset of results and you’re supposed to submit additional requests with a “next” parameter to fetch more. The implementation isn’t exactly straight forward though, and for some reason, CtCt doesn’t provide any pagination code sample. So here it is, for getContactsFromList().

You can either use ListService directly, or through an overarching ConstantContact object. Note that the $limit parameter will actually return $limit + 1 contacts. The max value of 500 will yield 501 contacts.

with ConstantContact object

  1. /** @var Contact[] $contacts */
  2. $contacts = array();
  3.  
  4. $client = new ConstantContact($apiKey);
  5. $param = $limitPerRequest;
  6. while (true) {
  7.   $result = $client->getContactsFromList($accessToken, $listId, $param);
  8.   if (empty($result->results)) {
  9.     break;
  10.   }
  11.  
  12.   $contacts = array_merge($contacts, $result->results);
  13.  
  14.   if (!$result->next) {
  15.     break;
  16.   }
  17.   $param = $result->next;
  18. }
  19.  
  20. return $contacts;
  21.  

ListService directly

  1. $service = new ListService($apiKey);
  2.  
  3. $params = array(‘limit’ => $limitPerRequest);
  4. while (true) {
  5.   $result = $service->getContactsFromList($accessToken, $listId, $params);
  6.   if (empty($result->results)) {
  7.     break;
  8.   }
  9.  
  10.   $contacts = array_merge($contacts, $result->results);
  11.  
  12.   if (!$result->next) {
  13.     break;
  14.   }
  15.   parse_str(ltrim($result->next, ‘?’), $params);
  16. }
  17.  

3 Responses to “Paginating in Constant Contact API”

  1. Hi Petra,

    I write the API docs for the CTCT v2 API. I’m wondering if you would allow me to use your code samples in our documentation, with due credit provided?

    Thanks,
    Rich

  2. Oh absolutely. I’m glad that you want to improve the documentation. Let me know if I can help.

  3. Matt L. says:

    Your w/CC object code is just a bit off. With the APIv2 php wrapper, simply setting the $param = $result->next; is incorrect and results in an exception. What’s really expected there is either an integer or a bit of a URL query string, so you need to do this:

    $param = “?next=” . $result->next;

    so the param looks like that bit of a query string. Just passing in the next variable from the response isn’t quite enough.

    Thanks.

Leave a Reply