I am unable to get more than 500 conatcts through java API

First-NameL1650
Occasional Participant

I am unable to get more than 500 conatcts through java API

Hello Team, We are using Constant contact Java API.It is very use full for us and we are very impressed with this Java API.But we are facing small issue while retrieving all contacts. We are unable to get more than 500 contacts using java API.Can you please provide code or process to meet this requirement. Thanks Santosh Kola Email:

15 REPLIES 15
Elijah_G
Member

Hello,

 

In this case what's happening is that since there are more than 500 results, the data that comes back from the API is paginated. You could handle this using the PaginationHelperService class as follows:

 

// Set up the service factory
ConstantContactFactory _serviceFactory = new ConstantContactFactory("ACCESS_TOKEN","API_KEY");

// Create the PaginationHelperService
PaginationHelperService _pagingService =  _serviceFactory.createPaginationHelperService();

// Create the ContactService
IContactService _contactService = _serviceFactory.createContactService();


// Define a place to store results per page, as well as aggregated contacts.
ResultSet<Contact> results;
List<Contact> contacts = new ArrayList<Contact>();

try {
    // Get the first page of contacts.
    results = _contactService.getContacts(500, null, null);

    // Store the first page of contacts.
    contacts.addAll(results.getResults());

    // As long as there continue to be more pages, keep fetching them
    while (results.getMeta().getPagination() != null) {
        results = _pagingService.getPage(results.getMeta().getPagination(), Contact.class);
        // Store the contacts as we fetch them
        if (results.getResults() != null) {
            contacts.addAll(results.getResults());
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

// Once the loop terminates, the List "contacts" will contain all contacts.

 

If you have any questions, please let me know! As a note, this code may not directly build, as I had to write this at the end of the day and haven't had a chance to properly test it. If there's any issues, I should be available Monday to correct them!

 

EDIT: The code in this post has been updated and tested

 

Sincerely,

Elijah G.
API Support Engineer
First-NameL1650
Occasional Participant

Elijah G.

Good Morning,

Thanks for your replay.We have used your given code but getting compile time error in below line.Because of last parameter i.e Contact . Can you please suggest  how that object should be declared and initialized.

 

 results = _pagingService.getPage(results.getMeta().getPagination(),Contact);

 

Thanks,

Santosh Kola.

Hello,

 

I had made a couple of minor mistakes when I built the original code due to the lack of time available to build and test it. I've updated the code in my previous post with code that has been built and tested. Please let me know if you have any trouble with it!

 

Sincerely,

Elijah G.
API Support Engineer
First-NameL1650
Occasional Participant

Good Morning Elijah,

Thanks for your help.Now Its working fine and we are getting total contacts.Can you please give me the solution for below query.

 

could you please clarify my doubt regarding deleting contact permanantly from the constant contact account through java api call so that those contact shouldn't come under billing.
Actually we are using


ContactService cs = new ContactService(Api_Key, Access_Tocken);
 cs.deleteContactFromList(contactId, listId);
 
 but the contact is not deleted permanantly only the status changed to Removed .so we are getting problem that "Email is already existed" when we are trying to add new  contact with same email id .

 

Thanks for your excellent support till now.

 

Santosh Kola.

Hello Santosh,

 

The method that you are using to remove the contact from lists and billing is correct. However, it is important to know that even when deleting a contact in our UI, it is considered a soft delete. This is done to allow contacts to be restored and protect our users in case they were to accidentally delete important contact data.

 

When you are working with the API, the best process for adding contacts is to do the following:

 

Check if a contact with the desired email address already exists. You can do this using ContactService.getContactByEmail(String email). If there is a contact already using that email, the resultset will contain a single result.

 

If the contact already exists, simply update the existing contact with your new details and ensure that it is placed on at least one list. This will change the status back to active. Please note that if the contact is unsubscribed, this can only be done by setting the actionByVisitor flag to True, and should only be done when the API action is a direct result of an action by the contact in question (a signup form is a good example). For this action you will use ContactService.updateContact(Contact contact, Boolean actionByVisitor).

 

If the contact does not yet exist, you can create a new contact. Please note that when creating a new contact, a welcome email will only be sent if the actionByVisitor flag is set to True. For this action you will use ContactService.addContact(Contact contact, Boolean actionByVisitor).

 

 

If you have any questions or if I can clarify, please let me know!

 

Sincerely,

Elijah Gaiter

API Support Engineer

Elijah G.
API Support Engineer
TriveniN
Regular Participant

Hello Elijah,

It means when we delete a contact through java api using deleteContactFromLists(contact Id) method , it will changed status into REMOVED..
Now my doubt is removed(Status Removed) contacts will comes under billing or not ?

 

Please clarify my doubt.

Thanks You,

Trivani.

Hello Trivani,

 

Any contact with the following status is not billable:

  • REMOVED
  • OPTOUT

 

Please let me know if you have any additional questions that I can help with!

 

Sincerely,

Elijah G.
API Support Engineer
TriveniN
Regular Participant

Hello Elijah,

 

Thanks for your support till now.Can you please give me the solution for below query.

 

Can we have chance of adding bulk of contacts to a constant contact list at once ?

 

Actually we are receiving all contacts in result set from database and we are adding to constant contact list one by one from that Result Set  through java api but while adding contact in iteration of result set...

 

i am getting "java.net.SocketTimeoutException: Read timed out" exception in the middle but we want to add all the contacts that are in resul set without any exception.

 

Could you please help me regarding this issue.

 

Thank you,

Triveni.

 

 

Hello,

 

It is absolutely possible to import contacts in bulk. You can find a sample that I created for another developer to demonstrate the process here:

https://community.constantcontact.com/t5/Developer-Support-ask-questions/Sample-Java-Application/m-p...

 

Please let me know if you have any questions!

 

Sincerely,

Elijah G.
API Support Engineer
TriveniN
Regular Participant

Hello Elijah,

 

Thanks for your excellent support till now. Can you please give me the solution for below query.

 

Can we have any method for checking whether ContactList is existed or not using java api ?

 

Requirement :

We need to add Contact List through Java API with Unique List name..But If I try to add Contact List with existed name Its throwing Exception.

 

So We need to check wheather ContactList name is existed or not before adding the ContactList.

 

Thank You,

triveni

 

 

 

 

 

 

Hello,

 

In order to solve this issue, there are two options:

 

  1. Get the collection of all contact lists (up to 1000) and search for the list name you wish to use. This can be done using the ListService.GetLists() method.
  2. Attempt to create the list and specifically catch the exception that is thrown when it already exists (status code 409). 

 

I would personally advocate option #2, as it will save you a step if the list name is already unique, and it produces a predictable outcome when the list is not unique, allowing you to handle that situation as well.

 

If you have any questions, please let me know!

 

Sincerely,

Elijah G.
API Support Engineer
TriveniN
Regular Participant

Hello Elijah,

 

Thanks for your great support till now. Can you please give me the solution for below query.

 

Actually i am retriving all the EmailCampaigns for getting all its "name" ,"lastRunDate", "status", and  (TrackingSummary for getting number of  {sends, opens, clicks, forwards, unsubscribes, bounces} through java API with this code.

 

ConstantContactFactory _serviceFactory = new ConstantContactFactory("Access_token", "Api_key");


PaginationHelperService _pagingService = _serviceFactory.createPaginationHelperService();


IEmailCampaignService iEmail_Camp_Ser= _serviceFactory.createEmailCampaignService();


ResultSet<EmailCampaignResponse> resEcs ;


List<EmailCampaignResponse> Email_Cam_Res_list = new ArrayList<EmailCampaignResponse>();


resEcs=iEmail_Camp_Ser.getCampaigns(50, null);


System.out.println(resEcs.get(0));


Esr.addAll(resEcs.getResults());


while (resEcs.getMeta().getPagination()!= null) {


resEcs = _pagingService.getPage(resEcs.getMeta().getPagination(), EmailCampaignResponse.class);
// Store the contacts as we fetch them

if (resEcs!=null&&resEcs.getResults()!= null) {


Email_Cam_Res_list .addAll(resEcs.getResults());


}else break;


}

 

for (int ld = 0; ld < Email_Cam_Res_list .size(); ld++) {


System.out.println("Email Campaign Id ------>"+Email_Cam_Res_list .get(
ld).getId());

 EmailCampaignResponse resE = Email_Cam_Res_list .get(
ld);

 

System.out.println(resE.getName());


TrackingSummary ts = resE.getTrackingSummary();

System.out.println(ts.getOpens());


System.out.println(ts.getBounces());
}

 

here we are getting all its names but for remaining we are getting null.

 

And we getting all values if we create EmailCampaignResponse object with respertive id.

 

like:-

 

  EmailCampaignResponse resE = iEmail_Camp_Ser.getCampaign(Email_Cam_Res_list .get(ld).getId());

 

by appling like this is take lot of time for execution as we are creating EmailCampaignResponse again with id.

 

So could please help to slove this problem.

 

Thanks

triveni.

 

 

 

 

 

Hello,

 

The problem you are seeing is happening because the collection of email campaigns only provides the following 4 fields:

  • id
  • name
  • status
  • modified_date

 

In order to get additional details it is required to use the getCampaign method as you showed at the end of your post. Depending on your use case, it may be most effective to perform a one-time download of the data you need for all campaign and then use a modified_since filter to collect only data about campaigns within the last X days. You can do this with the "modifiedSinceTimestamp" parameter in the getCampaigns method.

 

Other than the above proposed process, the only option would be to individually get the details for each campaign every time, which can be very time consuming for accounts with a large number of campaigns.

 

If you have any questions or if I can provide any guidance, please let me know!

 

Sincerely,

Elijah G.
API Support Engineer

Hello Elijah,

 

Thanks for your great support, and could you please  clarify us regarding below exception, that occurs when creating Email Campaign Using Java API. and plese provide us with required solution.

 

json.payload.contains_invalid_characters : The request contains text outside supported character set.

 

Below is our code in java.

 

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

 

EmailCampaignRequest emailReq=new EmailCampaignRequest();
emailReq.setName("Campign");
emailReq.setSubject("REG :Campign");
emailReq.setFromEmail("XXX@xxx.com");
emailReq.setFromName("XXXXX");
emailReq.setReplyToEmail("XXX@xxx.com");
emailReq.setStatus("DRAFT");
emailReq.setViewAsWebpageEnabled(false);
emailReq.setGreetingName("FIRST_NAME");
emailReq.setGreetingSalutations("Hello");
emailReq.setGreetingString("Dear");
emailReq.setEmailContent("<html xmlns='http://www.w3.org/1999/xhtml'><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'><meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0;' name='viewport'><link rel='stylesheet' type='text/css' href='//fonts.googleapis.com/css?family=Open+Sans'><body></body></html>");
emailReq.setEmailContentFormat("HTML");
emailReq.setTemplateType("CUSTOM");
emailReq.setTextContent("test");
MessageFooter messageFooter =new MessageFooter();
messageFooter.setAddressLine1("XXXXXXX");
messageFooter.setOrganizationName("xxxx");
messageFooter.setCity("xxx");
messageFooter.setCountry("US");
messageFooter.setState("MA");
messageFooter.setPostalCode("01444");
emailReq.setMessageFooter(messageFooter);
List<SentToContactList> scl=new ArrayList();
SentToContactList stcl=new SentToContactList();
stcl.setId(contactId);
scl.add(stcl);
emailReq.setSentToContactLists(scl); System.out.println(emailReq.toJSON().toString());
EmailCampaignResponse errs= ecs.addCampaign(emailReq);

 

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

Actually it is working fine when we run in our console application , but we are getting exception when we include in our project.

Please provide me requied solution.

 

Thanks.

 

Triveni

 

Hello Triveni,

Thank you for reaching out to the API Support team here at Constant Contact.

When I POST a new email campaign to my own account using a REST client with the information you provided as my content, I did not get an error back. This error usually occurs when you are using special characters in your campaign such as an elipsis (…).

 

I would be happy to troubleshoot this with you. Please send an email to webservices@constantcontact.com with the actual data that you are submitting when you see this error. This way we can troubleshoot with your specific details while not exposing them publicly. I see in your code you are outputting your JSON to a string in your console. Would you be able to include that as well? That way I can have the best chance at finding what could be causing the issue.

 

Also, you mentioned that you are using our Java API -- please also note if you are using version 4 or the new version 5 of our Java SDK.

 

Sincerely,
David B.
API Support Specialist

Developer Portal

View API documentation, code samples, get your API key.

Visit Page