Quick tutorial

Introduction

This tutorial provides a quick overview of how to get started by building a simple application. The tutorial is aimed at developers that will write applications using the API, and there will be quite a few code examples. The finished application is also available for you to download, so please download it, read the code and test it.

Access to APSIS API

The first step is that you need access to the APSIS API. This is an add-on feature of APSIS Pro. Contact your APSIS Account Manager or send an email to info@apsis.com to initiate activation.

Once you have REST API access, you need to create an API key from within APSIS Pro. Visit the "Getting started" section for more details about API keys.

What We Will Build

We will walk you through how to build a simple application that allows the user to list their mailing lists, create a new list and create subscribers on the list. The user will also be able to create newsletters and send a newsletter to a mailing list. This tutorial will showcase how to use the API from PHP, but you can use C#, Java, Python or whichever programming language you feel comfortable with. We will consistently request the API to return XML, even if we just as well could have used JSON.

Get a Mailing List

Let us get started by listing the existing mailing list in our account. This is done by calling the GetMailinglistsPaginated method. According to the method documentation, we need to call the following URL to use this method:

http://se.api.anpdm.com/v1/mailinglists/{PageNumber}/{PageSize}

PageNumber and PageSize allows us to divide all the mailing lists into smaller subsets. We can choose to return just 10 or 20 mailing list per request. For now, let us get the first page and set the page size to 10, which means that we will return the first ten mailing lists. That makes the URL we need to call:

http://se.api.anpdm.com/v1/mailinglists/1/10

To make the request, we need to specify a couple of things: our API key and in which format we want the response.

Let us begin with the API key. There are a couple of ways to set the API key. In this tutorial, we will use the HTTP Basic auth method, i.e. to send the API key as a username in the URL. If our API Key is "abc123", we need to use this URL to call the GetMailinglistsPaginated method:

http://abc123:@se.api.anpdm.com/v1/mailinglists/1/10

As a last configuration step of the API request, we need to define in which format we want the response. Our choices are XML or JSON. This is set in an HTTP Header when making the request. The header is "Accept" and it should be set to "text/xml" to get XML back, or "application/json" to get JSON back. In this tutorial, we will always request XML � even though we just as well could have used JSON.

Using PHP to implement this API call includes using cURL to make an HTTP request and then parse the response using https://php.net/manual/en/book.simplexml.php . If we would have used JSON, the response could be parsed using json_decode(). This is the PHP code needed to call the GetMailinglistsPaginated method:

$ch = curl_init(http:abc123:@se.api.anpdm.com/v1/mailinglists/1/10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: text/xml'
));
$result = curl_exec($ch);
curl_close($ch);
$result_as_an_object = new SimpleXMLElement($result);


In the complete PHP application tutorial, this call is made from the ApsisApiMethods class in the apsis_api_methods.php file. The function get_mailing_lists_paginated() in turn uses the get() function from the ApsisApi class in the apsis_api.php file, and it is this method that implements the actual cURL call. This makes the code as reusable as possible, and you can easily just add new methods in the ApsisApiMethods class without having to touch the code that makes the actual API call. The data returned from this API call will be something along the line of:

<?xml version="1.0" encoding="utf-16"?>
<Response xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <Code>1</Code>
        <Message>Successfully retrieved paginated mailing lists</Message>
        <Result>
        <TotalCount>2</TotalCount>
        <TotalPages>1</TotalPages>
        <Items>
        <MailingListSummaryItem>
        <Created>2011-10-11T09:43:07.637Z</Created>
        <FolderId>0</FolderId>
        <Id>1111</Id>
        <Name>My mailinglist</Name>
        <Updated>2011-10-11T09:43:07.637Z</Updated>
        </MailingListSummaryItem
        <MailingListSummaryItem>
        <Created>2011-10-11T13:17:46.957Z</Created>
        <FolderId>0</FolderId>
        <Id>2222</Id>
        <Name>My other mailinglist</Name>
        <Updated>2011-10-11T13:17:46.957Z</Updated>
        </MailingListSummaryItem>
        </Items>
        </Result>
</Response> 


This response follows the same structure as all APSIS API responses. There is a Code that informs us of the status of the request (1 = Successful), a Message that is a readable status message and a Result that contains the actual data of the response. After parsing this XML with SimpleXML, we have a PHP object that we can use in our code. This is how we can get an array of mailing lists:

$mailing_lists = $result_as_an_object->Result->Items->MailingListSummaryItem;

Then it is easy to loop through all mailing lists and print out their name etc. This is all done in the mailing_lists.php file.

Note that GetMailinglistsPaginated only returns a subset of all existing mailing lists depending on the request parameters and the number of mailing lists. Use the queued method GetAllMailingLists if you want to retrieve all of the mailing lists that belong to an account.

Create a Mailing List

At the starting point, we do not have any mailing lists, so let us add the functionality needed to add a new mailing list. This is done with the CreateMailinglist API method. This method is slightly different than the previously used GetMailinglistsPaginated method as the CreateMailinglist is a POST method, that is called using HTTP POST since we are creating new data on the account. GetMailinglistsPaginated was called with a HTTP GET since the purpose was to retrieve data.

To call CreateMailinglist, we need to use this URL:

http://se.api.anpdm.com/v1/mailinglists/

We also need to specify some body parameters. These are parameters set in the body of the POST request in either an XML format or in JSON. This is an example of how an XML formatted body could look like:

<CreateMailinglist xmlns:i="http://www.w3.org/2001/XMLSchema-instancepan">
        <CharacterSet>utf-8</CharacterSet>
        <Description>This is the mailinglist for the next campaign</Description>
        <FolderID>0</FolderID>
        <FromEmail>eldlabs@hotmail.com</FromEmail>
        <FromName>John Andersson</FromName>
        <Name>Next campaign</Name>
        <ReplyToEmail>eldlabs@hotmail.com</ReplyToEmail>
</CreateMailinglist>

Since we are sending either XML or JSON in the request body, we need to set the Content-Type HTTP header to tell the API server which format we are using. Set it to either "text/xml" or "application/json" depending on which format you are sending. The PHP code to do this API call is quite similar to the code above, but we need to specify how that HTTP POST should be used as well as to set the body and the Content-Type header. Assuming we already have a parameter called $body containing the XML we can make the request with this PHP code:

$ch = curl_init(http://abc123:@se.api.anpdm.com/v1/mailinglists/);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: text/xml',
        'Accept: text/xml'
        ));
$result = curl_exec($ch);
curl_close($ch);


Once again with a Code, Message and Result. This time the Result contains the ID of the newly created Mailing List. This is implemented in the mailing_lists.php file using a simple HTML form to allow users to specify the parameters of the new mailing list.

Create Subscribers

A mailing list needs subscribers. Listing subscribers for a mailing list is easily done with the GetMailinglistSubscribersPaginated method, similar to the previously mentioned GetMailinglistsPaginated method. However, creating subscribers is a bit different since the CreateSubscribers method is a "queued" method. That means that the subscribers are added in batches on the server and the result might not be immediate. The purpose of using queued API methods is to reduce the load on APSIS Pro and to minimise the risk of a timeout, especially since an API call could potentially return hundreds of thousands of rows of data.

To call CreateSubscribers, an HTTP POST should be sent to:

http://se.api.anpdm.com/v1/subscribers/queue

The data of all the Subscribers we will create are defined in the body of the POST request like this:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfCreateQueuedSubscriber xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <CreateQueuedSubscriber>
        <CountryCode>UK</CountryCode>
        <DemDataFields>
        <DemDataField>
        <Key>Gender</Key>
        <Value>Male</Value>
        </DemDataField>
        </DemDataFields>
        <Email>eldlabs@apsis.com</Email>
        <Format>html</Format>
        <MailingListID>12345</MailingListID>
        <Name>John Andersson</Name>
        <Password>Summer2011</Password>
        <PhoneNumber>0734150000 </PhoneNumber>
        <CountryCode>46</CountryCode>
        </CreateQueuedSubscriber>
</ArrayOfCreateQueuedSubscriber>

In this example, only one user named John Andersson will be created. This POST request is made in the same way as the CreateMailinglist call above. The difference is in what the API call returns:

<?xml version="1.0" encoding="utf-16"?>
<Response xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <Code>1</Code>
        <Message>OK</Message>
        <Result>
        <OperationGuid>23f9435a-bf52-4190-8ae2-63daf05a39ec</OperationGuid>
        <PollURL>http://se.api.anpdm.com/v1/........xml</PollURL>
        </Result>
</Response>

The response contains Code, Message and Result as usual. However, the Result does not contain information about how the operation went, since this has not yet been executed by the server. Instead, it contains a PollURL, which is a URL that we need to call until the server has created the subscribers. Calling the PollURL is done with HTTP GET, i.e. in the same way as GetMailinglistPaginated above, and the response looks like this:

<StatusDocumentItem xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <DataUrl>http://se.api.anpdm.com/data/5f1a08e8-33cc-4021-84e7-a2c5d4f5474e_result.xml</DataUrl>
        <LastUpdated>2011-10-12T09:14:37.9309713Z</LastUpdated>
        <Message>The processing of this task is completed</Message>
        <State>2</State>
        <StateName>Completed</StateName>
</StatusDocumentItem>

If there are a lot of subscribers added, the State might be set to 1, which means that the operation has started but is not yet completed. However, the state we are looking for is 2, which means the operation is completed. Keep calling the PollURL until you get either a completed operation or an error. Best practice is to call the PollURL with longer and longer pauses between each call and to set a limit to the number of calls made. Otherwise, your application might keep polling � even if something would go wrong.

This is an example of how the polling can be implemented in PHP:

<?php
$i = 0;
do {
  sleep($i);
  $response = $this->get_url($url); 

        if ($response->State == 2)
        {
        if (!empty($response->DataUrl))
        {
      $data_url = $response->DataUrl;
        }

        break;
        }
} while (++$i < 10); 
?>

The polling is done a maximum of 10 times with increasing pauses between each poll: from 0 to 9 seconds. If this code would be used in production, we should continue polling for up to an hour or two, since this is how long Queued methods might take.

Once the state is completed, we need to make a GET request to the DataUrl returned from the polling. This is the URL that contains the actual result and the return data from the API call. There we will find information if some subscribers failed to be created and if so � why.

To sum it up, calling a queued method requires that we:
  1. Make a POST request to the API method's URL.
  2. Retrieve the PollURL from the response and keep polling that URL with a HTTP GET until you get a completed or an error.
  3. And, once the operation has completed you can get the data about the operation by making a GET request to the DataURL.

Newsletters

We can implement the listing and creation of newsletters the same way that we did of Mailing Lists. Just use the CreateNewsletter and the GetNewslettersPaginated methods. Once we have a mailing list with at least one subscriber and we have created a newsletter, we can send it to the mailing list by using the SendNewsletter method.

Please view the complete PHP tutorial application and the API documentation for details about all of these method calls.

Summary

If you followed the above tutorial you should now have a simple PHP application that enables you to handle mailing list and newsletters, as well as sending the newsletter to our subscribers. As this is only a tutorial application, there is some more work needed before using it in production. This could be an error handling, being able to delete mailing list etc. The important thing is that we have touched upon all the major parts of the APSIS API. If you would like to test the PHP application, all you need is a server that can handle PHP and an APSIS API key (set in the apsis_api.php file). For more information about APSIS REST API, contact support@apsis.com.