Introduction to the Moosend API

Abstract

Introduction to the Moosend API and what topics are included in this API documentation.

Moosend is a cloud-based, AI-powered email marketing solution that allows you to target your audience at scale.

The API enables you to connect directly to the Moosend infrastructure and programmatically run many of the system’s capabilities from creating email lists to retrieving advanced real-time analytics in an easier, faster, and more efficient manner.

To get started, you need a Moosend  account and an API key. By accessing the API endpoints, you can programmatically leverage the system’s core capabilities:

Email lists

  • Create, retrieve, update, or delete email lists and their details.

  • Create or update custom data included in the email lists.

Subscribers

  • Add up to 1000 subscribers with their custom data or retrieve them by ID or email address.

  • Remove subscribers or unsubscribe them from an email list or a campaign.

Campaigns

  • Create or clone campaigns, and efficiently retrieve their details and campaign senders.

  • Send a test campaign, schedule campaign delivery, or dispatch it immediately.

  • Retrieve campaign metrics such as link performance, opens, clicks, and A/B test results to make data-driven decisions.

Segments

  • Create, update, delete, and retrieve segments with their details and subscribers.

Getting started with the Moosend API

Abstract

Overview of how to get started with the Moosend API.

Before you can start using the Moosend API, you must have a Moosend account. Each account is associated with a specific role, such as Owner, Admin, Viewer, Manager, Designer, Admin observer, and GDPR viewer. The permissions specific to your role determine which resources and endpoints you can access with your API key.

Base URL

Abstract

Describes the base URL for all Moosend API endpoints.

All API request URLs referenced in this API documentation begin with the following base URL:

https://api.moosend.com/v3

The base URL includes the {hostname} which is api.moosend.com and the API version v3.

To make a request to a specific API endpoint, the path to the endpoint is added to the base URL.

For example, to make a request to get all active email lists in your account, create a GET request and add the specific endpoint path /lists to the base URL:

https://api.moosend.com/v3/lists

Authenticate a Moosend API request

Abstract

Overview of the authentication process and how to get your API key from your Moosend account.

All Moosend API requests are authenticated by providing your API key. Moosend provides your account with a unique key that can be found in your settings.

To get your API key:

  1. Log in to your account.

  2. On the menu bar, click More > Settings.

  3. Click API key.

  4. To copy your API key, click Copy.

    Important

    You must keep your API key secure to prevent any unauthorized access to your account. You can click Generate new API key to create a new API key if your account gets compromised.

When you obtain your API key, you can begin making calls to the Moosend API. The API key is a required query parameter in all API endpoints.

For example, if your API key is bafe55f4-e53e-4651-8164-c6d6ff05081b, then a sample request to get all campaigns looks like the following:

curl --include \
'https://{hostname}/v3/campaigns.{Format}?apikey=bafe55f4-e53e-4651-8164-c6d6ff05081b'

HTTP methods

Abstract

Describes the standard HTTP methods to use when making calls to the Moosend APIs.

The Moosend API uses the following standard HTTP methods for indicating the action to take on available resources:

  • GET - you can use this method to retrieve data from your account in our system. When you make a GET request, all request parameters are added to the request URL, in a format specific to the API call.

    curl --include \
    'https://{hostname}/v3/campaigns.{Format}?apikey='
  • DELETE - you can use this method to remove information from your account.

    curl --include \
         --request DELETE \
    'https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey='
  • POST - you can use this method to send data to our system to modify data in your account. When you make a POST request, the request URL usually contains the response format and authentication, and the request stream contains hypothetical parameters for Name, Subject, SenderEmail, WebLocation, and MailingListID:

    curl --include \
         --request POST \
         --header "Content-Type: application/json" \
         --header "Accept: application/json" \
         --data-binary "{
        \"Name\":\"Test campaign\",
        \"Subject\":\"Some subject\",
        \"SenderEmail\":\"something@email.com\",
        \"ReplyToEmail\":\"something@email.com\",
        \"ConfirmationToEmail\":\"something@email.com\",
        \"HTMLContent\":\"Some HTML body\",      
        \"MailingLists\": [
            {
                \"MailingListID\":\"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",
                \"SegmentID\":\"10166\"
            },
            {
                \"MailingListID\":\"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"
            }
        ],
        \"IsAB\":\"true\",
        \"ABCampaignType\":\"Content\",
        \"WebLocationB\":\"http://www.mysite.gr/newsletter/index\",
        \"HoursToTest\":\"2\",
        \"ListPercentage\":\"20\",
        \"ABWinnerSelectionType\":\"OpenRate\"
    }" \
    'https://{hostname}/v3/campaigns/create.{Format}?apikey='
    

Request and response parameters

Abstract

Describes the different types of request and response parameters that are used when making calls to the Moosend API.

When making an API request, you can pass different parameters to the API endpoints to determine the response. There are several types of request parameters: header parameters, path parameters, query parameters, and request body parameters.

Not all Moosend API endpoints contain each type of parameter. The API Reference details the specific request and response parameters for each API endpoint.

Header parameters

You must set the correct header parameters in every API request to retrieve the response data in the expected format and data type. The following headers are supported in Moosend API requests:

Request header

Value

Accept

application/json

application/xml

application/html+xml

Content-Type

application/json

For the response header parameter, only the JSON type is supported.

Request header

Value

Accept

application/json

Content-Type

application/json

Query parameters

You can use query parameters for filtering, pagination, and partial responses in the Moosend API. Query parameters are added to the request URL after the query string ?. You can add one or more query parameters separated by &.

The following is an example that shows three query parameters apikey, WithStatistics, and SortMethod.

curl --include \
'https://{hostname}/v3/lists.{Format}?apikey=value1&&WithStatitiscs=value2&SortMethod=value3'

When you have an API request that uses query parameters, you must add the actual value of each parameter after the =. For example:

curl --include \
'https://{hostname}/v3/campaigns.{Format}?apikey=bafe55f4-e53e-4651-8164-c6d6ff05081b'

The apikey is an example of a request query parameter that is required in all Moosend API endpoints.

Path parameters

You can use path parameters as identifiers to help you structure your requests. Path parameters appear within the path of the request URL before the query string ? and are usually indicated in curly brackets { }.

The following example shows three path parameters Page, PageSize, and Format:

curl --include \
'https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?'

When you have an API request that uses path parameters, you must replace the path parameter with their actual values in your request. For example:

curl --include \
'https://{hostname}/v3/lists/1/100.json?'

Format is an example of a path parameter that is required in all Moosend API endpoints. There are only two available formats you can use in getting a response: xml and json.

Request body parameters

For POST requests, you must include a request body with parameters. You can find the details of request body parameters for each endpoint, including required fields in the API Reference.

The following is an example of a request body containing the Name, ConfirmationPage, and RedirectAfterUnsubscribePage parameters:

curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\":\"New List\",
    \"ConfirmationPage\":\"www.someUrl.com\",
    \"RedirectAfterUnsubscribePage\":\"www.someUrl.com\"
}" \
'https://{hostname}/v3/lists/create.{Format}?apikey='

Response body parameters

All responses to API calls include an HTTP status code, a response header, and a response schema with a JSON-formatted body. You can find the details of the response body parameters corresponding to each endpoint in the API Reference.

The following is an example of a JSON response body containing three parameters for Code, Error, and Context:

{
  "Code": 0,
  "Error": null,
  "Context": "e5f6c0a3-1fe6-4d89-951e-eafae0b01368"
}

HTTP status codes

Abstract

Describes the possible HTTP status codes returned in the Moosend API response.

The Moosend API returns standard HTTP success or error status codes. The following is a list of various HTTP status codes that the API returns:

HTTP status code

Description

200 OK

The request was successful.

201 Created

The request has been fulfilled and has resulted in one or more new resources being created.

202 Accepted

The request has been accepted for processing, but the processing has not been completed.

400 Bad Request

The server cannot process the request due to something that is perceived to be a client error.

API rate limiting

Abstract

Describes the API rate limiting enforced by Moosend to prevent having too many requests.

The Moosend API enforces rate limiting to prevent the API from being overwhelmed by too many requests. This means that it allows only a certain number of API calls from users within a given time. If a user sends too many requests, API rate limiting can throttle client connections.

The following table describes the current rate limit (number of requests per 10 seconds) per user (per API key):

Resource

Method

Endpoint path

Rate limit

Add subscribers

POST

/subscribers/{MailingListID}/subscribe.{Format}

10

Add multiple subscribers

POST

/subscribers/{MailingListID}/subscribe_many.{Format}

2

Unsubscribe a subscriber from an account

POST

/subscribers/unsubscribe.{Format}

20

Unsubscribe a subscriber from an email list

POST

/subscribers/{MailingListID}/unsubscribe.{Format}

20

Unsubscribe a subscriber from an email list and a campaign

POST

/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}

20

Example response

The following is an example of a response when request submissions exceed the rate limit. When you go over the rate limit, you receive a RATE_LIMITING error in the response body.

{
  "Code": 429,
  "Error": "RATE_LIMITING",
  "Context": null
}

Walkthrough: Create a mailing list and add subscribers

Abstract

Provides a walkthrough in making your first requests to the Moosend API to create a new email list and add multiple subscribers to the list.

This walkthrough shows how you can make your first calls to the Moosend API. When making API requests, you must always locate the specific API endpoints and parameters you need in API reference.

In this example, you create two requests using two API endpoints.

This walkthrough describes how to:

Create a new email list using the API

To create a new email list using the API:

  1. Go to the Create a mailing list endpoint reference.

  2. Create a POST request using /lists/create.{Format}.

  3. Add your request header. You can use the following value: Content-Type:application/json.

  4. Add the required Format in the request URL path. Possible values are json or xml.

    For example, if you select a JSON format, you can edit the URL as: https://{hostname}/v3/lists/create.json.

  5. Add the required apikey parameter in the request URL after the ?.

    For example, you can add your API key as https://{hostname}/v3/lists/create.json?apikey=bafe55f4-e53e-4651-8164-c6d6ff05081b.

  6. Add the required request body parameter for Name. Optionally, you can add the ConfirmationPage, and RedirectAfterUnsubscribePage parameters.

    curl --include \
         --request POST \
         --header "Content-Type: application/json" \
         --header "Accept: application/json" \
         --data-binary "{
        \"Name\":\"New List\",
        \"ConfirmationPage\":\"www.someUrl.com\",
        \"RedirectAfterUnsubscribePage\":\"www.someUrl.com\"
    }" \
    'https://{hostname}/v3/lists/create.json?apikey=bafe55f4-e53e-4651-8164-c6d6ff05081b'
    
    
  7. Send your API request. If successful, you get a response with HTTP code 200, a Content-Type: application/json response header, and the following JSON response:

    {
      "Code": 0,
      "Error": null,
      "Context": "6ca52d31-765c-4760-a78e-91e511e49d76"
    }

    The response body contains the Context parameter that gives you the ID of the new email list created. You can now use this ID to add subscribers to your new email list using the next API endpoint.

Add subscribers to your new email list using the API

To add subscribers to your new email list:

  1. Go to the Add multiple subscribers endpoint reference.

  2. Create a POST request using /subscribers/{MailingListID}/subscribe_many.{Format}.

  3. Add your request header. You can use the following value: Content-Type:application/json.

  4. Add the required path parameters in the request URL. Possible values for Format are json or xml. For MailingListID, use the ID of the new email list you created.

    For example, if you select a JSON format and use the new email list ID, you can edit the URL as:

    https://{hostname}/v3/subscribers/6ca52d31-765c-4760-a78e-91e511e49d76/subscribe_many.json

  5. Add the required query parameter in the request URL after the ?.

    For example, you can add your API key as https://{hostname}/v3/subscribers/6ca52d31-765c-4760-a78e-91e511e49d76/subscribe_many.json?apikey=bafe55f4-e53e-4651-8164-c6d6ff05081b

  6. Add the required request body parameters for Subscribers. You must specify the Name, Email, and CustomEields for each subscriber on this list. Optionally, you can add the HasExternalDoubleOptIn parameter.

    curl --include \
         --request POST \
         --header "Content-Type: application/json" \
         --header "Accept: application/json" \
         --data-binary "{  
        \"HasExternalDoubleOptIn\": false,
        \"Subscribers\":[  
          {  
             \"Name\":\"test1Email\",
             \"Email\":\"test1@test.com\",
             \"CustomFields\":[  
                \"Country=UK\"
             ]
          },
          {  
             \"Name\":\"test2133Email\",
             \"Email\":\"test2133@test.com\",
             \"CustomFields\":[  
                \"Age=25\",
                \"Country=USA\"
             ]
          }
       ]
    }" \
    'https://{hostname}/v3/subscribers/6ca52d31-765c-4760-a78e-91e511e49d76/subscribe_many.json?apikey=bafe55f4-e53e-4651-8164-c6d6ff05081b'
    
  7. Send your API request. If successful, you get a response with HTTP code 200, a Content-Type: application/json response header, and the following JSON response:

    {
      "Code": 0,
      "Error": "2 items with invalid email address were ignored: email@email, email2@email",
      "Context": [
        {
          "ID": "ca506fc5-0967-4756-8848-74e9766bdbdd",
          "Name": "test1Email",
          "Email": "test1@test.com",
          "CreatedOn": "/Date(1465377493907+0100)/",
          "UpdatedOn": "/Date(1465381164389)/",
          "UnsubscribedOn": null,
          "UnsubscribedFromID": null,
          "SubscribeType": 1,
          "SubscribeMethod": 1,
          "CustomFields": [
            {
              "CustomFieldID": "42acf2cf-1096-4c80-960b-051791d9a276",
              "Name": "Country",
              "Value": "UK"
            }
          ],
          "RemovedOn": null
        },
        {
          "ID": "b751f349-f6b3-4b14-8d75-c37dfafbe40a",
          "Name": "test2133Email",
          "Email": "test2133@test.com",
          "CreatedOn": "/Date(1465377493907+0100)/",
          "UpdatedOn": "/Date(1465381164389)/",
          "UnsubscribedOn": null,
          "UnsubscribedFromID": null,
          "SubscribeType": 1,
          "SubscribeMethod": 1,
          "CustomFields": [
            {
              "CustomFieldID": "60d4e2b0-e5ae-4737-9ac5-ce071ab346fb",
              "Name": "Age",
              "Value": 25
            },
            {
              "CustomFieldID": "42acf2cf-1096-4c80-960b-051791d9a276",
              "Name": "Country",
              "Value": "USA"
            }
          ],
          "RemovedOn": null
        }
      ]
    }

    The response body contains the Context parameter that gives you the ID and details of each subscriber added to the new email list.

Introduction to segmentation

Abstract

Provides a basic description of segmentation and the query or expression used in Moosend API calls.

You can add segments to your email lists to send targeted email marketing campaigns. You can define a specific audience subset in your email lists using a segmentation query or expression to match the subscribers based on content engagement, location, language, and so on. You can have a single segmentation query or an expression consisting of multiple queries in complex or nested combinations.

A segmentation query or criterion consists of the following parts:

  • Field - the criterion used to filter the email list. See list of segmentation fields.

  • Comparer - the operator that defines how to compare a Field with its Value. Each field supports specific comparers based on the data type. See list of comparers.

  • Additional parameters:

    • MatchType - defines how to combine a group of queries or criteria. It specifies how subscribers are returned by your segment based on matching criteria. Possible values are:

      • All - returns subscribers that match all the given criteria.

      • Any - returns subscribers that match any of the given criteria.

    • FetchType -defines how many criteria-matching subscribers are contained in your segment. Possible values are:

      • All - returns all criteria-matching subscribers.

      • Top - returns only a maximum number of subscribers defined in FetchValue.

      • TopPercent - returns only a percentage of subscribers defined in FetchValue.

    • FetchValue - specifies the maximum number for FetchType:Top or percentage for FetchType:TopPercent of members to be contained in the created segment.

List of segmentation fields

Abstract

Lists the segmentation fields that are used in Moosend API segmentation expressions.

Segmentation queries or expressions can contain any combination of the Fields described in the following tables. You can use either the field name or the corresponding code in your JSON request body. Some fields accept these additional parameters:

  • Date Constrain - constrains the results based on a related date field.

  • OtherMailingListId - runs the query on another email list on members that are contained in both the current and the other email list.

  • CustomFieldId or CustomFieldName - used only with CustomField and specifies the custom field definition by the ID or the name for which the query applies. The custom field definition can be either one of the current email lists or the email list specified by the OtherMailingListId parameter.

Member fields

Code

Data type

Date constrain

OtherMailingListId

DateAdded

1

dateTime

Yes

DateUpdated

16

dateTime

Yes

RecipientName

2

string

Yes

RecipientEmail

3

string

SubscribeMethod

14

enum

Yes (SubscribedOn)

Yes

CustomField

99

string, decimal, dateTime, Boolean

Yes

MailingList

17

guid

Campaign fields

Code

Data type

Date constrain

OtherMailingListId

CampaignsOpened

4

integer

Yes (DeliveredOn)

Yes

LinksClicked

5

integer

Yes (DeliveredOn)

Yes

CampaignName

6

string

Yes (DeliveredOn)

Yes

CampaignTitle

20

string

Yes (Timestamp)

Yes

LinkURL

7

guid

Yes (DeliveredOn)

Yes

CampaignSent

15

guid

Yes (Timestamp)

Yes

OpenedAnyCampaign

24

Boolean

Yes (Timestamp)

Yes

CampaignID

19

guid

Yes (Timestamp)

Yes

SpecificCampaignClicked

26

string

Yes (Timestamp)

Yes

CampaignIdNotOpened

27

string

Yes

User agent fields

Code

Data type

Date constrain

OtherMailingListId

Platform

8

enum (Desktop = 1, Mobile = 2, Other = 3)

OperatingSystem

9

string

EmailClient

10

string

WebBrowser

11

string

MobileBrowser

12

string

Website fields

Code

Data type

Date constrain

OtherMailingListId

AddedAnythingToCart

21

Boolean + extra (CampaignId, ProductCode, WebsiteId, Times)

Yes (Timestamp)

Yes

ViewedProduct

22

Boolean + extra (CampaignId, ProductCode, WebsiteId, Times)

Yes (Timestamp)

Yes

PurchasedProduct

23

Boolean + extra (CampaignId, ProductCode, WebsiteId, Times)

Yes (Timestamp)

Yes

List of comparers

Abstract

Lists the comparers or operators that are used in Moosend API segmentation queries.

Query comparers or operators differ according to the data type of the field. The following table lists the supported operators for each data type. You can use either the name or the code in your JSON request body.

IsEmpty* and IsNotEmpty* are available when the field is nullable.

Operator

Code

String

Integer

Decimal

DateTime

Enum

Guid

Boolean

Is

0

+

+

+

+

+

+

IsNot

1

+

+

+

+

+

+

Contains

2

+

DoesNotContain

3

+

StartsWith

4

+

DoesNotStartWith

5

+

EndsWith

6

+

DoesNotEndWith

7

+

IsGreaterThan

8

+

+

IsGreaterThanOrEqualTo

9

+

+

IsLessThan

10

+

+

IsLessThanOrEqualTo

11

+

+

IsBefore

12

+

IsAfter

13

+

IsEmpty*

14

+

+

+

+

+

+

+

IsNotEmpty*

15

+

+

+

+

+

+

+

IsTrue

16

+

IsFalse

17

+

IsBetween

24

+

+

+

IsNotBetween

25

+

+

+

List of date functions

Abstract

Lists the date functions that are used in Moosend API segmentation fields.

The following table describes the DateFunction values that you can use with fields that have a DateTime data type. You can query based on a property of the date instead of the date itself. The calculation depends on the TimeZoneUsed parameter. Possible time zone values are Local or Utc. When Local is used, the user’s time zone offset is considered.

Function name

Code

Description

Year

1

The four-digit year part of the date.

Month

2

The month part of the date from 1 to 12.

Day

3

The day part of the date from 1 to 31.

WeekDay

4

The day of the week from 1 to 7. For example, 1 for Sunday, 2 for Monday, and so on.

DaysPassed

5

The number of days that have passed until now.

HoursPassed

6

The number of hours that have passed until now.

MinutesPassed

7

The number of minutes that have passed until now.

List of date constrain parameters

Abstract

Lists the date parameters that are used to constrain results of a Moosend API response based on the elapsed time or date span.

You can constrain the results of a Moosend API response based on the elapsed time or date span using the following parameters:

  • LastXMinutes - constrains the results by the time that has elapsed.

  • DateFrom and DateTo - constrain the results based on a specific date span.

API reference

The following sections provide the reference containing all the information required to work with the Moosend API endpoints:

Mailing lists

Abstract

Describes how to use the Moosend API to create, edit, and manage email lists in your account.

Use the Moosend API to get your email lists, get details about email lists, create, update, and delete email lists. You can also create, update, or remove custom fields in your email lists.

Get all active mailing lists

Abstract

Describes the request and response details of this Moosend API endpoint to get your active email lists.

Request

Parameter

In

Type

Required

Description

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

WithStatistics

query

string

false

Specifies whether to fetch statistics for the subscribers.

Possible values: true (Default) and false.

ShortBy

query

string

false

The name of the email list property to sort results by.

Possible values: Name, Subject, Status, DeliveredOn, and CreatedOn (Default).

SortMethod

query

string

false

Specifies the method to sort results.

Possible values: DESC for descending and ASC (Default) for ascending.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the Paging and MailingLists information for the requested email list:

  • Paging - an object that contains the following information:

    • PageSize - the page size of the results. This is 0 if not defined.

    • CurrentPage - the number of the result page. This is 1 if not defined.

    • Totalresults - the number of email lists that are included in the response.

    • TotalPageCount - the total number of available email list pages in your account.

    • SortExpression - the sort expression associated with the column or columns being sorted.

    • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

  • MailingLists - a list of email lists in your account containing the following information for each email list:

    • ID -the ID of the email list.

    • Name - the name of the email list.

    • ActiveMemberCount - the number of active members in the email list.

    • BouncedMemberCount - the number of bounced emails in the email list.

    • RemovedMemberCount - the number of emails removed from the email list.

    • UnsubscribedMemberCount - the number of emails unsubscribed from the email list.

    • Status - status of the email list. For created, this is 0, for imported, this is 1, for importing, this is 2 , and for deleted, this is 3.

    • CustomFieldsDefinition - an array containing the parameters of custom fields in the email list. The parameters are:

      • ID - the ID of the custom field.

      • Name - the name of the custom field

      • Context - the context of the custom field. This is null if the field type is not SingleSelectDropDown.

      • IsRequired - this is true if the custom field is required and false if it is not.

      • Type - the data type of the custom field. Possible values: 0 for text, 1 for number, 2 for dateTime, 3 for SingleSelectDropDown, and 5 for checkbox.

  • CreatedBy - the IP address used to create the requested email list.

  • CreatedOn - the date-time the requested email list was created.

  • UpdatedBy - the IP address used to update the requested email list.

  • UpdatedOn - the date-time the requested email list was updated.

  • ImportOperation - an object that contains the details of the latest import operation performed in the requested email list. This is blank if there was no import done.

    • ID - the ID of the import operation.

    • DataHash - a globally unique identifier (GUID) for the import operation

    • Mappings - the data mappings used for the specific import operation.

    • EmailNotify - this is null if the import operation notification email was not selected to be sent

    • CreatedOn - the date-time when the import operation was created.

    • StartedOn - the date-time when the import operation was stated.

    • CompletedOn - the date-time when the import operation was completed.

    • TotalInserted - the total number of inserted emails.

    • TotalUpdated - the total number of updated emails.

    • TotalUnsubscribed - the total number of unsubscribed emails.

    • TotalInvalid - the total number of invalid emails.

    • TotalIgnored - the total number of ignored emails.

    • TotalDuplicate - the total number of duplicate emails.

    • TotalMembers - the total number of members that were selected to be imported.

    • Message - the message of the import operation. This is null if successful.

    • Success - this is true if successful.

    • SkipNewMembers - this is false if the skip new members option was not selected before the import operation began.

Request
GET https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=
Request
curl --include \
'https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("lists.{Format}{?apikey}{?WithStatistics}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/lists.{Format}{?apikey}{?WithStatistics}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists.{Format}?apikey=&WithStatistics=&ShortBy=&SortMethod=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 0,
      "CurrentPage": 1,
      "TotalResults": 90,
      "TotalPageCount": 9,
      "SortExpression": null,
      "SortIsAscending": false
    },
    "MailingLists": [
      {
        "ID": "04fad8e2-2b35-4302-a887-58f14a1152ab",
        "Name": "Your List Name",
        "ActiveMemberCount": 1024,
        "BouncedMemberCount": 16,
        "RemovedMemberCount": 32,
        "UnsubscribedMemberCount": 24,
        "Status": 0,
        "CustomFieldsDefinition": [
          {
            "ID": "dd4fb545-ba00-4afe-bc39-5ed2462fd1d3",
            "Name": "City",
            "Context": null,
            "IsRequired": false,
            "Type": 0
          },
          {
            "ID": "ae8500d7-d1df-4118-9a2c-6654a7d6a6db",
            "Name": "Age",
            "Context": null,
            "IsRequired": true,
            "Type": 1
          }
        ],
        "CreatedBy": "127.0.0.1",
        "CreatedOn": "/Date(1368710504000+0300)/",
        "UpdatedBy": "127.0.0.1",
        "UpdatedOn": "/Date(1368710923000+0300)/",
        "ImportOperation": {
          "ID": 0,
          "DataHash": "97de8bcb-ca1c-4a4b-bf02-3f639952e093",
          "Mappings": "Some Mappings",
          "EmailNotify": "Some EmailNotify",
          "CreatedOn": "/Date(1400765707431)/",
          "StartedOn": "/Date(1400765707431)/",
          "CompletedOn": "/Date(1400765707432)/",
          "TotalInserted": 0,
          "TotalUpdated": 0,
          "TotalUnsubscribed": 0,
          "TotalInvalid": 0,
          "TotalDuplicate": 0,
          "TotalMembers": 0,
          "Message": "Some Message",
          "Success": false
        }
      },
      {
        "ID": "4d90a60c-fad2-4f29-b541-318f0ea82be6",
        "Name": "Some Name",
        "ActiveMemberCount": 0,
        "BouncedMemberCount": 0,
        "RemovedMemberCount": 0,
        "UnsubscribedMemberCount": 0,
        "Status": 0,
        "CustomFieldsDefinition": [
          {
            "ID": "c0adddda-12c1-4109-b7db-9a997f70c81f",
            "Name": "Some Name",
            "Context": "Some Context",
            "IsRequired": false,
            "Type": 0
          },
          {
            "ID": "da5bdc1c-08b2-4b3e-b44b-d56ede6d1a31",
            "Name": "Some Name",
            "Context": "Some Context",
            "IsRequired": false,
            "Type": 0
          }
        ],
        "CreatedBy": "Some CreatedBy",
        "CreatedOn": "/Date(1400765707432)/",
        "UpdatedBy": "Some UpdatedBy",
        "UpdatedOn": "/Date(1400765707432)/",
        "ImportOperation": {
          "ID": 0,
          "DataHash": "7ec702c2-0481-45cc-bf92-72bb4912c60d",
          "Mappings": "Some Mappings",
          "EmailNotify": "Some EmailNotify",
          "CreatedOn": "/Date(1400765707432)/",
          "StartedOn": "/Date(1400765707432)/",
          "CompletedOn": "/Date(1400765707432)/",
          "TotalInserted": 0,
          "TotalUpdated": 0,
          "TotalUnsubscribed": 0,
          "TotalInvalid": 0,
          "TotalDuplicate": 0,
          "TotalMembers": 0,
          "Message": "Some Message",
          "Success": false
        }
      }
    ]
  }
}

Get mailing list details

Abstract

Describes the request and response details of this Moosend API endpoint to get your email list details.

Request

Parameter

In

Type

Required

Description

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

MailingListID

path

string

true

The ID of the email list that contains the details you are requesting.

apikey

query

string

true

The API key of your account.

WithStatistics

query

string

false

Specifies whether to fetch statistics for the subscribers.

Possible values: true (Default) and false.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the requested email list:

  • ID - the ID of the email list.

  • Name - the name of the email list.

  • ActiveMemberCount - the number of active members in the email list.

  • BouncedMemberCount - the number of bounced emails in the email list.

  • RemovedMemberCount - the number of emails removed from the email list.

  • UnsubscribedMemberCount - the number of emails unsubscribed from the email list.

  • Status - status of the email list. For created, this is 0, for imported, this is 1, for importing, this is 2 , and for deleted, this is 3.

  • CustomFieldsDefinition - an array containing the parameters of custom fields in the email list. The parameters are:

    • ID - the ID of the custom field.

    • Name - the name of the custom field

    • Context - the context of the custom field. This is null if the field type is not SingleSelectDropDown.

    • IsRequired - this is true if the custom field is required and false if it is not.

    • Type - the data type of the custom field. Possible values: 0 for text, 1 for number, 2 for dateTime, 3 for SingleSelectDropDown, and 5 for checkbox.

  • CreatedBy - the IP address used to create the requested email list.

  • CreatedOn - the date-time the requested email list was created.

  • UpdatedBy - the IP address used to update the requested email list.

  • UpdatedOn - the date-time the requested email list was updated.

  • ImportOperation - an object that contains the details of the latest import operation performed in the requested email list. This is blank if there was no import done.

    • ID - the ID of the import operation.

    • DataHash - a globally unique identifier (GUID) for the import operation

    • Mappings - the data mappings used for the specific import operation.

    • EmailNotify - this is null if the import operation notification email was not selected to be sent

    • CreatedOn - the date-time when the import operation was created.

    • StartedOn - the date-time when the import operation was stated.

    • CompletedOn - the date-time when the import operation was completed.

    • TotalInserted - the total number of inserted emails.

    • TotalUpdated - the total number of updated emails.

    • TotalUnsubscribed - the total number of unsubscribed emails.

    • TotalInvalid - the total number of invalid emails.

    • TotalIgnored - the total number of ignored emails.

    • TotalDuplicate - the total number of duplicate emails.

    • TotalMembers - the total number of members that were selected to be imported.

    • Message - the message of the import operation. This is null if successful.

    • Success - this is true if successful.

    • SkipNewMembers - this is false if the skip new members option was not selected before the import operation began.

Request
GET https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=
Request
curl --include \
'https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);

Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}v/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("lists.{Format}{?apikey}{?WithStatistics}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/lists.{Format}{?apikey}{?WithStatistics}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/details.{Format}?apikey=&WithStatistics=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "28132257-f655-49a4-8af7-6fbf31645641",
    "Name": "test auto",
    "ActiveMemberCount": 19999,
    "BouncedMemberCount": 0,
    "RemovedMemberCount": 0,
    "UnsubscribedMemberCount": 0,
    "Status": 1,
    "CustomFieldsDefinition": [
      {
        "ID": "c3226cc-8a18-4f22-907b-8422d61a53a1",
        "Name": "Gender",
        "Context": "<items><item><name>Male</name><value>Male</value></item><item><name>Female</name><value>Female</value></item></items>",
        "IsRequired": true,
        "Type": 3
      },
      {
        "ID": "bf14b37c-3c47-412d-baf1-c6850b8cf2af",
        "Name": "Town",
        "Context": null,
        "IsRequired": false,
        "Type": 0
      }
    ],
    "CreatedBy": "223.16.165.23",
    "CreatedOn": "/Date(1443174387327+0100)/",
    "UpdatedBy": "223.16.165.23",
    "UpdatedOn": "/Date(1443174387327+0100)/",
    "ImportOperation": {
      "ID": 3706,
      "DataHash": "2490c26c-79f6-a52c-4afb-852f624a91b0",
      "Mappings": "Email",
      "EmailNotify": null,
      "CreatedOn": "/Date(1443181931130+0100)/",
      "StartedOn": "/Date(1443181958330+0100)/",
      "CompletedOn": "/Date(1443182730673+0100)/",
      "TotalInserted": 19999,
      "TotalUpdated": 0,
      "TotalUnsubscribed": 1,
      "TotalInvalid": 0,
      "TotalIgnored": 0,
      "TotalDuplicate": 0,
      "TotalMembers": 20000,
      "Message": null,
      "Success": true,
      "SkipNewMembers": false
    }
  }
}

Get all active mailing lists with paging

Abstract

Describes the request and response details of this Moosend API endpoint to get your active email lists with paging information included.

Request

Parameter

In

Type

Required

Description

Page

path

number

false

The page that you want to get.

PageSize

path

number

false

The number of email lists per page.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

ShortBy

query

string

false

The name of the email list property to sort results by.

Possible values: Name, Subject, Status, DeliveredOn, and CreatedOn (Default).

SortMethod

query

string

false

Specifies the method to sort results.

Possible values: DESC for descending and ASC (Default) for ascending.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the Paging and MailingLists information for the requested email list:

  • Paging - an object that contains the following information:

    • PageSize - the page size of the results. This is 0 if not defined.

    • CurrentPage - the number of the result page. This is 1 if not defined.

    • Totalresults - the number of email lists that are included in the response.

    • TotalPageCount - the total number of available email list pages in your account.

    • SortExpression - the sort expression associated with the column or columns being sorted.

    • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

  • MailingLists - a list of email lists in your account containing the following information for each email list:

    • ID -the ID of the email list.

    • Name - the name of the email list.

    • ActiveMemberCount - the number of active members in the email list.

    • BouncedMemberCount - the number of bounced emails in the email list.

    • RemovedMemberCount - the number of emails removed from the email list.

    • UnsubscribedMemberCount - the number of emails unsubscribed from the email list.

    • Status - status of the email list. For created, this is 0, for imported, this is 1, for importing, this is 2 , and for deleted, this is 3.

    • CustomFieldsDefinition - an array containing the parameters of custom fields in the email list. The parameters are:

      • ID - the ID of the custom field.

      • Name - the name of the custom field

      • Context - the context of the custom field. This is null if the field type is not SingleSelectDropDown.

      • IsRequired - this is true if the custom field is required and false if it is not.

      • Type - the data type of the custom field. Possible values: 0 for text, 1 for number, 2 for dateTime, 3 for SingleSelectDropDown, and 5 for checkbox.

  • CreatedBy - the IP address used to create the requested email list.

  • CreatedOn - the date-time the requested email list was created.

  • UpdatedBy - the IP address used to update the requested email list.

  • UpdatedOn - the date-time the requested email list was updated.

  • ImportOperation - an object that contains the details of the latest import operation performed in the requested email list. This is blank if there was no import done.

    • ID - the ID of the import operation.

    • DataHash - a globally unique identifier (GUID) for the import operation

    • Mappings - the data mappings used for the specific import operation.

    • EmailNotify - this is null if the import operation notification email was not selected to be sent

    • CreatedOn - the date-time when the import operation was created.

    • StartedOn - the date-time when the import operation was stated.

    • CompletedOn - the date-time when the import operation was completed.

    • TotalInserted - the total number of inserted emails.

    • TotalUpdated - the total number of updated emails.

    • TotalUnsubscribed - the total number of unsubscribed emails.

    • TotalInvalid - the total number of invalid emails.

    • TotalIgnored - the total number of ignored emails.

    • TotalDuplicate - the total number of duplicate emails.

    • TotalMembers - the total number of members that were selected to be imported.

    • Message - the message of the import operation. This is null if successful.

    • Success - this is true if successful.

    • SkipNewMembers - this is false if the skip new members option was not selected before the import operation began.

Request
GET https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=
Request
curl --include \
'https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);

Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("lists.{Format}{?apikey}{?WithStatistics}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/lists.{Format}{?apikey}{?WithStatistics}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{Page}/{PageSize}.{Format}?apikey=&ShortBy=&SortMethod=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 20,
      "CurrentPage": 1,
      "TotalResults": 92,
      "TotalPageCount": 5,
      "SortExpression": null,
      "SortIsAscending": false
    },
    "MailingLists": [
      {
        "ID": "04fad8e2-2b35-4302-a887-58f14a1152ab",
        "Name": "Your List Name",
        "ActiveMemberCount": 1024,
        "BouncedMemberCount": 16,
        "RemovedMemberCount": 32,
        "UnsubscribedMemberCount": 24,
        "Status": 0,
        "CustomFieldsDefinition": [
          {
            "ID": "dd4fb545-ba00-4afe-bc39-5ed2462fd1d3",
            "Name": "City",
            "Context": null,
            "IsRequired": false,
            "Type": 0
          },
          {
            "ID": "ae8500d7-d1df-4118-9a2c-6654a7d6a6db",
            "Name": "Age",
            "Context": null,
            "IsRequired": true,
            "Type": 1
          }
        ],
        "CreatedBy": "127.0.0.1",
        "CreatedOn": "/Date(1368710504000+0300)/",
        "UpdatedBy": "127.0.0.1",
        "UpdatedOn": "/Date(1368710923000+0300)/",
        "ImportOperation": {
          "ID": 0,
          "DataHash": "97de8bcb-ca1c-4a4b-bf02-3f639952e093",
          "Mappings": "Some Mappings",
          "EmailNotify": "Some EmailNotify",
          "CreatedOn": "/Date(1400765707431)/",
          "StartedOn": "/Date(1400765707431)/",
          "CompletedOn": "/Date(1400765707432)/",
          "TotalInserted": 0,
          "TotalUpdated": 0,
          "TotalUnsubscribed": 0,
          "TotalInvalid": 0,
          "TotalDuplicate": 0,
          "TotalMembers": 0,
          "Message": "Some Message",
          "Success": false
        }
      },
      {
        "ID": "4d90a60c-fad2-4f29-b541-318f0ea82be6",
        "Name": "Some Name",
        "ActiveMemberCount": 0,
        "BouncedMemberCount": 0,
        "RemovedMemberCount": 0,
        "UnsubscribedMemberCount": 0,
        "Status": 0,
        "CustomFieldsDefinition": [],
        "CreatedBy": "192.168.1.1",
        "CreatedOn": "/Date(1400765707432)/",
        "UpdatedBy": "192.168.1.1",
        "UpdatedOn": "/Date(1400765707432)/",
        "ImportOperation": {
          "ID": 0,
          "DataHash": "7ec702c2-0481-45cc-bf92-72bb4912c60d",
          "Mappings": "Some Mappings",
          "EmailNotify": "Some EmailNotify",
          "CreatedOn": "/Date(1400765707432)/",
          "StartedOn": "/Date(1400765707432)/",
          "CompletedOn": "/Date(1400765707432)/",
          "TotalInserted": 0,
          "TotalUpdated": 0,
          "TotalUnsubscribed": 0,
          "TotalInvalid": 0,
          "TotalDuplicate": 0,
          "TotalMembers": 0,
          "Message": "Some Message",
          "Success": false
        }
      }
    ]
  }
}

Create a mailing list

Abstract

Describes the request and response details of this Moosend API endpoint to create an email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the email list.

ConfirmationPage

body

string

false

The URL of the page displayed at the end of the subscription process.

RedirectAfterUnsubscribePage

body

string

false

The URL of the redirect page when users unsubscribe from your email list.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - the ID of the email list created.

Request
POST https://{hostname}/v3/lists/create.{Format}?apikey=

Request body:
{
  "Name": "New List",
  "ConfirmationPage": "www.someUrl.com",
  "RedirectAfterUnsubscribePage": "www.someUrl.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\":\"New List\",
    \"ConfirmationPage\":\"www.someUrl.com\",
    \"RedirectAfterUnsubscribePage\":\"www.someUrl.com\"
}" \
'https://{hostname}/v3/lists/create.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"New List\",  \"ConfirmationPage\": \"www.someUrl.com\",  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"}");
Response response = client.target("https://{hostname}/v3/lists/create.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/lists/create.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'New List',
  'ConfirmationPage': 'www.someUrl.com',
  'RedirectAfterUnsubscribePage': 'www.someUrl.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/lists/create.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"New List\",  \"ConfirmationPage\": \"www.someUrl.com\",  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "New List",  "ConfirmationPage": "www.someUrl.com",  "RedirectAfterUnsubscribePage": "www.someUrl.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/lists/create.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "New List",
    "ConfirmationPage": "www.someUrl.com",
    "RedirectAfterUnsubscribePage": "www.someUrl.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/lists/create.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/create.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"New List\",
  \"ConfirmationPage\": \"www.someUrl.com\",
  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);

Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "New List",
  "ConfirmationPage": "www.someUrl.com",
  "RedirectAfterUnsubscribePage": "www.someUrl.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/lists/create.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"New List\",\n  \"ConfirmationPage\": \"www.someUrl.com\",\n  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/lists/create.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"New List\",  \"ConfirmationPage\": \"www.someUrl.com\",  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("Mailing Lists/lists/create.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/create.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""New List\"",
  \""ConfirmationPage\"": \""www.someUrl.com\"",
  \""RedirectAfterUnsubscribePage\"": \""www.someUrl.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "New List",
  "ConfirmationPage": "www.someUrl.com",
  "RedirectAfterUnsubscribePage": "www.someUrl.com"
}')
response = client.post( path : "/Mailing Lists/lists/create.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/create.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"New List\",\n  \"ConfirmationPage\": \"www.someUrl.com\",\n  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/create.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"New List\",\n  \"ConfirmationPage\": \"www.someUrl.com\",\n  \"RedirectAfterUnsubscribePage\": \"www.someUrl.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": "6ca52d31-765c-4760-a78e-91e511e49d76"
}

Update a mailing list

Abstract

Describes the request and response details of this Moosend API endpoint to update an email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list to be updated.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the email list.

ConfirmationPage

body

string

false

The URL of the page displayed at the end of the subscription process.

RedirectAfterUnsubscribePage

body

string

false

The URL of the redirect page when users unsubscribe from your email list.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - the ID of the updated email list.

Request
POST https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=

Request body:
{
  "Name": "New List Name",
  "ConfirmationPage": "www.someotherUrl.com",
  "RedirectAfterUnsubscribePage": "www.someotherUrl.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\":\"New List Name\",
    \"ConfirmationPage\":\"www.someotherUrl.com\",
    \"RedirectAfterUnsubscribePage\":\"www.someotherUrl.com\"
}" \
'https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey='
Request
// Maven : Add these dependecies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"New List Name\",  \"ConfirmationPage\": \"www.someotherUrl.com\",  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"}");
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'New List Name',
  'ConfirmationPage': 'www.someotherUrl.com',
  'RedirectAfterUnsubscribePage': 'www.someotherUrl.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"New List Name\",  \"ConfirmationPage\": \"www.someotherUrl.com\",  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "New List Name",  "ConfirmationPage": "www.someotherUrl.com",  "RedirectAfterUnsubscribePage": "www.someotherUrl.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "New List Name",
    "ConfirmationPage": "www.someotherUrl.com",
    "RedirectAfterUnsubscribePage": "www.someotherUrl.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"New List Name\",
  \"ConfirmationPage\": \"www.someotherUrl.com\",
  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "New List Name",
  "ConfirmationPage": "www.someotherUrl.com",
  "RedirectAfterUnsubscribePage": "www.someotherUrl.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"New List Name\",\n  \"ConfirmationPage\": \"www.someotherUrl.com\",\n  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"New List Name\",  \"ConfirmationPage\": \"www.someotherUrl.com\",  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("Mailing Lists/lists/create.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""New List Name\"",
  \""ConfirmationPage\"": \""www.someotherUrl.com\"",
  \""RedirectAfterUnsubscribePage\"": \""www.someotherUrl.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "New List Name",
  "ConfirmationPage": "www.someotherUrl.com",
  "RedirectAfterUnsubscribePage": "www.someotherUrl.com"
}')
response = client.post( path : "/Mailing Lists/lists/create.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"New List Name\",\n  \"ConfirmationPage\": \"www.someotherUrl.com\",\n  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/update.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"New List Name\",\n  \"ConfirmationPage\": \"www.someotherUrl.com\",\n  \"RedirectAfterUnsubscribePage\": \"www.someotherUrl.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": "e5f6c0a3-1fe6-4d89-951e-eafae0b01368"
}

Delete a mailing list

Abstract

Describes the request and response details of this Moosend API endpoint to delete an email list.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list to be deleted.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response error message. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
DELETE https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=
Request
curl --include \
     --request DELETE \
'https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey='
Request
// Maven : Add these dependecies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .delete();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('DELETE', 'https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request({
  method: 'DELETE',
  url: 'https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=',
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->delete("https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=')
request.get_method = lambda: 'DELETE'

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

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

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.delete 'https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("DELETE", "https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.DeleteAsync("Mailing Lists/lists/create.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "DELETE"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.delete( path : "/Mailing Lists/lists/create.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"DELETE"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/delete.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "DELETE"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Create a custom field

Abstract

Describes the request and response details of this Moosend API endpoint to create a custom field.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list where the custom field is created.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the custom field.

CustomFieldType

body

string

false

Specifies the data type of the custom field. This must be one of the following values.

  • Text (Default) - accepts any text value as input.

  • Number - accepts only numeric values as input.

  • DateTime - accepts only date values as input, with or without time.

  • SingleSelectDropdown - accepts only values explicitly defined in a list.

  • CheckBox - accepts only values of true or false.

Options

body

string

false

If you want to create a SingleSelectDropdown custom field, you must set this parameter to specify the available options for the user to choose from. Use a comma (,) to separate different options.

IsRequired

body

Boolean

false

Specifies whether the custom field is mandatory or not when adding a subscriber to your list. You must specify a value of true or false (Default).

IsHidden

body

Boolean

false

Specifies whether the custom field is visible to your subscribers in the Update Profile page. You must specify a value of true or false (Default).

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - the ID of the custom field created.

Request
POST https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=

Request body:
{
  "Name": "Town",
  "CustomFieldType": "SingleSelectDropdown",
  "Options": "Athens,London,New York"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\": \"Town\",
    \"CustomFieldType\":\"SingleSelectDropdown\",
    \"Options\":\"Athens,London,New York\"
}" \
'https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"Town\",  \"CustomFieldType\": \"SingleSelectDropdown\",  \"Options\": \"Athens,London,New York\"}");
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'Town',
  'CustomFieldType': 'SingleSelectDropdown',
  'Options': 'Athens,London,New York'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"Town\",  \"CustomFieldType\": \"SingleSelectDropdown\",  \"Options\": \"Athens,London,New York\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "Town",  "CustomFieldType": "SingleSelectDropdown",  "Options": "Athens,London,New York"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "Town",
    "CustomFieldType": "SingleSelectDropdown",
    "Options": "Athens,London,New York"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"Town\",
  \"CustomFieldType\": \"SingleSelectDropdown\",
  \"Options\": \"Athens,London,New York\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "Town",
  "CustomFieldType": "SingleSelectDropdown",
  "Options": "Athens,London,New York"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"Town\",\n  \"CustomFieldType\": \"SingleSelectDropdown\",\n  \"Options\": \"Athens,London,New York\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"Town\",  \"CustomFieldType\": \"SingleSelectDropdown\",  \"Options\": \"Athens,London,New York\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("Mailing Lists/lists/create.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""Town\"",
  \""CustomFieldType\"": \""SingleSelectDropdown\"",
  \""Options\"": \""Athens,London,New York\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "Town",
  "CustomFieldType": "SingleSelectDropdown",
  "Options": "Athens,London,New York"
}')
response = client.post( path : "/Mailing Lists/lists/create.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"Town\",\n  \"CustomFieldType\": \"SingleSelectDropdown\",\n  \"Options\": \"Athens,London,New York\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/customfields/create.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"Town\",\n  \"CustomFieldType\": \"SingleSelectDropdown\",\n  \"Options\": \"Athens,London,New York\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": "b42b4e0f-ca2f-403d-8231-32a2405651af"
}

Update a custom field

Abstract

Describes the request and response details of this Moosend API endpoint to update a custom field.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list containing the custom field.

CustomFieldID

path

string

true

The ID of the custom field to be updated.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the custom field.

CustomFieldType

body

string

false

Specifies the data type of the custom field. This must be one of the following values.

  • Text (Default) - accepts any text value as input.

  • Number - accepts only numeric values as input.

  • DateTime - accepts only date values as input, with or without time.

  • SingleSelectDropdown - accepts only values explicitly defined in a list.

  • CheckBox - accepts only values of true or false.

Options

body

string

false

If you want to update a SingleSelectDropdown custom field, you must set this parameter to specify the available options for the user to choose from. Use a comma (,) to separate different options.

IsRequired

body

Boolean

false

Specifies whether the custom field is mandatory or not when adding a subscriber to your list. You must specify a value of true or false (Default).

IsHidden

body

Boolean

false

Specifies whether the custom field is visible to your subscribers in the Update Profile page. You must specify a value of true or false (Default).

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=

Request body:
{
  "Name": "City",
  "CustomFieldType": "SingleSelectDropdown",
  "Options": "Frankfurt,London,Paris,Rome"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\": \"City\",
    \"CustomFieldType\":\"SingleSelectDropdown\",
    \"Options\":\"Frankfurt,London,Paris,Rome\"
}" \
'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"City\",  \"CustomFieldType\": \"SingleSelectDropdown\",  \"Options\": \"Frankfurt,London,Paris,Rome\"}");
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'City',
  'CustomFieldType': 'SingleSelectDropdown',
  'Options': 'Frankfurt,London,Paris,Rome'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"City\",  \"CustomFieldType\": \"SingleSelectDropdown\",  \"Options\": \"Frankfurt,London,Paris,Rome\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "City",  "CustomFieldType": "SingleSelectDropdown",  "Options": "Frankfurt,London,Paris,Rome"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "City",
    "CustomFieldType": "SingleSelectDropdown",
    "Options": "Frankfurt,London,Paris,Rome"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"City\",
  \"CustomFieldType\": \"SingleSelectDropdown\",
  \"Options\": \"Frankfurt,London,Paris,Rome\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "City",
  "CustomFieldType": "SingleSelectDropdown",
  "Options": "Frankfurt,London,Paris,Rome"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"City\",\n  \"CustomFieldType\": \"SingleSelectDropdown\",\n  \"Options\": \"Frankfurt,London,Paris,Rome\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"City\",  \"CustomFieldType\": \"SingleSelectDropdown\",  \"Options\": \"Frankfurt,London,Paris,Rome\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("Mailing Lists/lists/create.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""City\"",
  \""CustomFieldType\"": \""SingleSelectDropdown\"",
  \""Options\"": \""Frankfurt,London,Paris,Rome\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "City",
  "CustomFieldType": "SingleSelectDropdown",
  "Options": "Frankfurt,London,Paris,Rome"
}')
response = client.post( path : "/Mailing Lists/lists/create.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"City\",\n  \"CustomFieldType\": \"SingleSelectDropdown\",\n  \"Options\": \"Frankfurt,London,Paris,Rome\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/update.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"City\",\n  \"CustomFieldType\": \"SingleSelectDropdown\",\n  \"Options\": \"Frankfurt,London,Paris,Rome\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": "null"
}

Remove a custom field

Abstract

Describes the request and response details of this Moosend API endpoint to remove a custom field.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list containing the custom field.

CustomFieldID

path

string

true

The ID of the custom field to be deleted.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
DELETE https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=
Request
curl --include \
     --request DELETE \
'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .delete();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('DELETE', 'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request({
  method: 'DELETE',
  url: 'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=',
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->delete("https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=')
request.get_method = lambda: 'DELETE'

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

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

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.delete 'https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("DELETE", "https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.DeleteAsync("Mailing Lists/lists/create.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https:/{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "DELETE"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.delete( path : "/Mailing Lists/lists/create.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"DELETE"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/customfields/{CustomFieldID}/delete.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "DELETE"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Subscribers

Abstract

Describes how to use the Moosend API to get, add, update, unsubscribe, and remove subscribers from email lists in your account.

Use the Moosend API to fetch your subscribers, get details about your subscribers, add, update, remove subscribers, and unsubscribe subscribers from email lists or campaigns.

Get all subscribers

Abstract

Describes the request and response details of this Moosend API endpoint to get all your subscribers.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list containing the subscribers.

Status

path

string

true

Specifies the type of subscriber statistics results to return.

Possible values: Subscribed , Unsubscribed BouncedRemoved.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Page

path

number

false

The page of subscriber statistics results to return.

PageSize

path

number

false

The page size of subscriber statistics results to return.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the Paging and Subscribers information in the specific email list:

  • Paging - an object that contains the following information:

    • PageSize - the page size of the results. This is 0 if not defined.

    • CurrentPage - the number of the result page. This is 1 if not defined.

    • Totalresults - the number of all the subscribers that are included in the response.

    • TotalPageCount - the total number of available subscriber pages in your account.

    • SortExpression - the sort expression associated with the column or columns being sorted.

    • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

  • Subscribers - a list of subscribers in the email list containing the following information for each subscriber:

    • ID - the ID of the subscriber.

    • Name - the name of the subscriber.

    • Email - the email address of the subscriber.

    • CreatedOn - the date-time the subscriber was added to the email list.

    • UnsubscribedOn - the date-time the subscriber was unsubscribed from the email list. This is null if not unsubscribed from the list.

    • UnsubscribedFromID - the ID that the subscriber is unsubscribed from.

    • SubscribeType - the status of the subscriber. For subscribed, this is 1, for unsubscribed, this is 2, for bounced, this is 3 , and for removed, this is 4.

    • SubscribeMethod - the method used to subscribe the member to the email list. For subscription forms, this is 0, for file imports, this is 1, for manually added, this is 2.

    • CustomFields - a list containing the custom fields of the new subscriber. Each custom field contains the following:

      • CustomFieldID - the ID of the custom field.

      • Name - the name of the custom field.

      • Value - the value of the custom field.

    • RemovedOn - the date-time the subscriber was removed from the email list.

    • Tags - a list containing the tags of the new subscriber.

Request
GET https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=
Request
curl --include \
'https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize='
Request
// Maven : Add these dependecies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=')

response_body = urlopen(r
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("Mailing Lists/subscribers/{Status}.{Format}{?apikey}{?Page}{?PageSize}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/Mailing Lists/subscribers/{Status}.{Format}{?apikey}{?Page}{?PageSize}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/subscribers/{Status}.{Format}?apikey=&Page=&PageSize=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 500,
      "CurrentPage": 1,
      "TotalResults": 2,
      "TotalPageCount": 1,
      "SortExpression": "CreatedOn",
      "SortIsAscending": false
    },
    "Subscribers": [
      {
        "ID": "4d03536e-7263-4a45-add0-8fe9568d7481",
        "Name": "Maria",
        "Email": "maria@email.com",
        "CreatedOn": "/Date(1456236266953+0000)/",
        "UpdatedOn": "/Date(1465286948363+0100)/",
        "UnsubscribedOn": null,
        "UnsubscribedFromID": null,
        "SubscribeType": 1,
        "SubscribeMethod": 2,
        "CustomFields": [
          {
            "CustomFieldID": "dbc599a6-3ac0-4843-830c-31fa78699fcc",
            "Name": "ID",
            "Value": "1233"
          },
          {
            "CustomFieldID": "bfe484f1-030f-4f8d-bdfa-93abc3b227c0",
            "Name": "City",
            "Value": "Athens"
          }
        ],
        "RemovedOn": null,
        "Tags": [
            "potential",
            "repeater"
        ]
      },
      {
        "ID": "83485f6c-569c-4012-ab2e-f91d3f888995",
        "Name": "Andreas",
        "Email": "andreas@email.com",
        "CreatedOn": "/Date(1454421397847+0000)/",
        "UpdatedOn": "/Date(1465286972657+0100)/",
        "UnsubscribedOn": null,
        "UnsubscribedFromID": null,
        "SubscribeType": 1,
        "SubscribeMethod": 2,
        "CustomFields": [
          {
            "CustomFieldID": "dbc599a6-3ac0-4843-830c-31fa78699fcc",
            "Name": "ID",
            "Value": "1333"
          },
          {
            "CustomFieldID": "bfe484f1-030f-4f8d-bdfa-93abc3b227c0",
            "Name": "City",
            "Value": "Liverpool"
          }
        ],
        "RemovedOn": null,
        "Tags": [
            "potential",
            "repeater"
        ]
      }
    ]
  }
}

Get subscriber by email address

Abstract

Describes the request and response details of this Moosend API endpoint to get a specific subscriber by email address.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list that contains the subscriber.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Email

query

string

true

The email address of the subscriber.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the requested subscriber:

    • ID - the ID of the subscriber.

    • Name - the name of the subscriber.

    • Email - the email address of the subscriber.

    • CreatedOn - the date-time the subscriber was added to the email list.

    • UnsubscribedOn - the date-time the subscriber was unsubscribed from the email list. This is null if not unsubscribed from the list.

    • UnsubscribedFromID - the ID that the subscriber is unsubscribed from.

    • SubscribeType - the status of the subscriber. For subscribed, this is 1, for unsubscribed, this is 2, for bounced, this is 3 , and for removed, this is 4.

    • SubscribeMethod - the method used to subscribe the member to the email list. For subscription forms, this is 0, for file imports, this is 1, for manually added, this is 2.

    • CustomFields - a list containing the custom fields of the new subscriber. Each custom field contains the following:

      • CustomFieldID - the ID of the custom field.

      • Name - the name of the custom field.

      • Value - the value of the custom field.

    • RemovedOn - the date-time the subscriber was removed from the email list.

    • Tags - a list containing the tags of the new subscriber.

Request
GET https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=
Request
curl --include \
'https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("subscribers/{MailingListID}/view.{Format}{?apikey}{?Email}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/subscribers/{MailingListID}/view.{Format}{?apikey}{?Email}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/view.{Format}?apikey=&Email=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "9bef1735-f04d-4472-b029-68eb7fa2cfe7",
    "Name": "Andreas",
    "Email": "andreas@email.com",
    "CreatedOn": "/Date(1461777152597+0100)/",
    "UpdatedOn": "/Date(1461777152597+0100)/",
    "UnsubscribedOn": null,
    "UnsubscribedFromID": null,
    "SubscribeType": 1,
    "SubscribeMethod": 2,
    "CustomFields": [
      {
        "CustomFieldID": "b7e68e81-b6ab-4caa-8d13-e65871b32386",
        "Name": "Registered",
        "Value": "4/21/2016 12:00:00 AM"
      },
      {
        "CustomFieldID": "9df6dcc4-bef2-47e7-93af-86889b6b6d6a",
        "Name": "Age",
        "Value": "24"
      },
      {
        "CustomFieldID": "0d2199aa-65fc-448c-b9fe-199e3b72ebc5",
        "Name": "Some custom field",
        "Value": "Something"
      },
      {
        "CustomFieldID": "46721a6b-09aa-46ff-bab1-a0b75dea24cf",
        "Name": "Some custom field",
        "Value": "Text1"
      }
    ],
    "RemovedOn": null,
    "Tags": [
            "potential",
            "repeater"
        ]
  }
}

Get subscriber by ID

Abstract

Describes the request and response details of this Moosend API endpoint to get a specific subscriber by ID.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list that contains the subscriber.

SubscriberID

path

string

true

The ID of the subscriber.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the subscriber:

    • ID - the ID of the subscriber.

    • Name - the name of the subscriber.

    • Email - the email address of the subscriber.

    • CreatedOn - the date-time the subscriber was added to the email list.

    • UnsubscribedOn - the date-time the subscriber was unsubscribed from the email list. This is null if not unsubscribed from the list.

    • UnsubscribedFromID - the ID that the subscriber is unsubscribed from.

    • SubscribeType - the status of the subscriber. For subscribed, this is 1, for unsubscribed, this is 2, for bounced, this is 3 , and for removed, this is 4.

    • SubscribeMethod - the method used to subscribe the member to the email list. For subscription forms, this is 0, for file imports, this is 1, for manually added, this is 2.

    • CustomFields - a list containing the custom fields of the new subscriber. Each custom field contains the following:

      • CustomFieldID - the ID of the custom field.

      • Name - the name of the custom field.

      • Value - the value of the custom field.

    • RemovedOn - the date-time the subscriber was removed from the email list.

    • Tags - a list containing the tags of the new subscriber.

Request
GET https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("subscribers/{MailingListID}/view.{Format}{?apikey}{?Email}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/subscribers/{MailingListID}/view.{Format}{?apikey}{?Email}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/find/{SubscriberID}.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "118e41dc-bb9e-435d-a86a-e5bd374668a8",
    "Name": "Some name",
    "Email": "getmoocampaigns+1@gmail.com",
    "CreatedOn": "/Date(1464952683773+0100)/",
    "UpdatedOn": "/Date(1465380328390+0100)/",
    "UnsubscribedOn": null,
    "UnsubscribedFromID": null,
    "SubscribeType": 4,
    "SubscribeMethod": 2,
    "CustomFields": [],
    "RemovedOn": "/Date(1465381597743+0100)/",
    "Tags": []
  }
}

Add a new subscriber

Abstract

Describes the request and response details of this Moosend API endpoint to add a new subscriber to an email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list where you want to add a new subscriber.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Name

body

string

false

The name of the new subscriber.

Email

body

string

true

The email address of the new subscriber.

HasExternalDoubleOptIn

body

Boolean

false

When true, it flags the added subscriber as having given subscription consent by other means.

CustomFields

body

array

false

A list of name-value pairs that match the subscriber’s custom fields defined in the email list.

For example, if you have two custom fields for Age and Country, you must specify the values for these two fields.

Tags

body

object

false

The member tag you can use to filter members by when working with an email list.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the new subscriber added to the email list:

    • ID - the ID of the subscriber.

    • Name - the name of the subscriber.

    • Email - the email address of the subscriber.

    • CreatedOn - the date-time the subscriber was added to the email list.

    • UnsubscribedOn - the date-time the subscriber was unsubscribed from the email list. This is null if not unsubscribed from the list.

    • UnsubscribedFromID - the ID that the subscriber is unsubscribed from.

    • SubscribeType - the status of the subscriber. For subscribed, this is 1, for unsubscribed, this is 2, for bounced, this is 3 , and for removed, this is 4.

    • SubscribeMethod - the method used to subscribe the member to the email list. For subscription forms, this is 0, for file imports, this is 1, for manually added, this is 2.

    • CustomFields - a list containing the custom fields of the new subscriber. Each custom field contains the following:

      • CustomFieldID - the ID of the custom field.

      • Name - the name of the custom field.

      • Value - the value of the custom field.

    • RemovedOn - the date-time the subscriber was removed from the email list.

    • Tags - a list containing the tags of the new subscriber.

Request
POST /v3/subscribers/{MailingListID}/subscribe.{Format}?apikey= HTTP/1.1
Host: {hostname}
User-Agent: curl/8.0.1
Content-Type: application/json
Accept: application/json
Content-Length: 206

{
    "Name" : "Paul",
    "Email" : "someEmail@email.com",
    "HasExternalDoubleOptIn": false,
    "CustomFields": [
        "Age=25",
        "Country=USA"
    ],
    "Tags": [
        "repeater"
    ]
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\" : \"Paul\",
    \"Email\" : \"someEmail@email.com\",
    \"HasExternalDoubleOptIn\": false,
    \"CustomFields\": [
        \"Age=25\",
        \"Country=USA\"
    ],
    \"Tags\": [
        \"repeater\"
    ]
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey='
Request

Request
$.ajax({
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=',
  crossDomain: true,
  method: 'post',
  headers: {
    'Accept': 'application/json'
  },
  contentType: 'application/json',
  // data: '{\n    "Name" : "Paul",\n    "Email" : "someEmail@email.com",\n    "HasExternalDoubleOptIn": false,\n    "CustomFields": [\n        "Age=25",\n        "Country=USA"\n    ],\n    "Tags": [\n        "repeater"\n    ]\n}',
  data: JSON.stringify({
    'Name': 'Paul',
    'Email': 'someEmail@email.com',
    'HasExternalDoubleOptIn': false,
    'CustomFields': [
      'Age=25',
      'Country=USA'
    ],
    'Tags': [
      'repeater'
    ]
  })
}).done(function(response) {
  console.log(response);
});
Request
var request = require('request');

var headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
};

var dataString = '{\n    "Name" : "Paul",\n    "Email" : "someEmail@email.com",\n    "HasExternalDoubleOptIn": false,\n    "CustomFields": [\n        "Age=25",\n        "Country=USA"\n    ],\n    "Tags": [\n        "repeater"\n    ]\n}';

var options = {
    url: 'https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=',
    method: 'POST',
    headers: headers,
    body: dataString
};

function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
    }
}

request(options, callback);
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "Paul",  "Email": "someEmail@email.com",  "HasExternalDoubleOptIn": false,  "CustomFields": [    "Age=25",    "Country=USA"  ]}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
import requests

headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
}

params = {
    'apikey': '',
}

json_data = {
    'Name': 'Paul',
    'Email': 'someEmail@email.com',
    'HasExternalDoubleOptIn': False,
    'CustomFields': [
        'Age=25',
        'Country=USA',
    ],
    'Tags': [
        'repeater',
    ],
}

response = requests.post(
    'https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}',
    params=params,
    headers=headers,
    json=json_data,
)

# Note: json_data will not be serialized by requests
# exactly as it was in the original request.
#data = '{\n    "Name" : "Paul",\n    "Email" : "someEmail@email.com",\n    "HasExternalDoubleOptIn": false,\n    "CustomFields": [\n        "Age=25",\n        "Country=USA"\n    ],\n    "Tags": [\n        "repeater"\n    ]\n}'
#response = requests.post(
#    'https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}',
#    params=params,
#    headers=headers,
#    data=data,
#)
Request
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Accept: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n    \"Name\" : \"Paul\",\n    \"Email\" : \"someEmail@email.com\",\n    \"HasExternalDoubleOptIn\": false,\n    \"CustomFields\": [\n        \"Age=25\",\n        \"Country=USA\"\n    ],\n    \"Tags\": [\n        \"repeater\"\n    ]\n}");

$response = curl_exec($ch);

curl_close($ch);
Request
require 'net/http'
require 'json'

uri = URI('https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}')
params = {
  :apikey => '',
}
uri.query = URI.encode_www_form(params)

req = Net::HTTP::Post.new(uri)
req.content_type = 'application/json'
req['Accept'] = 'application/json'

# The object won't be serialized exactly like this
# req.body = "{\n    \"Name\" : \"Paul\",\n    \"Email\" : \"someEmail@email.com\",\n    \"HasExternalDoubleOptIn\": false,\n    \"CustomFields\": [\n        \"Age=25\",\n        \"Country=USA\"\n    ],\n    \"Tags\": [\n        \"repeater\"\n    ]\n}"
req.body = {
  'Name' => 'Paul',
  'Email' => 'someEmail@email.com',
  'HasExternalDoubleOptIn' => false,
  'CustomFields' => [
    'Age=25',
    'Country=USA'
  ],
  'Tags' => [
    'repeater'
  ]
}.to_json

req_options = {
  use_ssl: uri.scheme == 'https'
}
res = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(req)
end
Request
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"strings"
)

func main() {
	client := &http.Client{}
	var data = strings.NewReader(`{
    "Name" : "Paul",
    "Email" : "someEmail@email.com",
    "HasExternalDoubleOptIn": false,
    "CustomFields": [
        "Age=25",
        "Country=USA"
    ],
    "Tags": [
        "repeater"
    ]
}`)
	req, err := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=", data)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	bodyText, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s\n", bodyText)
}
Request
using System.Net.Http;
using System.Net.Http.Headers;

HttpClient client = new HttpClient();

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=");

request.Headers.Add("Accept", "application/json");

request.Content = new StringContent("{\n    \"Name\" : \"Paul\",\n    \"Email\" : \"someEmail@email.com\",\n    \"HasExternalDoubleOptIn\": false,\n    \"CustomFields\": [\n        \"Age=25\",\n        \"Country=USA\"\n    ],\n    \"Tags\": [\n        \"repeater\"\n    ]\n}");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""Paul\"",
  \""Email\"": \""someEmail@email.com\"",
  \""HasExternalDoubleOptIn\"": false,
  \""CustomFields\"": [
    \""Age=25\"",
    \""Country=USA\""
  ]
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "Paul",
  "Email": "someEmail@email.com",
  "HasExternalDoubleOptIn": false,
  "CustomFields": [
    "Age=25",
    "Country=USA"
  ]
}')
response = client.post( path : "/subscribers/{MailingListID}/subscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
#import <Foundation/Foundation.h>

NSURL *url = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey="];
NSDictionary *headers = @{
    @"Content-Type": @"application/json",
    @"Accept": @"application/json"
};

NSMutableData *data = [[NSMutableData alloc] initWithData:[@"{\n    \"Name\" : \"Paul\",\n    \"Email\" : \"someEmail@email.com\",\n    \"HasExternalDoubleOptIn\": false,\n    \"CustomFields\": [\n        \"Age=25\",\n        \"Country=USA\"\n    ],\n    \"Tags\": [\n        \"repeater\"\n    ]\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:data];

NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
        NSLog(@"%@", error);
    } else {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        NSLog(@"%@", httpResponse);
    }
}];
[dataTask resume];
Request
import Foundation

let jsonData = [
    "Name": "Paul",
    "Email": "someEmail@email.com",
    "HasExternalDoubleOptIn": false,
    "CustomFields": [
        "Age=25",
        "Country=USA"
    ],
    "Tags": [
        "repeater"
    ]
] as [String : Any]
let data = try! JSONSerialization.data(withJSONObject: jsonData, options: [])
// let data = "{\n    \"Name\" : \"Paul\",\n    \"Email\" : \"someEmail@email.com\",\n    \"HasExternalDoubleOptIn\": false,\n    \"CustomFields\": [\n        \"Age=25\",\n        \"Country=USA\"\n    ],\n    \"Tags\": [\n        \"repeater\"\n    ]\n}".data(using: .utf8)

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/subscribe.{Format}?apikey=")!
let headers = [
    "Content-Type": "application/json",
    "Accept": "application/json"
]

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = data as Data

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let error = error {
        print(error)
    } else if let data = data {
        let str = String(data: data, encoding: .utf8)
        print(str ?? "")
    }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "f582c388-7916-4890-a9ab-b592615ef095",
    "Name": "Paul",
    "Email": "someemail@email.com",
    "CreatedOn": "/Date(1465379934028)/",
    "UpdatedOn": "/Date(1465379934028)/",
    "UnsubscribedOn": null,
    "UnsubscribedFromID": null,
    "SubscribeType": 1,
    "SubscribeMethod": 2,
    "CustomFields": [
      {
        "CustomFieldID": "728f6774-37ea-4d81-8607-ce8308136760",
        "Name": "Age",
        "Value": "25"
      },
      {
        "CustomFieldID": "b6380e04-c3a6-425b-9931-d25897fa4752",
        "Name": "Country",
        "Value": "USA"
      }
    ],
    "RemovedOn": null,
    "Tags": [
       "potential",
       "repeater"
    ]  
    }
}

Add multiple subscribers

Abstract

Describes the request and response details of this Moosend API endpoint to add multiple subscribers to an email list in a single request.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list where you want to add multiple subscribers.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

HasExternalDoubleOptIn

body

Boolean

false

When true, it flags the added subscribers as having given their subscription consent by other means.

Subscribers

body

array

true

A list containing up to 1000 subscribers that you are adding to the email list. You must specify the Name, Email, and CustomFields for each subscriber.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Erros - the response error message that shows how many and which emails are invalid. It is null if all emails are valid.

  • Context - an object that contains all the following information for each new subscriber added to the email list:

    • ID - the ID of the subscriber.

    • Name - the name of the subscriber.

    • Email - the email address of the subscriber.

    • CreatedOn - the date-time the subscriber was added to the email list.

    • UnsubscribedOn - the date-time the subscriber was unsubscribed from the email list. This is null if not unsubscribed from the list.

    • UnsubscribedFromID - the ID that the subscriber is unsubscribed from.

    • SubscribeType - the status of the subscriber. For subscribed, this is 1, for unsubscribed, this is 2, for bounced, this is 3 , and for removed, this is 4.

    • SubscribeMethod - the method used to subscribe the member to the email list. For subscription forms, this is 0, for file imports, this is 1, for manually added, this is 2.

    • CustomFields - a list containing the custom fields of the new subscriber. Each custom field contains the following:

      • CustomFieldID - the ID of the custom field.

      • Name - the name of the custom field.

      • Value - the value of the custom field.

    • RemovedOn - the date-time the subscriber was removed from the email list.

    • Tags - a list containing the tags of the new subscriber.

Request
POST /v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey= HTTP/1.1
Host: {hostname}
User-Agent: curl/8.0.1
Content-Type: application/json
Accept: application/json
Content-Length: 447

{  
    "HasExternalDoubleOptIn": false,
    "Subscribers":[  
      {  
         "Name":"test1Email",
         "Email":"test1@test.com",
         "CustomFields":[  
            "Country=UK"
         ]
      },
      {  
         "Name":"test2133Email",
         "Email":"test2133@test.com",
         "CustomFields":[  
            "Age=25",
            "Country=USA"
         ],
         "Tags": [
            "repeater"
         ]
      }
   ]
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{  
    \"HasExternalDoubleOptIn\": false,
    \"Subscribers\":[  
      {  
         \"Name\":\"test1Email\",
         \"Email\":\"test1@test.com\",
         \"CustomFields\":[  
            \"Country=UK\"
         ]
      },
      {  
         \"Name\":\"test2133Email\",
         \"Email\":\"test2133@test.com\",
         \"CustomFields\":[  
            \"Age=25\",
            \"Country=USA\"
         ],
         \"Tags\": [
            \"repeater\"
         ]
      }
   ]
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey='
Request
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey="))
    .POST(BodyPublishers.ofString("{  \n    \"HasExternalDoubleOptIn\": false,\n    \"Subscribers\":[  \n      {  \n         \"Name\":\"test1Email\",\n         \"Email\":\"test1@test.com\",\n         \"CustomFields\":[  \n            \"Country=UK\"\n         ]\n      },\n      {  \n         \"Name\":\"test2133Email\",\n         \"Email\":\"test2133@test.com\",\n         \"CustomFields\":[  \n            \"Age=25\",\n            \"Country=USA\"\n         ],\n         \"Tags\": [\n            \"repeater\"\n         ]\n      }\n   ]\n}"))
    .setHeader("Content-Type", "application/json")
    .setHeader("Accept", "application/json")
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Request
$.ajax({
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=',
  crossDomain: true,
  method: 'post',
  headers: {
    'Accept': 'application/json'
  },
  contentType: 'application/json',
  // data: '{  \n    "HasExternalDoubleOptIn": false,\n    "Subscribers":[  \n      {  \n         "Name":"test1Email",\n         "Email":"test1@test.com",\n         "CustomFields":[  \n            "Country=UK"\n         ]\n      },\n      {  \n         "Name":"test2133Email",\n         "Email":"test2133@test.com",\n         "CustomFields":[  \n            "Age=25",\n            "Country=USA"\n         ],\n         "Tags": [\n            "repeater"\n         ]\n      }\n   ]\n}',
  data: JSON.stringify({
    'HasExternalDoubleOptIn': false,
    'Subscribers': [
      {
        'Name': 'test1Email',
        'Email': 'test1@test.com',
        'CustomFields': [
          'Country=UK'
        ]
      },
      {
        'Name': 'test2133Email',
        'Email': 'test2133@test.com',
        'CustomFields': [
          'Age=25',
          'Country=USA'
        ],
        'Tags': [
          'repeater'
        ]
      }
    ]
  })
}).done(function(response) {
  console.log(response);
});
Request
var request = require('request');

var headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
};

var dataString = '{  \n    "HasExternalDoubleOptIn": false,\n    "Subscribers":[  \n      {  \n         "Name":"test1Email",\n         "Email":"test1@test.com",\n         "CustomFields":[  \n            "Country=UK"\n         ]\n      },\n      {  \n         "Name":"test2133Email",\n         "Email":"test2133@test.com",\n         "CustomFields":[  \n            "Age=25",\n            "Country=USA"\n         ],\n         "Tags": [\n            "repeater"\n         ]\n      }\n   ]\n}';

var options = {
    url: 'https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=',
    method: 'POST',
    headers: headers,
    body: dataString
};

function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
    }
}

request(options, callback);
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "HasExternalDoubleOptIn": false,  "Subscribers": [    {      "Name": "test1Email",      "Email": "test1@test.com",      "CustomFields": [        "Country=UK"      ]    },    {      "Name": "test2133Email",      "Email": "test2133@test.com",      "CustomFields": [        "Age=25",        "Country=USA"      ]    }  ]}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
import requests

headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
}

params = {
    'apikey': '',
}

json_data = {
    'HasExternalDoubleOptIn': False,
    'Subscribers': [
        {
            'Name': 'test1Email',
            'Email': 'test1@test.com',
            'CustomFields': [
                'Country=UK',
            ],
        },
        {
            'Name': 'test2133Email',
            'Email': 'test2133@test.com',
            'CustomFields': [
                'Age=25',
                'Country=USA',
            ],
            'Tags': [
                'repeater',
            ],
        },
    ],
}

response = requests.post(
    'https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}',
    params=params,
    headers=headers,
    json=json_data,
)

# Note: json_data will not be serialized by requests
# exactly as it was in the original request.
#data = '{  \n    "HasExternalDoubleOptIn": false,\n    "Subscribers":[  \n      {  \n         "Name":"test1Email",\n         "Email":"test1@test.com",\n         "CustomFields":[  \n            "Country=UK"\n         ]\n      },\n      {  \n         "Name":"test2133Email",\n         "Email":"test2133@test.com",\n         "CustomFields":[  \n            "Age=25",\n            "Country=USA"\n         ],\n         "Tags": [\n            "repeater"\n         ]\n      }\n   ]\n}'
#response = requests.post(
#    'https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}',
#    params=params,
#    headers=headers,
#    data=data,
#)
Request
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Accept: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{  \n    \"HasExternalDoubleOptIn\": false,\n    \"Subscribers\":[  \n      {  \n         \"Name\":\"test1Email\",\n         \"Email\":\"test1@test.com\",\n         \"CustomFields\":[  \n            \"Country=UK\"\n         ]\n      },\n      {  \n         \"Name\":\"test2133Email\",\n         \"Email\":\"test2133@test.com\",\n         \"CustomFields\":[  \n            \"Age=25\",\n            \"Country=USA\"\n         ],\n         \"Tags\": [\n            \"repeater\"\n         ]\n      }\n   ]\n}");

$response = curl_exec($ch);

curl_close($ch);
Request
require 'net/http'
require 'json'

uri = URI('https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}')
params = {
  :apikey => '',
}
uri.query = URI.encode_www_form(params)

req = Net::HTTP::Post.new(uri)
req.content_type = 'application/json'
req['Accept'] = 'application/json'

# The object won't be serialized exactly like this
# req.body = "{  \n    \"HasExternalDoubleOptIn\": false,\n    \"Subscribers\":[  \n      {  \n         \"Name\":\"test1Email\",\n         \"Email\":\"test1@test.com\",\n         \"CustomFields\":[  \n            \"Country=UK\"\n         ]\n      },\n      {  \n         \"Name\":\"test2133Email\",\n         \"Email\":\"test2133@test.com\",\n         \"CustomFields\":[  \n            \"Age=25\",\n            \"Country=USA\"\n         ],\n         \"Tags\": [\n            \"repeater\"\n         ]\n      }\n   ]\n}"
req.body = {
  'HasExternalDoubleOptIn' => false,
  'Subscribers' => [
    {
      'Name' => 'test1Email',
      'Email' => 'test1@test.com',
      'CustomFields' => [
        'Country=UK'
      ]
    },
    {
      'Name' => 'test2133Email',
      'Email' => 'test2133@test.com',
      'CustomFields' => [
        'Age=25',
        'Country=USA'
      ],
      'Tags' => [
        'repeater'
      ]
    }
  ]
}.to_json

req_options = {
  use_ssl: uri.scheme == 'https'
}
res = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(req)
end
Request
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"strings"
)

func main() {
	client := &http.Client{}
	var data = strings.NewReader(`{  
    "HasExternalDoubleOptIn": false,
    "Subscribers":[  
      {  
         "Name":"test1Email",
         "Email":"test1@test.com",
         "CustomFields":[  
            "Country=UK"
         ]
      },
      {  
         "Name":"test2133Email",
         "Email":"test2133@test.com",
         "CustomFields":[  
            "Age=25",
            "Country=USA"
         ],
         "Tags": [
            "repeater"
         ]
      }
   ]
}`)
	req, err := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=", data)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	bodyText, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s\n", bodyText)
}
Request
using System.Net.Http;
using System.Net.Http.Headers;

HttpClient client = new HttpClient();

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=");

request.Headers.Add("Accept", "application/json");

request.Content = new StringContent("{  \n    \"HasExternalDoubleOptIn\": false,\n    \"Subscribers\":[  \n      {  \n         \"Name\":\"test1Email\",\n         \"Email\":\"test1@test.com\",\n         \"CustomFields\":[  \n            \"Country=UK\"\n         ]\n      },\n      {  \n         \"Name\":\"test2133Email\",\n         \"Email\":\"test2133@test.com\",\n         \"CustomFields\":[  \n            \"Age=25\",\n            \"Country=USA\"\n         ],\n         \"Tags\": [\n            \"repeater\"\n         ]\n      }\n   ]\n}");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""HasExternalDoubleOptIn\"": false,
  \""Subscribers\"": [
    {
      \""Name\"": \""test1Email\"",
      \""Email\"": \""test1@test.com\"",
      \""CustomFields\"": [
        \""Country=UK\""
      ]
    },
    {
      \""Name\"": \""test2133Email\"",
      \""Email\"": \""test2133@test.com\"",
      \""CustomFields\"": [
        \""Age=25\"",
        \""Country=USA\""
      ]
    }
  ]
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "HasExternalDoubleOptIn": false,
  "Subscribers": [
    {
      "Name": "test1Email",
      "Email": "test1@test.com",
      "CustomFields": [
        "Country=UK"
      ]
    },
    {
      "Name": "test2133Email",
      "Email": "test2133@test.com",
      "CustomFields": [
        "Age=25",
        "Country=USA"
      ]
    }
  ]
}')
response = client.post( path : "/subscribers/{MailingListID}/subscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
#import <Foundation/Foundation.h>

NSURL *url = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey="];
NSDictionary *headers = @{
    @"Content-Type": @"application/json",
    @"Accept": @"application/json"
};

NSMutableData *data = [[NSMutableData alloc] initWithData:[@"{  \n    \"HasExternalDoubleOptIn\": false,\n    \"Subscribers\":[  \n      {  \n         \"Name\":\"test1Email\",\n         \"Email\":\"test1@test.com\",\n         \"CustomFields\":[  \n            \"Country=UK\"\n         ]\n      },\n      {  \n         \"Name\":\"test2133Email\",\n         \"Email\":\"test2133@test.com\",\n         \"CustomFields\":[  \n            \"Age=25\",\n            \"Country=USA\"\n         ],\n         \"Tags\": [\n            \"repeater\"\n         ]\n      }\n   ]\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:data];

NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
        NSLog(@"%@", error);
    } else {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        NSLog(@"%@", httpResponse);
    }
}];
[dataTask resume];
Request
import Foundation

let jsonData = [
    "HasExternalDoubleOptIn": false,
    "Subscribers": [
        [
            "Name": "test1Email",
            "Email": "test1@test.com",
            "CustomFields": [
                "Country=UK"
            ]
        ],
        [
            "Name": "test2133Email",
            "Email": "test2133@test.com",
            "CustomFields": [
                "Age=25",
                "Country=USA"
            ],
            "Tags": [
                "repeater"
            ]
        ]
    ]
] as [String : Any]
let data = try! JSONSerialization.data(withJSONObject: jsonData, options: [])
// let data = "{  \n    \"HasExternalDoubleOptIn\": false,\n    \"Subscribers\":[  \n      {  \n         \"Name\":\"test1Email\",\n         \"Email\":\"test1@test.com\",\n         \"CustomFields\":[  \n            \"Country=UK\"\n         ]\n      },\n      {  \n         \"Name\":\"test2133Email\",\n         \"Email\":\"test2133@test.com\",\n         \"CustomFields\":[  \n            \"Age=25\",\n            \"Country=USA\"\n         ],\n         \"Tags\": [\n            \"repeater\"\n         ]\n      }\n   ]\n}".data(using: .utf8)

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/subscribe_many.{Format}?apikey=")!
let headers = [
    "Content-Type": "application/json",
    "Accept": "application/json"
]

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = data as Data

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let error = error {
        print(error)
    } else if let data = data {
        let str = String(data: data, encoding: .utf8)
        print(str ?? "")
    }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": "2 items with invalid email address were ignored: email@email, email2@email",
  "Context": [
    {
      "ID": "ca506fc5-0967-4756-8848-74e9766bdbdd",
      "Name": "test1Email",
      "Email": "test1@test.com",
      "CreatedOn": "/Date(1465377493907+0100)/",
      "UpdatedOn": "/Date(1465381164389)/",
      "UnsubscribedOn": null,
      "UnsubscribedFromID": null,
      "SubscribeType": 1,
      "SubscribeMethod": 1,
      "CustomFields": [
        {
          "CustomFieldID": "42acf2cf-1096-4c80-960b-051791d9a276",
          "Name": "Country",
          "Value": "UK"
        }
      ],
      "RemovedOn": null,
      "Tags": [
            "potential",
            "repeater"
        ]
    },
    {
      "ID": "b751f349-f6b3-4b14-8d75-c37dfafbe40a",
      "Name": "test2133Email",
      "Email": "test2133@test.com",
      "CreatedOn": "/Date(1465377493907+0100)/",
      "UpdatedOn": "/Date(1465381164389)/",
      "UnsubscribedOn": null,
      "UnsubscribedFromID": null,
      "SubscribeType": 1,
      "SubscribeMethod": 1,
      "CustomFields": [
        {
          "CustomFieldID": "60d4e2b0-e5ae-4737-9ac5-ce071ab346fb",
          "Name": "Age",
          "Value": 25
        },
        {
          "CustomFieldID": "42acf2cf-1096-4c80-960b-051791d9a276",
          "Name": "Country",
          "Value": "USA"
        }
      ],
      "RemovedOn": null,
      "Tags": [
            "potential",
            "repeater"
        ]
    }
  ]
}

Update a subscriber

Abstract

Describes the request and response details of this Moosend API endpoint to update a subscriber in your email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list that contains the subscriber.

SubscriberID

path

string

true

The ID of the subscriber that you want to update.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account

Name

body

string

false

The name of the subscriber.

Email

body

string

true

The email address of the subscriber.

HasExternalDoubleOptIn

body

Boolean

false

When true, it flags the added subscriber as having given subscription consent by other means.

CustomFields

body

array

false

A list of name-value pairs that match the subscriber’s custom fields defined in the email list.

For example, if you have two custom fields for Age and Country, you must specify the values for these two fields.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the updated subscriber:

    • ID - the ID of the subscriber.

    • Name - the name of the subscriber.

    • Email - the email address of the subscriber.

    • CreatedOn - the date-time the subscriber was added to the email list.

    • UnsubscribedOn - the date-time the subscriber was unsubscribed from the email list. This is null if not unsubscribed from the list.

    • UnsubscribedFromID - the ID that the subscriber is unsubscribed from.

    • SubscribeType - the status of the subscriber. For subscribed, this is 1, for unsubscribed, this is 2, for bounced, this is 3 , and for removed, this is 4.

    • SubscribeMethod - the method used to subscribe the member to the email list. For subscription forms, this is 0, for file imports, this is 1, for manually added, this is 2.

    • CustomFields - a list containing the custom fields of the new subscriber. Each custom field contains the following:

      • CustomFieldID - the ID of the custom field.

      • Name - the name of the custom field.

      • Value - the value of the custom field.

    • RemovedOn - the date-time the subscriber was removed from the email list.

    • Tags - a list containing the tags of the new subscriber.

Request
POST https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=

Request body:
{
  "Name": "Some Name",
  "HasExternalDoubleOptIn": false,
  "Email": "someEmail@email.com",
  "CustomFields": [
    "Age=25",
    "Country=USA"
  ]
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\" : \"Some Name\",
    \"HasExternalDoubleOptIn\": false,
    \"Email\" : \"someEmail@email.com\",
    \"CustomFields\": [
        \"Age=25\",
        \"Country=USA\"
    ]
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"Some Name\",  \"HasExternalDoubleOptIn\": false,  \"Email\": \"someEmail@email.com\",  \"CustomFields\": [    \"Age=25\",    \"Country=USA\"  ]}");
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'Some Name',
  'HasExternalDoubleOptIn': false,
  'Email': 'someEmail@email.com',
  'CustomFields': [
    'Age=25',
    'Country=USA'
  ]
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"Some Name\",  \"HasExternalDoubleOptIn\": false,  \"Email\": \"someEmail@email.com\",  \"CustomFields\": [    \"Age=25\",    \"Country=USA\"  ]}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "Some Name",  "HasExternalDoubleOptIn": false,  "Email": "someEmail@email.com",  "CustomFields": [    "Age=25",    "Country=USA"  ]}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "Some Name",
    "HasExternalDoubleOptIn": false,
    "Email": "someEmail@email.com",
    "CustomFields": [
      "Age=25",
      "Country=USA"
    ]
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"Some Name\",
  \"HasExternalDoubleOptIn\": false,
  \"Email\": \"someEmail@email.com\",
  \"CustomFields\": [
    \"Age=25\",
    \"Country=USA\"
  ]
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "Some Name",
  "HasExternalDoubleOptIn": false,
  "Email": "someEmail@email.com",
  "CustomFields": [
    "Age=25",
    "Country=USA"
  ]
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"Some Name\",\n  \"HasExternalDoubleOptIn\": false,\n  \"Email\": \"someEmail@email.com\",\n  \"CustomFields\": [\n    \"Age=25\",\n    \"Country=USA\"\n  ]\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"Some Name\",  \"HasExternalDoubleOptIn\": false,  \"Email\": \"someEmail@email.com\",  \"CustomFields\": [    \"Age=25\",    \"Country=USA\"  ]}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("subscribers/{MailingListID}/subscribe.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""Some Name\"",
  \""HasExternalDoubleOptIn\"": false,
  \""Email\"": \""someEmail@email.com\"",
  \""CustomFields\"": [
    \""Age=25\"",
    \""Country=USA\""
  ]
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "Some Name",
  "HasExternalDoubleOptIn": false,
  "Email": "someEmail@email.com",
  "CustomFields": [
    "Age=25",
    "Country=USA"
  ]
}')
response = client.post( path : "/subscribers/{MailingListID}/subscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"Some Name\",\n  \"HasExternalDoubleOptIn\": false,\n  \"Email\": \"someEmail@email.com\",\n  \"CustomFields\": [\n    \"Age=25\",\n    \"Country=USA\"\n  ]\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/update/{SubscriberID}.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"Some Name\",\n  \"HasExternalDoubleOptIn\": false,\n  \"Email\": \"someEmail@email.com\",\n  \"CustomFields\": [\n    \"Age=25\",\n    \"Country=USA\"\n  ]\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "d75fca65-a2bc-4474-bd4d-307f9cf63a57",
    "Name": "Some name",
    "Email": "someEmail@email.com",
    "CreatedOn": "/Date(1465380655880+0100)/",
    "UpdatedOn": "/Date(1465388373874)/",
    "UnsubscribedOn": null,
    "UnsubscribedFromID": null,
    "SubscribeType": 1,
    "SubscribeMethod": 2,
    "CustomFields": [
      {
        "CustomFieldID": "b9a6cb39-ec8f-4e5e-a41a-b64b9b3fc190",
        "Name": "Age",
        "Value": 25
      },
      {
        "CustomFieldID": "1c4ff8dc-48e3-4af1-ae4f-2b1b81a44d17",
        "Name": "Country",
        "Value": "USA"
      }
    ],
    "RemovedOn": null
  }
}

Unsubscribe a subscriber from an account

Abstract

Describes the request and response details of this Moosend API endpoint to unsubscribe a subscriber from all email lists in an account.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Email

body

string

true

The email address of the subscriber.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=

Request body:
{
  "Email": "test1@test.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Email\":\"test1@test.com\"
}" \
'https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Email\": \"test1@test.com\"}");
Response response = client.target("https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Email': 'test1@test.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Email\": \"test1@test.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Email": "test1@test.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Email": "test1@test.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Email\": \"test1@test.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Email": "test1@test.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Email\": \"test1@test.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Email\": \"test1@test.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("subscribers/unsubscribe.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Email\"": \""test1@test.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Email": "test1@test.com"
}')
response = client.post( path : "/subscribers/unsubscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Email\": \"test1@test.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/unsubscribe.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Email\": \"test1@test.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Unsubscribe a subscriber from a mailing list

Abstract

Describes the request and response details of this Moosend API endpoint to unsubscribe a subscriber from an email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list from which you want to unsubscribe a subscriber.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Email

body

string

true

The email address of the subscriber.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=

Request body:
{
  "Email": "test1@test.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Email\":\"test1@test.com\"
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Email\": \"test1@test.com\"}");
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Email': 'test1@test.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Email\": \"test1@test.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Email": "test1@test.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Email": "test1@test.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Email\": \"test1@test.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Email": "test1@test.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Email\": \"test1@test.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Email\": \"test1@test.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("subscribers/unsubscribe.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Email\"": \""test1@test.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Email": "test1@test.com"
}')
response = client.post( path : "/subscribers/unsubscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Email\": \"test1@test.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/unsubscribe.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Email\": \"test1@test.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Unsubscribe a subscriber from a mailing list and a campaign

Abstract

Describes the request and response details of this Moosend API endpoint to unsubscribe a subscriber from an email list and a campaign.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list from which you want to unsubscribe a subscriber.

CampaignID

path

string

true

The ID of the campaign sent to the specific email list.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Email

body

string

true

The email address of the subscriber.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=

Request body:
{
  "Email": "test1@test.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Email\":\"test1@test.com\"
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Email\": \"test1@test.com\"}");
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Email': 'test1@test.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Email\": \"test1@test.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Email": "test1@test.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Email": "test1@test.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Email\": \"test1@test.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Email": "test1@test.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Email\": \"test1@test.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Email\": \"test1@test.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("subscribers/unsubscribe.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Email\"": \""test1@test.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Email": "test1@test.com"
}')
response = client.post( path : "/subscribers/unsubscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Email\": \"test1@test.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/{CampaignID}/unsubscribe.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Email\": \"test1@test.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Remove a subscriber

Abstract

Describes the request and response details of this Moosend API endpoint to remove a subscriber from a specific email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list that contains the subscriber you want to remove.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Email

body

string

true

The email address of the subscriber.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=

Request body:
{
  "Email": "test1@test.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Email\":\"test1@test.com\"
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Email\": \"test1@test.com\"}");
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Email': 'test1@test.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Email\": \"test1@test.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Email": "test1@test.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Email": "test1@test.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Email\": \"test1@test.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Email": "test1@test.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Email\": \"test1@test.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Email\": \"test1@test.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("subscribers/unsubscribe.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Email\"": \""test1@test.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Email": "test1@test.com"
}')
response = client.post( path : "/subscribers/unsubscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Email\": \"test1@test.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/remove.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Email\": \"test1@test.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Remove multiple subscribers

Abstract

Describes the request and response details of the Moosend API endpoint to remove multiple subscribers from a specific email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list that contains the subscribers you want to remove.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Emails

body

object

true

A list of subscriber email addresses that you want to remove from the email list. Use a comma (,) to separate the email addresses.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains the following information:

    • EmailsIgnored - the number of ignored email addresses.

    • EmailsProcessed - the number of processed email addresses.

Request
POST https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=

Request body:
{
  "Emails": "someEmail@email.com,someEmail2@email.com,someEmail3@email.com"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{  
   \"Emails\":\"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"
}" \
'https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"}");
Response response = client.target("https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Emails': 'someEmail@email.com,someEmail2@email.com,someEmail3@email.com'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Emails": "someEmail@email.com,someEmail2@email.com,someEmail3@email.com"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Emails": "someEmail@email.com,someEmail2@email.com,someEmail3@email.com"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Emails": "someEmail@email.com,someEmail2@email.com,someEmail3@email.com"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("subscribers/unsubscribe.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Emails\"": \""someEmail@email.com,someEmail2@email.com,someEmail3@email.com\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Emails": "someEmail@email.com,someEmail2@email.com,someEmail3@email.com"
}')
response = client.post( path : "/subscribers/unsubscribe.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/subscribers/{MailingListID}/remove_many.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Emails\": \"someEmail@email.com,someEmail2@email.com,someEmail3@email.com\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "EmailsIgnored": 0,
    "EmailsProcessed": 3
  }
}

Campaigns

Abstract

Describes how to use the Moosend API to get, clone, update, delete, test, and send campaigns, including how to fetch campaign statistics.

Use the Moosend API to fetch your campaigns, get details about campaigns, fetch your campaign senders and their details, create, clone, update, delete, test, and send campaigns. The API also lets you fetch campaign statistics, activity by location, link activity, and campaign summaries.

Get all campaigns by page

Abstract

Describes the request and response details of this Moosend API endpoint to get all campaigns in your account with paging information.

Request

Parameter

In

Type

Required

Description

Page

path

number

false

The page number to display results for.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the information for the requested campaigns:

    • Paging - an object that contains the following information:

      • PageSize - the page size of the results. This is 0 if not defined.

      • CurrentPage - the number of the result page. This is 1 if not defined.

      • Totalresults - the number of campaigns that are included in the response.

      • TotalPageCount - the number of all the available campaign pages for your account.

      • SortExpression - the sort expression associated with the column or columns being sorted.

      • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

    • ID - the ID of the campaign.

    • Name - the name of the campaign.

    • Subject - the subject of the campaign.

    • SiteName - the site name of the account.

    • ConfirmationTo - the email address to which a confirmation message is sent when the campaign has been successfully sent.

    • CreatedOn - the date-time the requested campaign was created.

    • ABHoursToTest - specifies the total number of hours to test versions A and B of your campaign before sending the winning version. This is null if the campaign is not an A/B split test campaign.

    • ABCampaignType - specifies the type of the A/B split campaign test. Possible values are:

      • 0 - for a campaign sender test.

      • 1 - for a campaign content test.

      • 2 - for a subject line test.

    • ABWinner - specifies if the winning campaign is A or B. This is null if the campaign is not an A/B split test campaign.

    • ABWinnerSelectionType - specifies the method to determine the winning version for the test. This is null if the given campaign is not an A/B split test campaign, or one of the following values if it is:

      • 0 - the campaign version with the highest number of unique opens is selected to be sent to the rest of your list.

      • 1 - the campaign version with the highest number of unique clicks is selected to be sent to the rest of your list.

    • Status - status of the campaign. Possible values are the following:

      • 0 - draft

      • 1 - queued for sending

      • 3 - sent

      • 4 - not enough credits

      • 5 - awaiting delivery

      • 6 - sending

      • 10 - deleted

      • 11 - selecting a winner

      • 12 - archived

      • 13 - subscription expired

      • 14 - subscription limits exceeded

    • DeliveredOn - the date-time the campaign was delivered.

    • ScheduledFor - the date-time the campaign is scheduled to be delivered.

    • ScheduledForTimezone - the selected time zone for the scheduled campaign to be delivered.

    • MailingLists - a list of email lists selected for sending the campaign. It contains the following information for each email list:

      • Campaign - the campaign associated with this email list. This is null for this case.

      • MailingList - an object that contains the following information for each email list:

        • ID - the ID of the email list.

        • Name - the name of the email list.

        • ActiveMemberCount - the number of active members in the email list.

        • BouncedMemberCount - the number of bounced emails in the email list.

        • RemovedMemberCount - the number of removed emails in the email list.

        • UnsubscribedMemberCount - the number of unsubscribed emails in the email list.

        • Status - status of the email list. For created, this is 0, for imported, this is 1, for importing, this is 2 , and for deleted, this is 3.

        • CustomFieldsDefinition - an array containing the parameters of custom fields in the email list.

        • CreatedBy - the IP address used to create the email list.

        • CreatedOn - the date-time the email list was created.

        • UpdatedBy - the IP address used to update the email list.

        • UpdatedOn - the date-time that the email list was updated.

        • ImportOperation - an object that contains the details of the latest import operation performed in the email list.

      • Segment - a list of segments in the email list containing the following information for each segment. This is null if the campaign was not sent to any email list segment.

        • ID - the ID of the segment.

        • Name - the name of the segment.

        • MatchType - specifies how subscribers are returned by your segment based on matching criteria. Possible values are:

          • 0 - for All. Returns subscribers that match all the given criteria.

          • 1 - for Any. Returns subscribers that match any of the given criteria.

        • Criteria - contains a list with information for each selected criterion selected for the segment.

        • CreatedBy - the IP address used to create the segment.

        • CreatedOn - the date-time the requested segment was created.

        • UpdatedBy - the IP address used to update the segment.

        • UpdatedOn - the date-time the segment was updated.

        • FetchType - the selected fetch type for the selected segment criteria. Possible values are:

          • 0 - for all segment criteria.

          • 1 - for the top segment criteria.

          • 2 - for the top percent segment criteria.

        • Description - contains a string representation of all the selected filters, MatchType criteria, and FetchType criteria.

      • TotalSent - the total number of campaign emails sent.

      • TotalOpens - the total number of emails opens.

      • UniqueOpens - the total number of unique email opens.

      • TotalBounces - the total number of email bounces.

      • TotalForwards - the total number of email forwards for the campaign using the Forward to a friend personalization tag.

      • UniqueForwards - the total number of unique forwards for the campaign using the Forward to a friend personalization tag.

      • TotalLinkClicks - the total number of link clicks.

      • UniqueLinkClicks - the total number of unique link clicks.

      • RecipientsCount - the total number of recipients.

      • IsTransactional - this is false for this case.

      • TotalComplaints - the total number of complaints.

      • TotalUnsubscribes - the total number of unsubscribed recipients for the campaign.

Request
GET https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{Page}.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{Page}.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{Page}.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{Page}.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{Page}.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 10,
      "CurrentPage": 1,
      "TotalResults": 2,
      "TotalPageCount": 1,
      "SortExpression": null,
      "SortIsAscending": true
    },
    "Campaigns": [
      {
        "ID": "cbcb297d-52a8-4bed-ae85-640c37c92771",
        "Name": "Test Release 1",
        "Subject": "Test Release 1",
        "SiteName": "mysite",
        "ConfirmationTo": "andreas@email.com",
        "CreatedOn": "/Date(1464952661697+0100)/",
        "ABHoursToTest": null,
        "ABCampaignType": null,
        "ABWinner": null,
        "ABWinnerSelectionType": null,
        "Status": 3,
        "DeliveredOn": "/Date(1464952817450+0100)/",
        "ScheduledFor": null,
        "ScheduledForTimezone": "GTB Standard Time",
        "MailingLists": [
          {
            "Campaign": null,
            "MailingList": {
              "ID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b",
              "Name": "Some Name",
              "ActiveMemberCount": 0,
              "BouncedMemberCount": 0,
              "RemovedMemberCount": 0,
              "UnsubscribedMemberCount": 0,
              "Status": 0,
              "CustomFieldsDefinition": [],
              "CreatedBy": "212.205.224.198",
              "CreatedOn": "/Date(1464952667680+0100)/",
              "UpdatedBy": "212.205.224.198",
              "UpdatedOn": "/Date(1464952667680+0100)/",
              "ImportOperation": null
            },
            "Segment": null
          }
        ],
        "TotalSent": 1,
        "TotalOpens": 1,
        "UniqueOpens": 1,
        "TotalBounces": 0,
        "TotalForwards": 0,
        "UniqueForwards": 0,
        "TotalLinkClicks": 0,
        "UniqueLinkClicks": 0,
        "RecipientsCount": 1,
        "IsTransactional": false,
        "TotalComplaints": 0,
        "TotalUnsubscribes": 0
      },
      {
        "ID": "ef2ab040-aec8-46bf-be54-3d8311093015",
        "Name": "Performance Testing",
        "Subject": "Performance Testing",
        "SiteName": "mysite",
        "ConfirmationTo": "info@northweb.biz",
        "CreatedOn": "/Date(1464647633330+0100)/",
        "ABHoursToTest": null,
        "ABCampaignType": null,
        "ABWinner": null,
        "ABWinnerSelectionType": null,
        "Status": 3,
        "DeliveredOn": "/Date(1464647633207+0100)/",
        "ScheduledFor": null,
        "ScheduledForTimezone": "GTB Standard Time",
        "MailingLists": [
          {
            "Campaign": null,
            "MailingList": {
              "ID": "9b7611be-d395-4677-9983-697d261cca91",
              "Name": "Performance Testing",
              "ActiveMemberCount": 0,
              "BouncedMemberCount": 0,
              "RemovedMemberCount": 0,
              "UnsubscribedMemberCount": 0,
              "Status": 0,
              "CustomFieldsDefinition": [],
              "CreatedBy": "127.0.0.1",
              "CreatedOn": "/Date(1464647633220+0100)/",
              "UpdatedBy": "127.0.0.1",
              "UpdatedOn": "/Date(1464647633220+0100)/",
              "ImportOperation": null
            },
            "Segment": null
          }
        ],
        "TotalSent": 0,
        "TotalOpens": 0,
        "UniqueOpens": 0,
        "TotalBounces": 0,
        "TotalForwards": 0,
        "UniqueForwards": 0,
        "TotalLinkClicks": 0,
        "UniqueLinkClicks": 0,
        "RecipientsCount": 18561,
        "IsTransactional": false,
        "TotalComplaints": 0,
        "TotalUnsubscribes": 0
      }
    ]
  }
}

Get all campaigns by page and page size

Abstract

Describes the request and response details of this Moosend API endpoint to get all campaigns in your account with paging and page size information.

Request

Parameter

In

Type

Required

Description

Page

path

number

false

The page number to display results for. Returns the first page if not specified.

PageSize

path

number

false

The maximum number of results per page. This must be a positive integer up to 100.

Returns 10 results per page if not specified. If a value greater than 100 is specified, it is treated as 100.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

SortBy

query

string

false

The name of the campaign property to sort results by.

Possible values: Name, Subject, Status, DeliveredOn, and CreatedOn (Default).

SortMethod

query

any

false

Specifies the method to sort results.

Possible values: DESC for descending and ASC (Default) for ascending.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the information for the requested campaigns:

    • Paging - an object that contains the following information:

      • PageSize - the page size of the results. This is 0 if not defined.

      • CurrentPage - the number of the result page. This is 1 if not defined.

      • Totalresults - the number of campaigns that are included in the response.

      • TotalPageCount - the number of all the available campaign pages for your account.

      • SortExpression - the sort expression associated with the column or columns being sorted.

      • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

    • ID - the ID of the campaign.

    • Name - the name of the campaign.

    • Subject - the subject of the campaign.

    • SiteName - the site name of the account.

    • ConfirmationTo - the email address to which a confirmation message is sent when the campaign has been successfully sent.

    • CreatedOn - the date-time the requested campaign was created.

    • ABHoursToTest - specifies the total number of hours to test versions A and B of your campaign before sending the winning version. This is null if the campaign is not an A/B split test campaign.

    • ABCampaignType - specifies the type of the A/B split campaign test. Possible values are:

      • 0 - for a campaign sender test.

      • 1 - for a campaign content test.

      • 2 - for a subject line test.

    • ABWinner - specifies if the winning campaign is A or B. This is null if the campaign is not an A/B split test campaign.

    • ABWinnerSelectionType - specifies the method to determine the winning version for the test. This is null if the given campaign is not an A/B split test campaign, or one of the following values if it is:

      • 0 - the campaign version with the highest number of unique opens is selected to be sent to the rest of your list.

      • 1 - the campaign version with the highest number of unique clicks is selected to be sent to the rest of your list.

    • Status - status of the campaign. Possible values are the following:

      • 0 - draft

      • 1 - queued for sending

      • 3 - sent

      • 4 - not enough credits

      • 5 - awaiting delivery

      • 6 - sending

      • 10 - deleted

      • 11 - selecting a winner

      • 12 - archived

      • 13 - subscription expired

      • 14 - subscription limits exceeded

    • DeliveredOn - the date-time the campaign was delivered.

    • ScheduledFor - the date-time the campaign is scheduled to be delivered.

    • ScheduledForTimezone - the selected time zone for the scheduled campaign to be delivered.

    • MailingLists - a list of email lists selected for sending the campaign. It contains the following information for each email list:

      • Campaign - the campaign associated with this email list. This is null for this case.

      • MailingList - an object that contains the following information for each email list:

        • ID - the ID of the email list.

        • Name - the name of the email list.

        • ActiveMemberCount - the number of active members in the email list.

        • BouncedMemberCount - the number of bounced emails in the email list.

        • RemovedMemberCount - the number of removed emails in the email list.

        • UnsubscribedMemberCount - the number of unsubscribed emails in the email list.

        • Status - status of the email list. For created, this is 0, for imported, this is 1, for importing, this is 2 , and for deleted, this is 3.

        • CustomFieldsDefinition - an array containing the parameters of custom fields in the email list.

        • CreatedBy - the IP address used to create the email list.

        • CreatedOn - the date-time the email list was created.

        • UpdatedBy - the IP address used to update the email list.

        • UpdatedOn - the date-time that the email list was updated.

        • ImportOperation - an object that contains the details of the latest import operation performed in the email list.

      • Segment - a list of segments in the email list containing the following information for each segment. This is null if the campaign was not sent to any email list segment.

        • ID - the ID of the segment.

        • Name - the name of the segment.

        • MatchType - specifies how subscribers are returned by your segment based on matching criteria. Possible values are:

          • 0 - for All. Returns subscribers that match all the given criteria.

          • 1 - for Any. Returns subscribers that match any of the given criteria.

        • Criteria - contains a list with information for each selected criterion selected for the segment.

        • CreatedBy - the IP address used to create the segment.

        • CreatedOn - the date-time the requested segment was created.

        • UpdatedBy - the IP address used to update the segment.

        • UpdatedOn - the date-time the segment was updated.

        • FetchType - the selected fetch type for the selected segment criteria. Possible values are:

          • 0 - for all segment criteria.

          • 1 - for the top segment criteria.

          • 2 - for the top percent segment criteria.

        • Description - contains a string representation of all the selected filters, MatchType criteria, and FetchType criteria.

      • TotalSent - the total number of campaign emails sent.

      • TotalOpens - the total number of emails opens.

      • UniqueOpens - the total number of unique email opens.

      • TotalBounces - the total number of email bounces.

      • TotalForwards - the total number of email forwards for the campaign using the Forward to a friend personalization tag.

      • UniqueForwards - the total number of unique forwards for the campaign using the Forward to a friend personalization tag.

      • TotalLinkClicks - the total number of link clicks.

      • UniqueLinkClicks - the total number of unique link clicks.

      • RecipientsCount - the total number of recipients.

      • IsTransactional - this is false for this case.

      • TotalComplaints - the total number of complaints.

      • TotalUnsubscribes - the total number of unsubscribed recipients for the campaign.

Request
GET https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=
Request
curl --include \
'https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>dependencies

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{Page}/{PageSize}.{Format}?apikey=&SortBy=&SortMethod=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 5,
      "CurrentPage": 1,
      "TotalResults": 2,
      "TotalPageCount": 1,
      "SortExpression": null,
      "SortIsAscending": true
    },
    "Campaigns": [
      {
        "ID": "cbcb297d-52a8-4bed-ae85-640c37c92771",
        "Name": "Test Release 1",
        "Subject": "Test Release 1",
        "SiteName": "mysite",
        "ConfirmationTo": "andreas@email.com",
        "CreatedOn": "/Date(1464952661697+0100)/",
        "ABHoursToTest": null,
        "ABCampaignType": null,
        "ABWinner": null,
        "ABWinnerSelectionType": null,
        "Status": 3,
        "DeliveredOn": "/Date(1464952817450+0100)/",
        "ScheduledFor": null,
        "ScheduledForTimezone": "GTB Standard Time",
        "MailingLists": [
          {
            "Campaign": null,
            "MailingList": {
              "ID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b",
              "Name": "Some Name",
              "ActiveMemberCount": 0,
              "BouncedMemberCount": 0,
              "RemovedMemberCount": 0,
              "UnsubscribedMemberCount": 0,
              "Status": 0,
              "CustomFieldsDefinition": [],
              "CreatedBy": "212.205.224.198",
              "CreatedOn": "/Date(1464952667680+0100)/",
              "UpdatedBy": "212.205.224.198",
              "UpdatedOn": "/Date(1464952667680+0100)/",
              "ImportOperation": null
            },
            "Segment": null
          }
        ],
        "TotalSent": 1,
        "TotalOpens": 1,
        "UniqueOpens": 1,
        "TotalBounces": 0,
        "TotalForwards": 0,
        "UniqueForwards": 0,
        "TotalLinkClicks": 0,
        "UniqueLinkClicks": 0,
        "RecipientsCount": 1,
        "IsTransactional": false,
        "TotalComplaints": 0,
        "TotalUnsubscribes": 0
      },
      {
        "ID": "ef2ab040-aec8-46bf-be54-3d8311093015",
        "Name": "Performance Testing",
        "Subject": "Performance Testing",
        "SiteName": "mysite",
        "ConfirmationTo": "info@northweb.biz",
        "CreatedOn": "/Date(1464647633330+0100)/",
        "ABHoursToTest": null,
        "ABCampaignType": null,
        "ABWinner": null,
        "ABWinnerSelectionType": null,
        "Status": 3,
        "DeliveredOn": "/Date(1464647633207+0100)/",
        "ScheduledFor": null,
        "ScheduledForTimezone": "GTB Standard Time",
        "MailingLists": [
          {
            "Campaign": null,
            "MailingList": {
              "ID": "9b7611be-d395-4637-9983-697d261cca91",
              "Name": "Performance Testing",
              "ActiveMemberCount": 0,
              "BouncedMemberCount": 0,
              "RemovedMemberCount": 0,
              "UnsubscribedMemberCount": 0,
              "Status": 0,
              "CustomFieldsDefinition": [],
              "CreatedBy": "127.0.0.1",
              "CreatedOn": "/Date(1464647633220+0100)/",
              "UpdatedBy": "127.0.0.1",
              "UpdatedOn": "/Date(1464647633220+0100)/",
              "ImportOperation": null
            },
            "Segment": null
          }
        ],
        "TotalSent": 0,
        "TotalOpens": 0,
        "UniqueOpens": 0,
        "TotalBounces": 0,
        "TotalForwards": 0,
        "UniqueForwards": 0,
        "TotalLinkClicks": 0,
        "UniqueLinkClicks": 0,
        "RecipientsCount": 18561,
        "IsTransactional": false,
        "TotalComplaints": 0,
        "TotalUnsubscribes": 0
      }
    ]
  }
}

Get campaign details

Abstract

Describes the request and response details of this Moosend API endpoint to get details of a specific campaign.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that contains the details you are requesting.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the requested campaign:

  • ID - the ID of the campaign.

  • Name - the name of the campaign.

  • Subject - the subject of the campaign.

  • WebLocation - the web location of the HTML campaign.

  • HTMLContent - the HTML content of the campaign.

  • PlainContent - the content of the campaign in plain text.

  • Sender - a list that contains the following information about the campaign sender:

    • ID - the ID of the sender.

    • Name - the name of the sender.

    • Email - the email address of the sender.

    • CreatedOn - the date that the sender was created.

    • IsEnabled - this is true if the sender is enabled and false if it is not.

    • SpfVerified - this is true if the SPF record for the sender is enabled and false if it is not.

    • DkimVerified - this is true if the DKIM record for the sender is enabled and false if it is not.

    • DkimPublic - specifies the sender's email public DKIM.

  • DeliveredOn - the date-time the campaign was delivered. This is null for a cloned campaign.

  • ReplyToEmail - an object that contains details about the Reply to email address selected to receive replies from the campaign:

    • ID - the ID of the Reply to email receiver.

    • Name - the name of the Reply to email receiver.

    • Email - the email address of the Reply to email receiver.

    • CreatedOn - the date that the Reply to email receiver was created.

    • IsEnabled - this is true if the Reply to email receiver is enabled and false if it is not.

    • SpfVerified - this is true if the SPF record for the Reply to email receiver is enabled and false if it is not.

    • DkimVerified - this is true if the DKIM record for the Reply to email receiver is enabled and false if it is not.

    • DkimPublic - specifies the Reply to email receiver's email public DKIM.

  • CreatedOn - the date-time the campaign was created.

  • UpdatedOn - the date-time the campaign was updated.

  • ScheduledFor - the date-time the campaign is scheduled to be delivered. This is null for a cloned campaign.

  • TimeZone - the selected time zone for the account.

  • FormatType - the format type of the campaign. This is 0 for HTML, 1 for Template, and 2 for Plain Text.

  • ABCampaignData - this is null if the campaign is a regular campaign. If the campaign is an A/B split campaign, the object contains the following information :

    • ID - the four-digit integer ID of the ABCampaignData.

    • SubjectB - if the A/B split campaign is testing the subject, this is the subject line for campaign B.

    • PlainContentB - if the A/B split campaign is testing the content, this is the plain text content for campaign B.

    • HTMLContentB - if the A/B split campaign is testing the content, this is the HTML content for campaign B.

    • WebLocationB - if the A/B split campaign is testing the content, this is the web location for campaign B.

    • SenderB - if the A/B split campaign is testing the sender, this is campaign B's sender.

    • HoursToTest - the total number of hours to test campaigns A and B of your split test before sending the winning version.

    • ListPercentage - specifies the size of your test group in your list.

    • ABCampaignType - specifies the type of A/B split campaign. This is 0 for sender, 1 for content, and 2 for subject line

    • ABWinnerSelectionType - specifies the type of test that defines the winning version of the campaign. This is 0 for a unique opens test and 1 for a unique clicks test.

    • DeliveredOnA - the date-time campaign A was delivered. This is null for a cloned campaign.

    • DeliveredOnB - the date-time campaign B was delivered. This is null for a cloned campaign.

  • MailingLists - a list that contains the email lists or segments that that campaign is sent to.

    • MailingListID - the ID of the email list.

    • SegmentID - the ID of the selected segment. This is 0 if there is no segment selected.

  • ConfirmationTo - the email address to which a confirmation message is sent when the campaign has been successfully sent.

  • Status - status of the campaign.

  • IsTransactional - specifies whether the campaign was created using SMTP. This can be true or false.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/view.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "2fa129d1-a0ab-467a-ab3e-e43fd9f6bfb",
    "Name": "Test",
    "Subject": "Test",
    "WebLocation": null,
    "HTMLContent": someHtmlContent,
    "PlainContent": somePlainContent,
    "Sender": {
      "ID": "28a7ee75-034a-44e0-a946-fe28fc229d6e",
      "Name": "Fanis",
      "Email": "some@memail.com",
      "CreatedOn": "/Date(1457684250090+0100)/",
      "IsEnabled": true,
      "SpfVerified": false,
      "DkimVerified": true,
      "DkimPublic": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmO"
    },
    "DeliveredOn": "/Date(1464339959683+0100)/",
    "ReplyToEmail": {
      "ID": "28a7ee75-034a-4110-a9116-fe34235re6e",
      "Name": "Fanis",
      "Email": "some@email.com",
      "CreatedOn": "/Date(1457684250090+0100)/",
      "IsEnabled": true,
      "SpfVerified": false,
      "DkimVerified": true,
      "DkimPublic": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmO"
    },
    "CreatedOn": "/Date(1464339921630+0100)/",
    "UpdatedOn": "/Date(1464339949343+0100)/",
    "ScheduledFor": null,
    "Timezone": "GTB Standard Time",
    "FormatType": 0,
    "ABCampaignData": null,
    "MailingLists": [
      {
        "MailingListID": "ad4b18-3sd0-4e1a-a110-481080fa94",
        "SegmentID": 0
      }
    ],
    "ConfirmationTo": "some@email.com",
    "Status": 3,
    "IsTransactional": false
  }
}

Get all senders

Abstract

Describes the request and response details of this Moosend API endpoint to get senders of a specific campaign.

Request

Parameter

In

Type

Required

Description

Format

path

string

true

The supported file format for getting a response.

Possible values: jsonand xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code for this call. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - a list of campaign senders in your account containing the following information for each sender:

    • ID - the ID of the sender.

    • Name - the name of the sender.

    • Email - the email address of the sender.

    • CreatedOn - the date that the sender was created.

    • IsEnabled - this is true if the sender is enabled and false if it is not.

    • SpfVerified - this is true if the SPF record for the sender is enabled and false if it is not.

    • DkimVerified - this is true if the DKIM record for the sender is enabled and false if it is not.

    • DkimPublic - specifies the sender's email public DKIM.

Request
GET https://{hostname}/v3/senders/find_all.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/senders/find_all.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/senders/find_all.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/senders/find_all.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/senders/find_all.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/senders/find_all.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/senders/find_all.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/senders/find_all.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/senders/find_all.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/senders/find_all.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/senders/find_all.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/senders/find_all.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/senders/find_all.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/senders/find_all.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/senders/find_all.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": [
    {
      "ID": "01234567-89ab-cdef-0123-456789abcdef",
      "Name": "Your Name",
      "Email": "sender@example.com",
      "CreatedOn": "/Date(1323857838000+0200)/",
      "IsEnabled": true,
      "SpfVerified": false,
      "DkimVerified": false,
      "DkimPublic": "Some DkimPublic"
    },
    {
      "ID": "e57c96b7-5786-489b-b3a2-bac3e30dd6bd",
      "Name": "Some Name",
      "Email": "Some Email",
      "CreatedOn": "/Date(1400765125478)/",
      "IsEnabled": false,
      "SpfVerified": false,
      "DkimVerified": false,
      "DkimPublic": "Some DkimPublic"
    }
  ]
}

Get sender details

Abstract

Describes the request and response details of this Moosend API endpoint to get details of a specific sender.

Request

Parameter

In

Type

Required

Description

Format

path

string

true

The supported file format for getting a response.

Possible values: jsonand xml.

Email

query

string

true

The email address of the sender that contains the details you are requesting.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the information about the sender:

    • ID - the ID of the sender.

    • Name - the name of the sender.

    • Email - the email address of the sender.

    • CreatedOn - the date that the sender was created.

    • IsEnabled - this is true if the sender is enabled and false if it is not.

    • SpfVerified - this is true if the SPF record for the sender is enabled and false if it is not.

    • DkimVerified - this is true if the DKIM record for the sender is enabled and false if it is not.

    • DkimPublic - specifies the sender's email public DKIM.

Request
GET https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=
Request
curl --include \
'https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}v/v3/senders/find_one.{Format}?Email=&apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/senders/find_all.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/senders/find_all.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/senders/find_one.{Format}?Email=&apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "01234567-89ab-cdef-0123-456789abcdef",
    "Name": "Your Name",
    "Email": "sender@example.com",
    "CreatedOn": "/Date(1323857838000+0200)/",
    "IsEnabled": true,
    "SpfVerified": false,
    "DkimVerified": false,
    "DkimPublic": "Some DkimPublic"
  }
}

Create a draft campaign

Abstract

Describes the request and response details of this Moosend API endpoint to create a draft campaign.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the campaign.

Subject

body

string

true

The subject line of the campaign.

SenderEmail

body

string

true

The email address of the campaign sender.

ReplyToEmail

body

string

true

The email address selected to receive replies from the campaign. This must be one of your campaign senders. If not specified, the SenderEmail is assumed.

ConfirmationToEmail

body

string

false

The email address used to send a confirmation message when the campaign has been successfully sent. This can be any valid email address. If not specified, the SenderEmail is assumed.

HTMLContent

body

string

false

The complete HTML body of the campaign. You can use this parameter instead of using the WebLocation parameter.

WebLocation

body

string

false

The URL used to retrieve the HTML content of the campaign. Moosend automatically moves all CSS inline.

MailingLists

body

array

false

A list of email lists in your account that is used to send the campaign.

SegmentID

body

string

false

The ID of a segment in the selected email list. If not specified, the campaign is sent to all active subscribers of the email list.

IsAB

body

Boolean

true

A flag that defines if a campaign is an A/B split campaign. If true, you must fill out A/B split campaign parameters.

TrackInGoogleAnalytics

body

Boolean

false

Specifies if tracking is enabled for the campaign. You must have Google Analytics configured on your site to use this feature.

A/B split campaign parameters

Use these parameters when creating an A/B split campaign. If you specify any of the parameters below when creating a regular campaign, they are ignored in the request.

Parameter

In

Type

Required

Description

ABCampaignType

body

string

true

Specify the type of test to be performed in the AB split campaign to determine the winning version:

  • Subjectline - test two different versions of the subject line.

  • Content - test two different versions of the campaign content.

  • Sender - test two different versions of the campaign sender.

SubjectB

body

string

false

If testing A/B split campaigns with two subject line versions, this is the second subject version of the subject.

HTMLContentB

body

string

false

If testing A/B split campaigns with two HTML content versions, this is the complete HTML body of the second version.

WebLocationB

body

string

false

If testing A/B split campaigns with two HTML content versions, this is the web location of the second HTML content version.

SenderEmailB

body

string

false

If testing A/B split campaigns with two sender versions, this is the email address of the second campaign sender. This must be one of the senders defined in your account.

HoursToTest

body

integer

false

Specify how long the test runs, before determining the winning campaign version to be sent to the rest of the recipients.

This must be an integer between 1 and 24.

ListPercentage

body

integer

false

Specifies a portion of the target recipients to get the test campaign versions. For example, if you specify 10, then 10% of your recipients receive campaign A and another 10% receive the campaign B version.

This must be an integer between 5 and 40.

ABWinnerSelectionType

body

string

false

Specifies the method to determine the winning version for the test. If not set, OpenRate is assumed.

  • OpenRate - determine the winner based on the version that achieved more opens.

  • TotalUniqueClicks - determine the winner based on the version that achieved more unique link clicks.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - the ID of the campaign created.

Request
POST https://{hostname}/v3/campaigns/create.{Format}?apikey=

Request body:
{
  "Name": "Test campaign",
  "Subject": "Some subject",
  "SenderEmail": "something@email.com",
  "ReplyToEmail": "something@email.com",
  "ConfirmationToEmail": "something@email.com",
  "HTMLContent": "Some HTML body",  
  "MailingLists": [
    {
      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
      "SegmentID": "10166"
    },
    {
      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
    }
  ],
  "IsAB": "true",
  "ABCampaignType": "Content",
  "WebLocationB": "http://www.mysite.gr/newsletter/index",
  "HoursToTest": "2",
  "ListPercentage": "20",
  "ABWinnerSelectionType": "OpenRate"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\":\"Test campaign\",
    \"Subject\":\"Some subject\",
    \"SenderEmail\":\"something@email.com\",
    \"ReplyToEmail\":\"something@email.com\",
    \"ConfirmationToEmail\":\"something@email.com\",
    \"HTMLContent\":\"Some HTML body\",      
    \"MailingLists\": [
        {
            \"MailingListID\":\"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",
            \"SegmentID\":\"10166\"
        },
        {
            \"MailingListID\":\"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"
        }
    ],
    \"IsAB\":\"true\",
    \"ABCampaignType\":\"Content\",
    \"WebLocationB\":\"http://www.mysite.gr/newsletter/index\",
    \"HoursToTest\":\"2\",
    \"ListPercentage\":\"20\",
    \"ABWinnerSelectionType\":\"OpenRate\"
}" \
'https://{hostname}/v3/campaigns/create.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"Test campaign\",  \"Subject\": \"Some subject\",  \"SenderEmail\": \"something@email.com\",  \"ReplyToEmail\": \"something@email.com\",  \"ConfirmationToEmail\": \"something@email.com\",  \"HTMLContent\": \"Some HTML body\",  \"MailingLists\": [    {      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",      \"SegmentID\": \"10166\"    },    {      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"    }  ],  \"IsAB\": \"true\",  \"ABCampaignType\": \"Content\",  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",  \"HoursToTest\": \"2\",  \"ListPercentage\": \"20\",  \"ABWinnerSelectionType\": \"OpenRate\"}");
Response response = client.target("https://{hostname}/v3/campaigns/create.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/create.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'Test campaign',
  'Subject': 'Some subject',
  'SenderEmail': 'something@email.com',
  'ReplyToEmail': 'something@email.com',
  'ConfirmationToEmail': 'something@email.com',
  'HTMLContent': 'Some HTML body',  
  'MailingLists': [
    {
      'MailingListID': 'adaf2fe1-55db-42dc-aaf8-56d8f502138d',
      'SegmentID': '10166'
    },
    {
      'MailingListID': 'dce99b7a-2619-4805-aaeb-7fecdcb3c71b'
    }
  ],
  'IsAB': 'true',
  'ABCampaignType': 'Content',
  'WebLocationB': 'http://www.mysite.gr/newsletter/index',
  'HoursToTest': '2',
  'ListPercentage': '20',
  'ABWinnerSelectionType': 'OpenRate'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/create.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"Test campaign\",  \"Subject\": \"Some subject\",  \"SenderEmail\": \"something@email.com\",  \"ReplyToEmail\": \"something@email.com\",  \"ConfirmationToEmail\": \"something@email.com\",  \"HTMLContent\": \"Some HTML body\",  \"MailingLists\": [    {      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",      \"SegmentID\": \"10166\"    },    {      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"    }  ],  \"IsAB\": \"true\",  \"ABCampaignType\": \"Content\",  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",  \"HoursToTest\": \"2\",  \"ListPercentage\": \"20\",  \"ABWinnerSelectionType\": \"OpenRate\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "Test campaign",  "Subject": "Some subject",  "SenderEmail": "something@email.com",  "ReplyToEmail": "something@email.com",  "ConfirmationToEmail": "something@email.com",  "HTMLContent": "Some HTML body",  "MailingLists": [    {      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",      "SegmentID": "10166"    },    {      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"    }  ],  "IsAB": "true",  "ABCampaignType": "Content",  "WebLocationB": "http://www.mysite.gr/newsletter/index",  "HoursToTest": "2",  "ListPercentage": "20",  "ABWinnerSelectionType": "OpenRate"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/campaigns/create.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "Test campaign",
    "Subject": "Some subject",
    "SenderEmail": "something@email.com",
    "ReplyToEmail": "something@email.com",
    "ConfirmationToEmail": "something@email.com",
    "HTMLContent": "Some HTML body", 
    "MailingLists": [
      {
        "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
        "SegmentID": "10166"
      },
      {
        "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
      }
    ],
    "IsAB": "true",
    "ABCampaignType": "Content",
    "WebLocationB": "http://www.mysite.gr/newsletter/index",
    "HoursToTest": "2",
    "ListPercentage": "20",
    "ABWinnerSelectionType": "OpenRate"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/campaigns/create.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/create.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"Test campaign\",
  \"Subject\": \"Some subject\",
  \"SenderEmail\": \"something@email.com\",
  \"ReplyToEmail\": \"something@email.com\",
  \"ConfirmationToEmail\": \"something@email.com\",
  \"HTMLContent\": \"Some HTML body\", 
  \"MailingLists\": [
    {
      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",
      \"SegmentID\": \"10166\"
    },
    {
      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"
    }
  ],
  \"IsAB\": \"true\",
  \"ABCampaignType\": \"Content\",
  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",
  \"HoursToTest\": \"2\",
  \"ListPercentage\": \"20\",
  \"ABWinnerSelectionType\": \"OpenRate\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "Test campaign",
  "Subject": "Some subject",
  "SenderEmail": "something@email.com",
  "ReplyToEmail": "something@email.com",
  "ConfirmationToEmail": "something@email.com",
  "HTMLContent": "Some HTML body",
  "MailingLists": [
    {
      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
      "SegmentID": "10166"
    },
    {
      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
    }
  ],
  "IsAB": "true",
  "ABCampaignType": "Content",
  "WebLocationB": "http://www.mysite.gr/newsletter/index",
  "HoursToTest": "2",
  "ListPercentage": "20",
  "ABWinnerSelectionType": "OpenRate"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/campaigns/create.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"Test campaign\",\n  \"Subject\": \"Some subject\",\n  \"SenderEmail\": \"something@email.com\",\n  \"ReplyToEmail\": \"something@email.com\",\n  \"ConfirmationToEmail\": \"something@email.com\",\n  \"HTMLContent\": \"Some HTML body\",\n  \"MailingLists\": [\n    {\n      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",\n      \"SegmentID\": \"10166\"\n    },\n    {\n      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"\n    }\n  ],\n  \"IsAB\": \"true\",\n  \"ABCampaignType\": \"Content\",\n  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",\n  \"HoursToTest\": \"2\",\n  \"ListPercentage\": \"20\",\n  \"ABWinnerSelectionType\": \"OpenRate\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/create.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"Test campaign\",  \"Subject\": \"Some subject\",  \"SenderEmail\": \"something@email.com\",  \"ReplyToEmail\": \"something@email.com\",  \"ConfirmationToEmail\": \"something@email.com\",  \"HTMLContent\": \"Some HTML body\",  \"MailingLists\": [    {      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",      \"SegmentID\": \"10166\"    },    {      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"    }  ],  \"IsAB\": \"true\",  \"ABCampaignType\": \"Content\",  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",  \"HoursToTest\": \"2\",  \"ListPercentage\": \"20\",  \"ABWinnerSelectionType\": \"OpenRate\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/clone.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/create.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""Test campaign\"",
  \""Subject\"": \""Some subject\"",
  \""SenderEmail\"": \""something@email.com\"",
  \""ReplyToEmail\"": \""something@email.com\"",
  \""ConfirmationToEmail\"": \""something@email.com\"",
  \""HTMLContent\"": \""Some HTML body\"", 
  \""MailingLists\"": [
    {
      \""MailingListID\"": \""adaf2fe1-55db-42dc-aaf8-56d8f502138d\"",
      \""SegmentID\"": \""10166\""
    },
    {
      \""MailingListID\"": \""dce99b7a-2619-4805-aaeb-7fecdcb3c71b\""
    }
  ],
  \""IsAB\"": \""true\"",
  \""ABCampaignType\"": \""Content\"",
  \""WebLocationB\"": \""http://www.mysite.gr/newsletter/index\"",
  \""HoursToTest\"": \""2\"",
  \""ListPercentage\"": \""20\"",
  \""ABWinnerSelectionType\"": \""OpenRate\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "Test campaign",
  "Subject": "Some subject",
  "SenderEmail": "something@email.com",
  "ReplyToEmail": "something@email.com",
  "ConfirmationToEmail": "something@email.com",
  "HTMLContent": "Some HTML body",  
  "MailingLists": [
    {
      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
      "SegmentID": "10166"
    },
    {
      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
    }
  ],
  "IsAB": "true",
  "ABCampaignType": "Content",
  "WebLocationB": "http://www.mysite.gr/newsletter/index",
  "HoursToTest": "2",
  "ListPercentage": "20",
  "ABWinnerSelectionType": "OpenRate"
}')
response = client.post( path : "/campaigns/{CampaignID}/clone.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/create.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"Test campaign\",\n  \"Subject\": \"Some subject\",\n  \"SenderEmail\": \"something@email.com\",\n  \"ReplyToEmail\": \"something@email.com\",\n  \"ConfirmationToEmail\": \"something@email.com\",\n  \"HTMLContent\": \"Some HTML body\",\n  \"MailingLists\": [\n    {\n      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",\n      \"SegmentID\": \"10166\"\n    },\n    {\n      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"\n    }\n  ],\n  \"IsAB\": \"true\",\n  \"ABCampaignType\": \"Content\",\n  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",\n  \"HoursToTest\": \"2\",\n  \"ListPercentage\": \"20\",\n  \"ABWinnerSelectionType\": \"OpenRate\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/create.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"Test campaign\",\n  \"Subject\": \"Some subject\",\n  \"SenderEmail\": \"something@email.com\",\n  \"ReplyToEmail\": \"something@email.com\",\n  \"ConfirmationToEmail\": \"something@email.com\",\n  \"HTMLContent\": \"Some HTML body\",\n  \"MailingLists\": [\n    {\n      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",\n      \"SegmentID\": \"10166\"\n    },\n    {\n      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"\n    }\n  ],\n  \"IsAB\": \"true\",\n  \"ABCampaignType\": \"Content\",\n  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",\n  \"HoursToTest\": \"2\",\n  \"ListPercentage\": \"20\",\n  \"ABWinnerSelectionType\": \"OpenRate\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": "afdc4ef6-999f-4d74-905b-ec234789f9d6"
}

Clone an existing campaign

Abstract

Describes the request and response details of this Moosend API endpoint to clone a campaign.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that you want to clone.

Format

path

string

true

The supported file format for getting a response.

Possible values: jsonand xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the cloned campaign:

  • ID - the ID of the cloned campaign.

  • Name - the name of the campaign.

  • Subject- the subject of the campaign.

  • WebLocation - the web location of the HTML campaign.

  • HTMLContent - the HTML content of the campaign.

  • PlainContent - the content of the campaign in plain text.

  • Sender - a list that contains the following information about the campaign sender:

    • ID - the ID of the sender.

    • Name - the name of the sender.

    • Email - the email address of the sender.

    • CreatedOn - the date that the sender was created.

    • IsEnabled - this is true if the sender is enabled and false if it is not.

    • SpfVerified - this is true if the SPF record for the sender is enabled and false if it is not.

    • DkimVerified - this is true if the DKIM record for the sender is enabled and false if it is not.

    • DkimPublic - specifies the sender's email public DKIM.

  • DeliveredOn - the date-time the campaign was delivered. This is null for a cloned campaign.

  • ReplyToEmail - an object that contains details about the Reply to email address selected to receive replies from the campaign:

    • ID - the ID of the Reply to email receiver.

    • Name - the name of the Reply to email receiver.

    • Email - the email address of the Reply to email receiver.

    • CreatedOn - the date that the Reply to email receiver was created.

    • IsEnabled - this is true if the Reply to email receiver is enabled and false if it is not.

    • SpfVerified - this is true if the SPF record for the Reply to email receiver is enabled and false if it is not.

    • DkimVerified - this is true if the DKIM record for the Reply to email receiver is enabled and false if it is not.

    • DkimPublic - specifies the Reply to email receiver's email public DKIM.

  • CreatedOn - the date-time the campaign was created.

  • UpdatedOn - the date-time that the campaign was updated.

  • ScheduledFor - the date-time the campaign is scheduled to be delivered. This is null for a cloned campaign.

  • TimeZone - the selected time zone for the account.

  • FormatType - the format type of the campaign. This is 0 for HTML, 1 for Template, and 2 for Plain Text.

  • ABCampaignData : This is null if the cloned campaign is a regular campaign. If the cloned campaign is an A/B split campaign, the object contains the following information:

    • ID - the four-digit integer ID of the ABCampaignData.

    • SubjectB - if the A/B split campaign is testing the subject, this is the subject line for campaign B.

    • PlainContentB - if the A/B split campaign is testing the content, this is the plain text content for campaign B.

    • HTMLContentB - if the A/B split campaign is testing the content, this is the HTML content for campaign B.

    • WebLocationB - if the A/B split campaign is testing the content, this is the web location for campaign B.

    • SenderB - if the A/B split campaign is testing the sender, this is campaign B's sender.

    • HoursToTest - the total number of hours to test campaigns A and B of your split test before sending the winning version.

    • ListPercentage - specifies the size of your test group in your list.

    • ABCampaignType - specifies the type of A/B split campaign. This is 0 for sender, 1 for content, and 2 for subject line

    • ABWinnerSelectionType - specifies the type of test that defines the winning version of the campaign. This is 0 for a unique opens test and 1 for a unique clicks test.

    • DeliveredOnA - the date-time campaign A was delivered. This is null for a cloned campaign.

    • DeliveredOnB - the date-time campaign B was delivered. This is null for a cloned campaign.

  • MailingLists - a list that contains the email lists or segments that that campaign is sent to.

    • MailingListID - the ID of the email list.

    • SegmentID - the ID of the selected segment. This is 0 if there is no segment selected.

  • ConfirmationTo - the email address to which a confirmation message is sent when the campaign has been successfully sent.

  • Status - status of the campaign. The cloned campaign has 0 for status.

  • IsTransactional - specifies whether the campaign was created using SMTP. This can be true or false.

Request
POST https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=
Request
curl --include \
     --request POST \
'https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey='
Request
// Maven : Add these dependecies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity<String> payload = Entity.text("");
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=',
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->post("https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.post 'https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

    using (var content = new StringContent(""))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/clone.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def jsonObj = new JsonSlurper().parseText()
response = client.post( path : "/campaigns/{CampaignID}/clone.{Format}{?apikey}",
                        body : jsonObj,
                        
                        contentType : ANY )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/clone.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": "248f97f5-1e5f-4e17-8fa8-818dc112be10",
    "Name": "Test",
    "Subject": "Test",
    "WebLocation": "http://www.your-domain.com/newsletter",
    "HTMLContent": "Some html content",
    "PlainContent": "Plain context ... ",
    "Sender": {
      "ID": "e9d2ed56-fc20-4337-bb6a-8b5884e8dfa6",
      "Name": "Test",
      "Email": "test@email.com",
      "CreatedOn": "/Date(1457526079160+0100)/",
      "IsEnabled": true,
      "SpfVerified": false,
      "DkimVerified": true,
      "DkimPublic": "sender email dkim public"
    },
    "DeliveredOn": null,
    "ReplyToEmail": {
      "ID": "21234a-cede-1234-1234-1bd8d7a46d2d",
      "Name": "Andreas",
      "Email": "andreas@email.com",
      "CreatedOn": "/Date(1457526079160+0100)/",
      "IsEnabled": true,
      "SpfVerified": false,
      "DkimVerified": true,
      "DkimPublic": "reply to email dkim public"
    },
    "CreatedOn": "/Date(1469541491211)/",
    "UpdatedOn": "/Date(1469541491211)/",
    "ScheduledFor": null,
    "Timezone": "Korea Standard Time",
    "FormatType": 0,
    "ABCampaignData": {
      "ID": 4080,
      "SubjectB": "B Subject",
      "PlainContentB": null,
      "HTMLContentB": null,
      "WebLocationB": null,
      "SenderB": null,
      "HoursToTest": 3,
      "ListPercentage": 19,
      "ABCampaignType": 2,
      "ABWinnerSelectionType": 1,
      "DeliveredOnA": null,
      "DeliveredOnB": null
    },
    "MailingLists": [
      {
        "MailingListID": "e9d2ed56-fc20-4337-bb6a-8b5884e8dfa6",
        "SegmentID": 0
      }
    ],
    "ConfirmationTo": "test@email.com",
    "Status": 0,
    "IsTransactional": false
  }
}

Delete a campaign

Abstract

Describes the request and response details of this Moosend API endpoint to delete a campaign.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the draft or sent campaign that you want to delete.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
DELETE https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=
Request
curl --include \
     --request DELETE \
'https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .delete();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('DELETE', 'https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request({
  method: 'DELETE',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=',
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->delete("https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=')
request.get_method = lambda: 'DELETE'

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

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

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.delete 'https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("DELETE", "https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.DeleteAsync("campaigns/{CampaignID}/clone.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "DELETE"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.delete( path : "/campaigns/{CampaignID}/clone.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"DELETE"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/delete.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "DELETE"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Update a draft campaign

Abstract

Describes the request and response details of this Moosend API endpoint to update a draft campaign.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

CampaignID

path

string

true

The ID of the campaign that you want to update.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the campaign.

Subject

body

string

false

The subject line of the campaign.

SenderEmail

body

string

false

The email address of the campaign sender.

ReplyToEmail

body

string

false

The email address selected to receive replies from the campaign. This must be one of your campaign senders. If not specified, the SenderEmail is assumed.

ConfirmationToEmail

body

string

false

The email address used to send a confirmation message when the campaign has been successfully sent. This can be any valid email address. If not specified, the SenderEmail is assumed.

WebLocation

body

string

false

The URL used to retrieve the HTML content of the campaign. Moosend automatically moves all CSS inline.

MailingLists

body

array

false

A list of email lists in your account that is used to send the campaign.

SegmentID

body

string

false

The ID of a segment in the selected email list. If not specified, the campaign is sent to all active subscribers of the email list.

IsAB

body

Boolean

false

A flag that defines if a campaign is an A/B split campaign. If true, you must fill out A/B split campaign parameters.

TrackInGoogleAnalytics

body

Boolean

false

Specifies if tracking is enabled for the campaign. You must have Google Analytics configured on your site to use this feature.

A/B split campaign parameters

Use these parameters when updating an A/B split campaign. If you specify any of the parameters below when updating a regular campaign, they are ignored in the request.

Name

In

Type

Required

Description

ABCampaignType

body

string

true

Specify the type of test to be performed in the AB split campaign to determine the winning version:

  • Subjectline - test two different versions of the subject line.

  • Content - test two different versions of the campaign content.

  • Sender - test two different versions of the campaign sender.

SubjectB

body

string

false

If testing A/B split campaigns with two subject line versions, this is the second subject version of the subject.

WebLocationB

body

string

false

If testing A/B split campaigns with two HTML content versions, this is the web location of the second HTML content version.

SenderEmailB

body

string

false

If testing A/B split campaigns with two sender versions, this is the email address of the second campaign sender. This must be one of the senders defined in your account.

HoursToTest

body

integer

false

Specify how long the test runs, before determining the winning campaign version to be sent to the rest of the recipients.

This must be an integer between 1 and 24.

ListPercentage

body

integer

false

Specifies a portion of the target recipients to get the test campaign versions. For example, if you specify 10, then 10% of your recipients receive campaign A and another 10% receive the campaign B version.

This must be an integer between 5 and 40.

ABWinnerSelectionType

body

string

false

Specifies the method to determine the winning version for the test. If not set, OpenRate is assumed.

  • OpenRate -determine the winner based on the version that achieved more opens.

  • TotalUniqueClicks - determine the winner based on the version that achieved more unique link clicks.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=

Request body:
{
  "Name": "Test campaign",
  "Subject": "Some subject",
  "SenderEmail": "something@email.com",
  "ReplyToEmail": "something@email.com",
  "ConfirmationToEmail": "something@email.com",
  "WebLocation": "http://www.mysite.gr/newsletter/index",
  "MailingLists": [
    {
      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
      "SegmentID": "10166"
    },
    {
      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
    }
  ],
  "IsAB": "true",
  "ABCampaignType": "Content",
  "WebLocationB": "http://www.mysite.gr/newsletter/index",
  "HoursToTest": "2",
  "ListPercentage": "20",
  "ABWinnerSelectionType": "OpenRate"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Name\":\"Test campaign\",
    \"Subject\":\"Some subject\",
    \"SenderEmail\":\"something@email.com\",
    \"ReplyToEmail\":\"something@email.com\",
    \"ConfirmationToEmail\":\"something@email.com\",
    \"WebLocation\":\"http://www.mysite.gr/newsletter/index\",
    \"MailingLists\": [
        {
            \"MailingListID\":\"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",
            \"SegmentID\":\"10166\"
        },
        {
            \"MailingListID\":\"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"
        }
    ],
    \"IsAB\":\"true\",
    \"ABCampaignType\":\"Content\",
    \"WebLocationB\":\"http://www.mysite.gr/newsletter/index\",
    \"HoursToTest\":\"2\",
    \"ListPercentage\":\"20\",
    \"ABWinnerSelectionType\":\"OpenRate\"
}" \
'https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"Test campaign\",  \"Subject\": \"Some subject\",  \"SenderEmail\": \"something@email.com\",  \"ReplyToEmail\": \"something@email.com\",  \"ConfirmationToEmail\": \"something@email.com\",  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",  \"MailingLists\": [    {      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",      \"SegmentID\": \"10166\"    },    {      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"    }  ],  \"IsAB\": \"true\",  \"ABCampaignType\": \"Content\",  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",  \"HoursToTest\": \"2\",  \"ListPercentage\": \"20\",  \"ABWinnerSelectionType\": \"OpenRate\"}");
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'Test campaign',
  'Subject': 'Some subject',
  'SenderEmail': 'something@email.com',
  'ReplyToEmail': 'something@email.com',
  'ConfirmationToEmail': 'something@email.com',
  'WebLocation': 'http://www.mysite.gr/newsletter/index',
  'MailingLists': [
    {
      'MailingListID': 'adaf2fe1-55db-42dc-aaf8-56d8f502138d',
      'SegmentID': '10166'
    },
    {
      'MailingListID': 'dce99b7a-2619-4805-aaeb-7fecdcb3c71b'
    }
  ],
  'IsAB': 'true',
  'ABCampaignType': 'Content',
  'WebLocationB': 'http://www.mysite.gr/newsletter/index',
  'HoursToTest': '2',
  'ListPercentage': '20',
  'ABWinnerSelectionType': 'OpenRate'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"Test campaign\",  \"Subject\": \"Some subject\",  \"SenderEmail\": \"something@email.com\",  \"ReplyToEmail\": \"something@email.com\",  \"ConfirmationToEmail\": \"something@email.com\",  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",  \"MailingLists\": [    {      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",      \"SegmentID\": \"10166\"    },    {      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"    }  ],  \"IsAB\": \"true\",  \"ABCampaignType\": \"Content\",  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",  \"HoursToTest\": \"2\",  \"ListPercentage\": \"20\",  \"ABWinnerSelectionType\": \"OpenRate\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "Test campaign",  "Subject": "Some subject",  "SenderEmail": "something@email.com",  "ReplyToEmail": "something@email.com",  "ConfirmationToEmail": "something@email.com",  "WebLocation": "http://www.mysite.gr/newsletter/index",  "MailingLists": [    {      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",      "SegmentID": "10166"    },    {      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"    }  ],  "IsAB": "true",  "ABCampaignType": "Content",  "WebLocationB": "http://www.mysite.gr/newsletter/index",  "HoursToTest": "2",  "ListPercentage": "20",  "ABWinnerSelectionType": "OpenRate"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "Test campaign",
    "Subject": "Some subject",
    "SenderEmail": "something@email.com",
    "ReplyToEmail": "something@email.com",
    "ConfirmationToEmail": "something@email.com",
    "WebLocation": "http://www.mysite.gr/newsletter/index",
    "MailingLists": [
      {
        "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
        "SegmentID": "10166"
      },
      {
        "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
      }
    ],
    "IsAB": "true",
    "ABCampaignType": "Content",
    "WebLocationB": "http://www.mysite.gr/newsletter/index",
    "HoursToTest": "2",
    "ListPercentage": "20",
    "ABWinnerSelectionType": "OpenRate"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"Test campaign\",
  \"Subject\": \"Some subject\",
  \"SenderEmail\": \"something@email.com\",
  \"ReplyToEmail\": \"something@email.com\",
  \"ConfirmationToEmail\": \"something@email.com\",
  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",
  \"MailingLists\": [
    {
      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",
      \"SegmentID\": \"10166\"
    },
    {
      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"
    }
  ],
  \"IsAB\": \"true\",
  \"ABCampaignType\": \"Content\",
  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",
  \"HoursToTest\": \"2\",
  \"ListPercentage\": \"20\",
  \"ABWinnerSelectionType\": \"OpenRate\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "Test campaign",
  "Subject": "Some subject",
  "SenderEmail": "something@email.com",
  "ReplyToEmail": "something@email.com",
  "ConfirmationToEmail": "something@email.com",
  "WebLocation": "http://www.mysite.gr/newsletter/index",
  "MailingLists": [
    {
      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
      "SegmentID": "10166"
    },
    {
      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
    }
  ],
  "IsAB": "true",
  "ABCampaignType": "Content",
  "WebLocationB": "http://www.mysite.gr/newsletter/index",
  "HoursToTest": "2",
  "ListPercentage": "20",
  "ABWinnerSelectionType": "OpenRate"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"Test campaign\",\n  \"Subject\": \"Some subject\",\n  \"SenderEmail\": \"something@email.com\",\n  \"ReplyToEmail\": \"something@email.com\",\n  \"ConfirmationToEmail\": \"something@email.com\",\n  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",\n  \"MailingLists\": [\n    {\n      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",\n      \"SegmentID\": \"10166\"\n    },\n    {\n      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"\n    }\n  ],\n  \"IsAB\": \"true\",\n  \"ABCampaignType\": \"Content\",\n  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",\n  \"HoursToTest\": \"2\",\n  \"ListPercentage\": \"20\",\n  \"ABWinnerSelectionType\": \"OpenRate\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"Test campaign\",  \"Subject\": \"Some subject\",  \"SenderEmail\": \"something@email.com\",  \"ReplyToEmail\": \"something@email.com\",  \"ConfirmationToEmail\": \"something@email.com\",  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",  \"MailingLists\": [    {      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",      \"SegmentID\": \"10166\"    },    {      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"    }  ],  \"IsAB\": \"true\",  \"ABCampaignType\": \"Content\",  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",  \"HoursToTest\": \"2\",  \"ListPercentage\": \"20\",  \"ABWinnerSelectionType\": \"OpenRate\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/clone.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""Test campaign\"",
  \""Subject\"": \""Some subject\"",
  \""SenderEmail\"": \""something@email.com\"",
  \""ReplyToEmail\"": \""something@email.com\"",
  \""ConfirmationToEmail\"": \""something@email.com\"",
  \""WebLocation\"": \""http://www.mysite.gr/newsletter/index\"",
  \""MailingLists\"": [
    {
      \""MailingListID\"": \""adaf2fe1-55db-42dc-aaf8-56d8f502138d\"",
      \""SegmentID\"": \""10166\""
    },
    {
      \""MailingListID\"": \""dce99b7a-2619-4805-aaeb-7fecdcb3c71b\""
    }
  ],
  \""IsAB\"": \""true\"",
  \""ABCampaignType\"": \""Content\"",
  \""WebLocationB\"": \""http://www.mysite.gr/newsletter/index\"",
  \""HoursToTest\"": \""2\"",
  \""ListPercentage\"": \""20\"",
  \""ABWinnerSelectionType\"": \""OpenRate\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "Test campaign",
  "Subject": "Some subject",
  "SenderEmail": "something@email.com",
  "ReplyToEmail": "something@email.com",
  "ConfirmationToEmail": "something@email.com",
  "WebLocation": "http://www.mysite.gr/newsletter/index",
  "MailingLists": [
    {
      "MailingListID": "adaf2fe1-55db-42dc-aaf8-56d8f502138d",
      "SegmentID": "10166"
    },
    {
      "MailingListID": "dce99b7a-2619-4805-aaeb-7fecdcb3c71b"
    }
  ],
  "IsAB": "true",
  "ABCampaignType": "Content",
  "WebLocationB": "http://www.mysite.gr/newsletter/index",
  "HoursToTest": "2",
  "ListPercentage": "20",
  "ABWinnerSelectionType": "OpenRate"
}')
response = client.post( path : "/campaigns/{CampaignID}/clone.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"Test campaign\",\n  \"Subject\": \"Some subject\",\n  \"SenderEmail\": \"something@email.com\",\n  \"ReplyToEmail\": \"something@email.com\",\n  \"ConfirmationToEmail\": \"something@email.com\",\n  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",\n  \"MailingLists\": [\n    {\n      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",\n      \"SegmentID\": \"10166\"\n    },\n    {\n      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"\n    }\n  ],\n  \"IsAB\": \"true\",\n  \"ABCampaignType\": \"Content\",\n  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",\n  \"HoursToTest\": \"2\",\n  \"ListPercentage\": \"20\",\n  \"ABWinnerSelectionType\": \"OpenRate\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/update.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"Test campaign\",\n  \"Subject\": \"Some subject\",\n  \"SenderEmail\": \"something@email.com\",\n  \"ReplyToEmail\": \"something@email.com\",\n  \"ConfirmationToEmail\": \"something@email.com\",\n  \"WebLocation\": \"http://www.mysite.gr/newsletter/index\",\n  \"MailingLists\": [\n    {\n      \"MailingListID\": \"adaf2fe1-55db-42dc-aaf8-56d8f502138d\",\n      \"SegmentID\": \"10166\"\n    },\n    {\n      \"MailingListID\": \"dce99b7a-2619-4805-aaeb-7fecdcb3c71b\"\n    }\n  ],\n  \"IsAB\": \"true\",\n  \"ABCampaignType\": \"Content\",\n  \"WebLocationB\": \"http://www.mysite.gr/newsletter/index\",\n  \"HoursToTest\": \"2\",\n  \"ListPercentage\": \"20\",\n  \"ABWinnerSelectionType\": \"OpenRate\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Test a campaign

Abstract

Describes the request and response details of this Moosend API endpoint to test a draft campaign.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

CampaignID

path

string

true

The ID of the draft campaign that you want to test.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

TestEmails

body

array

true

A list of email addresses that you want to use to send your test campaign. Use a comma (,) to separate up to a maximum of five email addresses.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=

Request body:
{
  "TestEmails": [
    "email1@email.com",
    "email2@email.com"
  ]
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"TestEmails\":
    [
        \"email1@email.com\",
        \"email2@email.com\"
    ]
}" \
'https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"TestEmails\": [    \"email1@email.com\",    \"email2@email.com\"  ]}");
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'TestEmails': [
    'email1@email.com',
    'email2@email.com'
  ]
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"TestEmails\": [    \"email1@email.com\",    \"email2@email.com\"  ]}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "TestEmails": [    "email1@email.com",    "email2@email.com"  ]}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "TestEmails": [
      "email1@email.com",
      "email2@email.com"
    ]
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"TestEmails\": [
    \"email1@email.com\",
    \"email2@email.com\"
  ]
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "TestEmails": [
    "email1@email.com",
    "email2@email.com"
  ]
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"TestEmails\": [\n    \"email1@email.com\",\n    \"email2@email.com\"\n  ]\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"TestEmails\": [    \"email1@email.com\",    \"email2@email.com\"  ]}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/send_test.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""TestEmails\"": [
    \""email1@email.com\"",
    \""email2@email.com\""
  ]
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "TestEmails": [
    "email1@email.com",
    "email2@email.com"
  ]
}')
response = client.post( path : "/campaigns/{CampaignID}/send_test.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"TestEmails\": [\n    \"email1@email.com\",\n    \"email2@email.com\"\n  ]\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/send_test.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"TestEmails\": [\n    \"email1@email.com\",\n    \"email2@email.com\"\n  ]\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Send a campaign

Abstract

Describes the request and response details of this Moosend API endpoint to send a campaign.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the draft campaign that you want to send.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=
Request
curl --include \
     --request POST \
'https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity<String> payload = Entity.text("");
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=',
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->post("https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.post 'https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

    using (var content = new StringContent(""))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/send.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def jsonObj = new JsonSlurper().parseText()
response = client.post( path : "/campaigns/{CampaignID}/send.{Format}{?apikey}",
                        body : jsonObj,
                        
                        contentType : ANY )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/send.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Schedule a campaign

Abstract

Describes the request and response details of this Moosend API endpoint to schedule a campaign for delivery.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

CampaignID

path

string

true

The ID of the campaign that you want to schedule.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

DateTime

body

date

true

The specific date and time the campaign is scheduled to be delivered.

Use the same format that you have in the Time and date settings in your account. For example, dd-mm-yyyy.

Timezone

body

string

false

The time zone of your specified date and time.

If you don't specify any timezone value, the time zone in your time and date settings is used.

Timezone values

The available time zones are the following:

  • Dateline Standard Time

  • Samoa Standard Time

  • Hawaiian Standard Time

  • Alaskan Standard Time

  • Pacific Standard Time

  • Pacific Standard Time (Mexico)

  • US Mountain Standard Time

  • Mountain Standard Time

  • Central Standard Time

  • Central Standard Time (Mexico)

  • Canada Central Standard Time

  • SA Pacific Standard Time

  • US Eastern Standard Time

  • Eastern Standard Time

  • Venezuela Standard Time

  • Atlantic Standard Time

  • SA Western Standard Time

  • Central Brazilian Standard Time

  • Pacific SA Standard Time

  • Newfoundland Standard Time

  • E. South America Standard Time

  • Argentina Standard Time

  • SA Eastern Standard Time

  • Greenland Standard Time

  • Montevideo Standard Time

  • Mid-Atlantic Standard Time

  • Azores Standard Time

  • Cape Verde Standard Time

  • Greenwich Standard Time

  • GMT Standard Time

  • Morocco Standard Time

  • W. Central Africa Standard Time

  • Central European Standard Time

  • Romance Standard Time

  • W. Europe Standard Time

  • Namibia Standard Time

  • E. Europe Standard Time

  • Israel Standard Time

  • FLE Standard Time

  • South Africa Standard Time

  • Egypt Standard Time

  • Middle East Standard Time

  • GTB Standard Time

  • Jordan Standard Time

  • Iran Standard Time

  • Georgian Standard Time

  • E. Africa Standard Time

  • Russian Standard Time

  • Arab Standard Time

  • Arabic Standard Time

  • Caucasus Standard Time

  • Mauritius Standard Time

  • Azerbaijan Standard Time

  • Arabian Standard Time

  • Afghanistan Standard Time

  • West Asia Standard Time

  • Pakistan Standard Time

  • Ekaterinburg Standard Time

  • Sri Lanka Standard Time

  • India Standard Time

  • Nepal Standard Time

  • N. Central Asia Standard Time

  • Central Asia Standard Time

  • Myanmar Standard Time

  • North Asia Standard Time

  • SE Asia Standard Time

  • Taipei Standard Time

  • W. Australia Standard Time

  • Singapore Standard Time

  • North Asia East Standard Time

  • China Standard Time

  • Yakutsk Standard Time

  • Korea Standard Time

  • Tokyo Standard Time

  • AUS Central Standard Time

  • Cen. Australia Standard Time

  • AUS Eastern Standard Time

  • West Pacific Standard Time

  • Tasmania Standard Time

  • Vladivostok Standard Time

  • Central Pacific Standard Time

  • New Zealand Standard Time

  • Tonga Standard Time

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response message. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=

Request body:
{
  "DateTime": "24-06-2023 13:17",
  "Timezone": "US Eastern Standard Time"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"DateTime\":\"24-06-2023 13:17\",
    \"Timezone\":\"US Eastern Standard Time\"
}" \
'https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"DateTime\": \"24-06-2016 13:17\",  \"Timezone\": \"US Eastern Standard Time\"}");
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'DateTime': '24-06-2023 13:17',
  'Timezone': 'US Eastern Standard Time'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"DateTime\": \"24-06-2023 13:17\",  \"Timezone\": \"US Eastern Standard Time\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "DateTime": "24-06-2023 13:17",  "Timezone": "US Eastern Standard Time"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "DateTime": "24-06-2023 13:17",
    "Timezone": "US Eastern Standard Time"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"DateTime\": \"24-06-2023 13:17\",
  \"Timezone\": \"US Eastern Standard Time\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "DateTime": "24-06-2023 13:17",
  "Timezone": "US Eastern Standard Time"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"DateTime\": \"24-06-2023 13:17\",\n  \"Timezone\": \"US Eastern Standard Time\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"DateTime\": \"24-06-2023 13:17\",  \"Timezone\": \"US Eastern Standard Time\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/schedule.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""DateTime\"": \""24-06-2023 13:17\"",
  \""Timezone\"": \""US Eastern Standard Time\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "DateTime": "24-06-2023 13:17",
  "Timezone": "US Eastern Standard Time"
}')
response = client.post( path : "/campaigns/{CampaignID}/schedule.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"DateTime\": \"24-06-2023 13:17\",\n  \"Timezone\": \"US Eastern Standard Time\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/schedule.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"DateTime\": \"24-06-2023 13:17\",\n  \"Timezone\": \"US Eastern Standard Time\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Unschedule a campaign

Abstract

Describes the request and response details of this Moosend API endpoint to unschedule a campaign that is scheduled for delivery.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that you want to unschedule.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response message. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=
Request
curl --include \
     --request POST \
'https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity<String> payload = Entity.text("");
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=',
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->post("https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.post 'https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

    using (var content = new StringContent(""))
    {
      using (var response = await httpClient.PostAsync("campaigns/{CampaignID}/schedule.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def jsonObj = new JsonSlurper().parseText()
response = client.post( path : "/campaigns/{CampaignID}/schedule.{Format}{?apikey}",
                        body : jsonObj,
                        
                        contentType : ANY )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/unschedule.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Get campaign statistics

Abstract

Describes the request and response details of this Moosend API endpoint to get campaign statistics.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that you are fetching statistics for.

Type

path

string

false

The type of activity used to get information and display statistics. Possible values are:

  • Sent - when and to which recipients the campaign was sent.

  • Opened - who opened the campaign.

  • LinkClicked - who clicked on which links in the campaign.

  • Forward - who forwarded the campaign using the relevant link in the email body and when.

  • Unsubscribed - who unsubscribed from the campaign by clicking the unsubscribe link and when.

  • Bounced - which email recipients failed to receive the campaign. If not specified, Sent value is used by default.

  • Complained - which email recipients reported your campaign as spam through their email service.

  • Activity - all types of activities for the campaign.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

date

query

date

false

The specific year, month, and day the activity occurred. The date has a YYYY/MM/DD format.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the Paging and Analytics information for the campaign:

    • Paging - an object that contains the following information:

      • PageSize - the page size of the results. This is 0 if not defined.

      • CurrentPage - the number of the result page. This is 1 if not defined.

      • Totalresults - the number of results that are included in the response.

      • TotalPageCount - the total number of pages in your account.

      • SortExpression - the sort expression associated with the column or columns being sorted.

      • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

    • Analytics - a list of recipients containing the following information for each recipient:

      • Context - the email address of the recipient.

      • ContextName - the name of the recipient.

      • TotalCount - the total number of statistics based on the activity Type made by the recipient. This can be opens, link clicks, and so on.

      • UniqueCount - the total number of unique statistics based on the activity Type made by the recipient. This can be opens, link clicks, and so on.

      • ContextDescription : If the selected Type is Unsubscribed, this contains the date-time the recipient unsubscribed from the campaign.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 1,
      "CurrentPage": 1,
      "TotalResults": 2,
      "TotalPageCount": 1,
      "SortExpression": null,
      "SortIsAscending": false
    },
    "Analytics": [
      {
        "Context": "recipient@email.com",
        "ContextName": "recipient name",
        "TotalCount": 1,
        "UniqueCount": 0,
        "ContextDescription": null
      },
      {
        "Context": "recipient2@email.com",
        "ContextName": "recipient2 name",
        "TotalCount": 1,
        "UniqueCount": 0,
        "ContextDescription": null
      }
    ]
  }
}

Get campaign statistics with paging and filter

Abstract

Describes the request and response details of this Moosend API endpoint to get campaign statistics with paging and filter information.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that you are fetching statistics for.

Type

path

string

false

The type of activity used to get information and display statistics. Possible values are:

  • Sent - when and to which recipients the campaign was sent.

  • Opened - who opened the campaign.

  • LinkClicked - who clicked on which links in the campaign.

  • Forward - who forwarded the campaign using the relevant link in the email body and when.

  • Unsubscribed - who unsubscribed from the campaign by clicking the unsubscribe link and when.

  • Bounced - which email recipients failed to receive the campaign. If not specified, Sent value is used by default.

  • Complained - which email recipients reported your campaign as spam through their email service.

  • Activity - all types of activities for the campaign.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Page

query

number

false

The page number to display results for. If not specified, the first page is returned.

PageSize

query

number

false

The maximum number of results per page. This must be a positive integer up to 100.

Returns 50 results per page if not specified. If a value greater than 100 is specified, it is treated as 100. 

From

query

date

false

The start date value to return results.  If not specified, results are returned from the date the campaign was sent. From date has a DD-MM-YYYY format.

To

query

date

false

The end date value to return results. If not specified, results are returned up to the current date.  To date has a DD-MM-YYYY format.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the Paging and Analytics information for the campaign:

    • Paging - an object that contains the following information:

      • PageSize - the page size of the results. This is 0 if not defined.

      • CurrentPage - the number of the result page. This is 1 if not defined.

      • Totalresults - the number of results that are included in the response.

      • TotalPageCount - the total number of pages in your account.

      • SortExpression - the sort expression associated with the column or columns being sorted.

      • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

    • Analytics - a list of recipients containing the following information for each recipient:

      • Context - the email address of the recipient.

      • ContextName - the name of the recipient.

      • TotalCount - the total number of statistics based on the activity Type made by the recipient. This can be opens, link clicks, and so on.

      • UniqueCount - the total number of unique statistics based on the activity Type made by the recipient. This can be opens, link clicks, and so on.

      • ContextDescription : If the selected Type is Unsubscribed, this contains the date-time the recipient unsubscribed from the campaign.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From&To=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To='
Request
// Maven : Add these dependecies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/stats/{Type}.{Format}?apikey=&Page=&PageSize=&From=&To=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 5,
      "CurrentPage": 1,
      "TotalResults": 374,
      "TotalPageCount": 75,
      "SortExpression": null,
      "SortIsAscending": false
    },
    "Analytics": [
      {
        "Context": "recipient1@email.com",
        "ContextName": "",
        "TotalCount": 1,
        "UniqueCount": 0,
        "ContextDescription": null
      },
      {
        "Context": "recipient2@email.com",
        "ContextName": "Paul",
        "TotalCount": 1,
        "UniqueCount": 0,
        "ContextDescription": null
      },
      {
        "Context": "recipient3@email.com",
        "ContextName": "John",
        "TotalCount": 5,
        "UniqueCount": 0,
        "ContextDescription": null
      },
      {
        "Context": "recipient4@email.com",
        "ContextName": "Marc",
        "TotalCount": 4,
        "UniqueCount": 0,
        "ContextDescription": null
      },
      {
        "Context": "recipient5@email.com",
        "ContextName": "",
        "TotalCount": 3,
        "UniqueCount": 0,
        "ContextDescription": null
      }
    ]
  }
}

Get campaign summary

Abstract

Describes the request and response details of this Moosend API endpoint to get a campaign summary

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that you want to get a summary of.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - contains all the following information for the campaign:

    • CampaignID - the ID of the campaign.

    • ABVersion - if the campaign is an A/B split test campaign, this displays which campaign version was sent. This is null for a regular campaign.

    • CampaignName - the name of the campaign.

    • CampaignSubject - the subject line of the campaign.

    • MailingLists - a list that contains the email lists or segments that that campaign is sent to.

      • MailingListID - the ID of the email list.

      • SegmentID - the ID of the selected segment. This is 0 if there is no segment selected.

    • CampaignDeliveredOn - the date-time the campaign was delivered.

    • To - the date-time the measurement ended.

    • From - the date-time the measurement started.

    • TotalOpens - the total number of email opens.

    • UniqueOpens - the total number of unique email opens.

    • TotalBounces - the total number of email bounces.

    • TotalComplaints - the total number of complaints.

    • TotalForwards - the total number of email forwards for the campaign using the Forward to a friend personalization tag.

    • UniqueForwards - the total number of unique forwards for the campaign using the Forward to a friend personalization tag.

    • TotalUnsubscribes - the total number of unsubscribed recipients for the campaign.

    • TotalLinkClicks - the total number of link clicks.

    • UniqueLinkClicks - the total number of unique link clicks.

    • Sent - the total number of campaign emails sent.

    • CampaignIsArchived - specifies whether the campaign has been archived. A campaign older than three months gets archived and only high-level data about the campaign becomes available.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/view_summary.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "CampaignID": "13cffeee-0b8c-4610-8e0d-efa7bd44be32",
    "ABVersion": null,
    "CampaignName": "test image path",
    "CampaignSubject": "test image path",
    "MailingLists": [
      {
        "MailingListID": "84bs231b131-367a-4d73-af11-01b4b45d3f54",
        "SegmentID": 0
      }
    ],
    "CampaignDeliveredOn": "/Date(1464256291013+0100)/",
    "To": "/Date(1465481260987+0100)/",
    "From": "/Date(1464256291013+0100)/",
    "TotalOpens": 1340,
    "UniqueOpens": 780,
    "TotalBounces": 4,
    "TotalComplaints": 0,
    "TotalForwards": 55,
    "UniqueForwards": 55,
    "TotalUnsubscribes": 7,
    "TotalLinkClicks": 976,
    "UniqueLinkClicks": 711,
    "Sent": 2550,
    "CampaignIsArchived": false
  }
}

Get campaign activity by location

Abstract

Describes the request and response details of this Moosend API endpoint to get campaign activity by location.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the campaign that you want to get the activity by location of.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the Paging and Analytics information for the campaign:

    • Paging - an object that contains the following information:

      • PageSize - the page size of the results. This is 0 if not defined.

      • CurrentPage - the number of the result page. This is 1 if not defined.

      • Totalresults - the number of results that are included in the response.

      • TotalPageCount - the total number of pages in your account.

      • SortExpression - the sort expression associated with the column or columns being sorted.

      • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

    • Analytics - a list of countries where the campaign opens occurred. It contains the following information for each country:

      • Context - the country code.

      • ContextName - the name of the country.

      • TotalCount - the total number of campaign opens.

      • UniqueCount - The total number of unique campaign opens.

      • ContextDescription - this is null for this case.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/stats/countries.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 0,
      "CurrentPage": 1,
      "TotalResults": 0,
      "TotalPageCount": 0,
      "SortExpression": null,
      "SortIsAscending": false
    },
    "Analytics": [
      {
        "Context": "  ",
        "ContextName": null,
        "TotalCount": 1,
        "UniqueCount": 1,
        "ContextDescription": null
      }
    ]
  }
}

Get campaign link activity

Abstract

Describes the request and response details of this Moosend API endpoint to get campaign link activity.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/{CampaignID}/stats/{Type}.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/stats/links.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 0,
      "CurrentPage": 1,
      "TotalResults": 0,
      "TotalPageCount": 0,
      "SortExpression": null,
      "SortIsAscending": false
    },
    "Analytics": [
      {
        "Context": "http://someUrl.com/",
        "ContextName": null,
        "TotalCount": 34,
        "UniqueCount": 30,
        "ContextDescription": null
      },
      {
        "Context": "http://someUrl.com/product1/",
        "ContextName": null,
        "TotalCount": 95,
        "UniqueCount": 67,
        "ContextDescription": null
      },
      {
        "Context": "http://someUrl.com/product2/",
        "ContextName": null,
        "TotalCount": 102,
        "UniqueCount": 78,
        "ContextDescription": null
      },
      {
        "Context": "https://twitter.com/myCompany",
        "ContextName": null,
        "TotalCount": 89,
        "UniqueCount": 89,
        "ContextDescription": null
      }
    ]
  }
}

Get A/B campaign summary

Abstract

Describes the request and response details of this Moosend API endpoint to get a summary of an A/B campaign.

Request

Parameter

In

Type

Required

Description

CampaignID

path

string

true

The ID of the A/B campaign that you want to get a summary of.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the A/B split test campaign:

    • CampaignID - the ID of the winning campaign version.

    • A - an object that contains the following information for campaign A:

      • CampaignID - the ID of campaign A.

      • ABVersion - the version of the campaign. This is 0 for campaign A and 1 for campaign B.

      • CampaignName - the name of the campaign.

      • CampaignSubject - the subject of the campaign.

      • MailingLists - a list that contains the details of email lists and any segments that that campaign is sent to:

        • Campaign - this is null for this case.

        • ID - the ID of the email list.

        • Name - the name of the email list.

        • ActiveMemberCount - the number of active members in the email list.

        • BouncedMemberCount - the number of bounced emails in the email list.

        • RemovedMemberCount - the number of members removed from the email list.

        • UnsubscribedMemberCount - the number of emails that unsubscribed from the email list.

        • Status - status of the email list. For created, this is 0, for imported, this is 1, for importing, this is 2, and for deleted, this is 3.

        • CustomFieldsDefinition - an array containing the parameters of custom fields in the email list. The parameters are:

          • ID - the ID of the custom field.

          • Name - the name of the custom field

          • Context - the context of the custom field. This is null if the field type is not SingleSelectDropDown.

          • IsRequired - this is true if the custom field is required and false if it is not.

          • Type - the data type of the custom field. Possible values: 0 for text, 1 for number, 2 for dateTime, 3 for SingleSelectDropDown, and 5 for checkbox.

        • CreatedBy - the IP address used to create the email list.

        • CreatedOn - the date-time the email list was created.

        • UpdatedBy - the IP address used to update the email list.

        • UpdatedOn - the date-time the requested email list was updated.

        • ImportOperation - an object that contains the details of the latest import operation performed in the requested email list. This is blank if there was no import done.

          • ID - the ID of the import operation.

          • DataHash - a globally unique identifier (GUID) for the import operation

          • Mappings - the data mappings used for the specific import operation.

          • EmailNotify - this is null if the import operation notification email was not selected to be sent

          • CreatedOn - the date-time when the import operation was created.

          • StartedOn - the date-time when the import operation was stated.

          • CompletedOn - the date-time when the import operation was completed.

          • TotalInserted - the total number of inserted emails.

          • TotalUpdated - the total number of updated emails.

          • TotalUnsubscribed - the total number of unsubscribed emails.

          • TotalInvalid - the total number of invalid emails.

          • TotalIgnored - the total number of ignored emails.

          • TotalDuplicate - the total number of duplicate emails.

          • TotalMembers - the total number of members that were selected to be imported.

          • Message - the message of the import operation. This is null if successful.

          • Success - this is true if successful.

          • SkipNewMembers - this is false if the skip new members option was not selected before the import operation began.

        • Segment - a list of segments containing all the following information for each segment. This is null if the campaign was not sent to a email list segment.

          • ID - the ID of the segment.

          • Name - the name of the segment.

          • MatchType - specifies how subscribers are returned by your segment based on matching criteria. Possible values are:

            • 0 - for All. Returns subscribers that match all the given criteria.

            • 1 - for Any. Returns subscribers that match any of the given criteria.

          • Criteria - contains a list with information for each selected criterion selected for the segment.

          • CreatedBy - the IP address used to create the segment.

          • CreatedOn - the date-time the requested segment was created.

          • UpdatedBy - the IP address used to update the segment.

          • UpdatedOn - the date-time the segment was updated.

          • FetchType - the selected fetch type for the selected segment criteria. Possible values are:

            • 0 - for all segment criteria.

            • 1 - for the top segment criteria.

            • 2 - for the top percent segment criteria.

          • Description - contains a string representation of all the selected filters, MatchType criteria, and FetchType criteria.

      • CampaignDeliveredOn - the date-time the campaign was delivered.

      • To - the date-time the measurement ended.

      • From - the date-time the measurement started.

      • TotalOpens - the total number of email opens.

      • UniqueOpens - the total number of unique email opens.

      • TotalBounces - the total number of email bounces.

      • TotalComplaints - the total number of complaints.

      • TotalForwards - the total number of email forwards for the campaign using the Forward to a friend personalization tag.

      • UniqueForwards - the total number of unique forwards for the campaign using the Forward to a friend personalization tag.

      • TotalUnsubscribes - the total number of unsubscribed recipients for the campaign.

      • TotalLinkClicks - the total number of link clicks.

      • UniqueLinkClicks - the total number of unique link clicks.

      • Sent - the total number of campaign emails sent.

      • CampaignIsArchived - specifies whether the campaign has been archived. A campaign older than three months gets archived and only high-level data about the campaign becomes available.

Request
GET https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("campaigns/{CampaignID}/schedule.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/campaigns/{CampaignID}/schedule.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/campaigns/{CampaignID}/view_ab_summary.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "CampaignID": "afdc4ef6-999f-4d74-905b-ec234789f9d6",
    "A": {
      "CampaignID": "afdc4ef6-999f-4d74-905b-ec234789f9d6",
      "ABVersion": 0,
      "CampaignName": "Test AB content",
      "CampaignSubject": "Test AB content",
      "MailingLists": [
        {
          "Campaign": null,
          "MailingList": {
            "ID": "afdc4ef6-999f-4d74-905b-ec234789f9d6",
            "Name": "Customers",
            "ActiveMemberCount": 1600,
            "BouncedMemberCount": 0,
            "RemovedMemberCount": 5,
            "UnsubscribedMemberCount": 56,
            "Status": 0,
            "CustomFieldsDefinition": [],
            "CreatedBy": "200.205.214.234",
            "CreatedOn": "/Date(1454421389673+0000)/",
            "UpdatedBy": "200.205.214.234",
            "UpdatedOn": "/Date(1454421389673+0000)/",
            "ImportOperation": null
          },
          "Segment": null
        },
        {
          "Campaign": null,
          "MailingList": {
            "ID": "a589366a-1a34-4965-ac50-f121234we9e",
            "Name": "Customers2",
            "ActiveMemberCount": 0,
            "BouncedMemberCount": 0,
            "RemovedMemberCount": 0,
            "UnsubscribedMemberCount": 0,
            "Status": 0,
            "CustomFieldsDefinition": [],
            "CreatedBy": "000.205.214.234",
            "CreatedOn": "/Date(1461777017163+0100)/",
            "UpdatedBy": "000.205.214.234",
            "UpdatedOn": "/Date(1461779935800+0100)/",
            "ImportOperation": null
          },
          "Segment": null
        }
      ],
      "CampaignDeliveredOn": "/Date(1461783674793+0100)/",
      "To": "/Date(1465550745283+0100)/",
      "From": "/Date(1461779880247+0100)/",
      "TotalOpens": 1834,
      "UniqueOpens": 1111,
      "TotalBounces": 0,
      "TotalComplaints": 0,
      "TotalForwards": 67,
      "UniqueForwards": 44,
      "TotalUnsubscribes": 6,
      "TotalLinkClicks": 1444,
      "UniqueLinkClicks": 1234,
      "Sent": 1,
      "CampaignIsArchived": false
    },
    "B": {
      "CampaignID": "04d8677b-e87b-4489-99e6-5867b648e1be",
      "ABVersion": 1,
      "CampaignName": "Test AB content",
      "CampaignSubject": "Test AB content",
      "MailingLists": [
        {
          "Campaign": null,
          "MailingList": {
            "ID": "ba5ab5a8-391f-4e96-8a83-b6838af8683b",
            "Name": "Andreas2323",
            "ActiveMemberCount": 0,
            "BouncedMemberCount": 0,
            "RemovedMemberCount": 0,
            "UnsubscribedMemberCount": 0,
            "Status": 0,
            "CustomFieldsDefinition": [],
            "CreatedBy": "212.205.224.198",
            "CreatedOn": "/Date(1454421389673+0000)/",
            "UpdatedBy": "212.205.224.198",
            "UpdatedOn": "/Date(1454421389673+0000)/",
            "ImportOperation": null
          },
          "Segment": null
        },
        {
          "Campaign": null,
          "MailingList": {
            "ID": "a589466a-12344-4965-ac50-f1299fe5979e",
            "Name": "Customers",
            "ActiveMemberCount": 2030,
            "BouncedMemberCount": 0,
            "RemovedMemberCount": 12,
            "UnsubscribedMemberCount": 33,
            "Status": 0,
            "CustomFieldsDefinition": [],
            "CreatedBy": "2.11.710.201",
            "CreatedOn": "/Date(1461777017163+0100)/",
            "UpdatedBy": "2.11.70.209",
            "UpdatedOn": "/Date(1461779935800+0100)/",
            "ImportOperation": null
          },
          "Segment": null
        }
      ],
      "CampaignDeliveredOn": "/Date(1461783674793+0100)/",
      "To": "/Date(1465550745287+0100)/",
      "From": "/Date(1461779880247+0100)/",
      "TotalOpens": 1234,
      "UniqueOpens": 1111,
      "TotalBounces": 0,
      "TotalComplaints": 0,
      "TotalForwards": 12,
      "UniqueForwards": 12,
      "TotalUnsubscribes": 5,
      "TotalLinkClicks": 1222,
      "UniqueLinkClicks": 999,
      "Sent": 1,
      "CampaignIsArchived": false
    }
  }
}

Segments

Abstract

Overview of segmentation and describes how to use the Moosend API to work with segments, subscribers, and criteria.

Use the Moosend API to fetch your segments, fetch subscribers in a segment, get details about segments, create, update, add or update criteria, and delete segments.

Get all segments

Abstract

Describes the request and response details of this Moosend API endpoint to get all segments created in a mailing list.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list that contains the segments.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the requested segments:

    • Paging - an object that contains the following information:

      • PageSize - the page size of the results. This is 0 if not defined.

      • CurrentPage - the number of the result page. This is 1 if not defined.

      • Totalresults - the number of segments that are included in the response.

      • TotalPageCount - the total number of available segment pages for your account.

      • SortExpression - the sort expression associated with the column or columns being sorted.

      • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

    • Segments - a list of segments in the email list containing the following information for each segment:

      • ID - the ID of the segment.

      • Name - the name of the segment.

      • MatchType - specifies how subscribers are returned by your segment based on the matching criteria. Possible values are:

        • 0 - for All. Returns subscribers that match all the given criteria.

        • 1 - for Any. Returns subscribers that match any of the given criteria.

      • Criteria - contains a list with the following information for each selected criterion selected for the segment:

        • ID - the ID of the criteria.

        • SegmentID - the ID of the segment.

        • Field - the enum value of the selected filter.

        • CustomFieldID - if the selected filter is a custom field, this is the ID of the custom field.

        • Comparer - the operator that defines how to compare Field and Value. If not specified, Is is assumed.

          • 0 - for Is. Finds subscribers where the Field is exactly equal to the specified Value.

          • 1 - for IsNot. Finds subscribers where the Field is not equal to the specified Value.

          • 2 - for Contains. Finds subscribers where the Field contains the specified Value.

          • 3 - for DoesNotContain. Finds subscribers where the Field does not contain the specified Value.

          • 4 - for StartsWith. Finds subscribers where the Field starts with the specified Value.

          • 5 - for DoesNotStartWith. Finds subscribers where the Field does not start with the specified Value.

          • 6 - for EndsWith. Finds subscribers where the Field ends with the specified Value.

          • 7 - for DoesNotEndWith. Finds subscribers where the Field does not end with the specified Value.

          • 8 - for IsGreaterThan. Finds subscribers where the Field is greater than the specified Value.

          • 9 - for IsGreaterThanOrEqualTo. Finds subscribers where the Field is greater than or equal to the specified Value.

          • 10 - for IsLessThan. Finds subscribers where the Field is less than the specified Value.

          • 11 - for IsLessThanOrEqualTo. Finds subscribers where the Field is less than or equal to the specified Value.

          • 12 - for IsBefore. Finds subscribers where the Field is before the specified Value.

          • 13 - for IsAfter. Finds subscribers where the Field is after the specified Value.

          • 14 - for IsEmpty. Finds subscribers where the Field has no Value.

          • 15 - for IsNotEmpty. Finds subscribers where the Field contains a Value.

          • 16 - for IsTrue. Finds subscribers where the condition defined by the Field is true.

          • 17 - for IsFalse. Finds subscribers where the condition defined by the Field is false.

          • 24 - for IsBetween. Finds subscribers where the numeric value of a criterion is between two defined numbers.

          • 25 - for IsNotBetween. Finds subscribers where the numeric value of a criterion is not between two defined numbers.

        • Value - the search term used to filter the specified Field.

        • DateFrom - the starting date-time value selected to filter the results. If not selected, this is null.

        • DateTo - the ending date-time value selected to filter the results. If not selected, this is null.

        • Properties - this is null for this case.

        • Subscriteria - this is null for this case.

      • CreatedBy - the IP address used to create the requested segment.

      • CreatedOn - the date-time the requested segment was created.

      • UpdatedBy - the IP address used to update the requested segment.

      • UpdatedOn - the date-time the requested segment was updated.

      • FetchType - the selected fetch type for the selected segment criteria. Possible values are:

        • 0 - for all segment criteria.

        • 1 - for the top segment criteria.

        • 2 - for the top percent segment criteria.

      • FetchValue - the value used to apply the FetchType filter.

      • Description - contains a string representation of all the selected filters, MatchType and FetchType criteria.

Request
GET https://{hostname}/v3/lists/{MailingListID}/segments.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/lists/{MailingListID}/segments.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/segments.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/lists/{MailingListID}/segments.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/lists/{MailingListID}/segments.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/lists/{MailingListID}/segments.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{MailingListID}/segments.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/segments.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/lists/{MailingListID}/segments.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/lists/{MailingListID}/segments.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("segments/{SegmentID}/details.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/segments.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/segments/{SegmentID}/details.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/segments.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/segments.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 100,
      "CurrentPage": 1,
      "TotalResults": 1,
      "TotalPageCount": 1,
      "SortExpression": "CreatedOn",
      "SortIsAscending": false
    },
    "Segments": [
      {
        "ID": 7314,
        "Name": "City",
        "MatchType": 1,
        "Criteria": [
          {
            "ID": 12244,
            "SegmentID": 7314,
            "Field": 2,
            "CustomFieldID": null,
            "Comparer": 0,
            "Value": "test",
            "DateFrom": null,
            "DateTo": null,
            "Properties": null,
            "Subscriteria": null
          },
          {
            "ID": 12348,
            "SegmentID": 7314,
            "Field": 99,
            "CustomFieldID": "e4823107-d02d-48af-8190-d8694a33401e",
            "Comparer": 0,
            "Value": "UK",
            "DateFrom": null,
            "DateTo": null,
            "Properties": null,
            "Subscriteria": null
          }
        ],
        "CreatedBy": "211.11.111.11",
        "CreatedOn": "/Date(1451490040010+0000)/",
        "UpdatedBy": "211.11.111.11",
        "UpdatedOn": "/Date(1451490040010+0000)/",
        "FetchType": 0,
        "FetchValue": 0,
        "Description": "Fetch all where \"City\" is \"UK\" or \"Recipient Name\" is \"Test\""
      }
    ]
  }
}

Get segment details

Abstract

Describes the request and response details of this Moosend API endpoint to get the details of a specific segment.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list that contains the segment.

SegmentID

path

string

true

The ID of the segment that contains the details you are requesting.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the requested segment:

    • ID - the ID of the segment.

    • Name - the name of the segment.

    • MatchType - specifies how subscribers are returned by your segment based on the matching criteria. Possible values are:

      • 0 - for All. Returns subscribers that match all the given criteria.

      • 1 - for Any. Returns subscribers that match any of the given criteria.

    • Criteria - contains a list with the following information for each selected criterion selected for the segment:

      • ID - the ID of the criteria.

      • SegmentID - the ID of the segment.

      • Field - the enum value of the selected filter.

      • CustomFieldID - if the selected filter is a custom field, this is the ID of the custom field.

      • Comparer - the operator that defines how to compare Field and Value. If not specified, Is is assumed.

        • 0 - for Is. Finds subscribers where the Field is exactly equal to the specified Value.

        • 1 - for IsNot. Finds subscribers where the Field is not equal to the specified Value.

        • 2 - for Contains. Finds subscribers where the Field contains the specified Value.

        • 3 - for DoesNotContain. Finds subscribers where the Field does not contain the specified Value.

        • 4 - for StartsWith. Finds subscribers where the Field starts with the specified Value.

        • 5 - for DoesNotStartWith. Finds subscribers where the Field does not start with the specified Value.

        • 6 - for EndsWith. Finds subscribers where the Field ends with the specified Value.

        • 7 - for DoesNotEndWith. Finds subscribers where the Field does not end with the specified Value.

        • 8 - for IsGreaterThan. Finds subscribers where the Field is greater than the specified Value.

        • 9 - for IsGreaterThanOrEqualTo. Finds subscribers where the Field is greater than or equal to the specified Value.

        • 10 - for IsLessThan. Finds subscribers where the Field is less than the specified Value.

        • 11 - for IsLessThanOrEqualTo. Finds subscribers where the Field is less than or equal to the specified Value.

        • 12 - for IsBefore. Finds subscribers where the Field is before the specified Value.

        • 13 - for IsAfter. Finds subscribers where the Field is after the specified Value.

        • 14 - for IsEmpty. Finds subscribers where the Field has no Value.

        • 15 - for IsNotEmpty. Finds subscribers where the Field contains a Value.

        • 16 - for IsTrue. Finds subscribers where the condition defined by the Field is true.

        • 17 - for IsFalse. Finds subscribers where the condition defined by the Field is false.

        • 24 - for IsBetween. Finds subscribers where the numeric value of a criterion is between two defined numbers.

        • 25 - for IsNotBetween. Finds subscribers where the numeric value of a criterion is not between two defined numbers.

      • Value - the search term used to filter the specified Field.

      • DateFrom - the starting date-time value selected to filter the results. If not selected, this is null.

      • DateTo - the ending date-time value selected to filter the results. If not selected, this is null.

      • Properties - this is null for this case.

      • Subscriteria - this is null for this case.

    • CreatedBy - the IP address used to create the requested segment.

    • CreatedOn - the date-time the requested segment was created.

    • UpdatedBy - the IP address used to update the requested segment.

    • UpdatedOn - the date-time the requested segment was updated.

    • FetchType - the selected fetch type for the selected segment criteria. Possible values are:

      • 0 - for all segment criteria.

      • 1 - for the top segment criteria.

      • 2 - for the top percent segment criteria.

    • FetchValue - the value used to apply the FetchType filter.

    • Description - contains a string representation of all the selected filters, MatchType and FetchType criteria.

Request
GET https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/details.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/details.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/details.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/details.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/details.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/details.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/details.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/details.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/details.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/details.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("segments/{SegmentID}/details.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/details.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/segments/{SegmentID}/details.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
SURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/details.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/details.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "ID": 10198,
    "Name": "test",
    "MatchType": 0,
    "Criteria": [
      {
        "ID": 15778,
        "SegmentID": 10198,
        "Field": 2,
        "CustomFieldID": null,
        "Comparer": 0,
        "Value": "Paul",
        "DateFrom": null,
        "DateTo": null,
        "Properties": null,
        "Subscriteria": null
      },
      {
        "ID": 15779,
        "SegmentID": 10198,
        "Field": 4,
        "CustomFieldID": null,
        "Comparer": 8,
        "Value": "5",
        "DateFrom": "/Date(1465167600000+0100)/",
        "DateTo": "/Date(1465945200000+0100)/",
        "Properties": null,
        "Subscriteria": null
      }
    ],
    "CreatedBy": "212.123.123.112",
    "CreatedOn": "/Date(1465806037033+0100)/",
    "UpdatedBy": "212.123.123.112",
    "UpdatedOn": "/Date(1465806269980+0100)/",
    "FetchType": 0,
    "FetchValue": 0,
    "Description": "Fetch all where \"Recipient Name\" is \"Paul\" and \"Campaigns Opened\" is greater than \"5\""
  }
}

Get segment subscribers

Abstract

Describes the request and response details of this Moosend API endpoint to get the subscribers of a specific segment.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list that contains the segment.

SegmentID

path

string

true

The ID of the segment that contains the subscribers you are requesting.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - an object that contains all the following information for the requested segment:

    • Paging - an object that contains the following information:

      • PageSize - the page size of the results. This is 0 if not defined.

      • CurrentPage - the number of the result page. This is 1 if not defined.

      • Totalresults - the number of segment subscribers that are included in the response.

      • TotalPageCount - the total number of available segment subscriber pages for your account.

      • SortExpression - the sort expression associated with the column or columns being sorted.

      • SortIsAscending - this is false if the results are not displayed in ascending order based on the sort expression.

    • Subscribers - a list of subscribers included in the segment containing the following information for each subscriber:

      • ID - the ID of the subscriber.

      • Name - the name of the subscriber.

      • Email - the email address of the subscriber.

      • CreatedOn - the date-time the subscriber was added to the email list.

      • UpdatedOn - the date-time the subscriber was updated in the email list.

      • UnsubscribedOn - the date-time the subscriber was unsubscribed from the email list.

      • UnsubscribedFromID - the ID that the subscriber is unsubscribed from.

      • SubscribeType - the status of the subscriber. For subscribed, this is 1, for unsubscribed, this is 2, for bounced, this is 3, and for removed, this is 4.

      • CustomFields - a list containing the custom fields of the subscriber. Each custom field includes the following:

        • CustomFieldID - the ID of the custom field.

        • Name - the name of the custom field.

        • Value - the value of the custom field.

      • RemovedOn - the date-time the subscriber was removed from the email list.

Request
GET https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/members.{Format}?apikey=
Request
curl --include \
'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/members.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/members.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .get();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('GET', 'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/members.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request('https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/members.{Format}?apikey=', function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->get("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/members.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/members.{Format}?apikey=')

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/members.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.get 'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/members.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("GET", "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/members.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.GetAsync("segments/{SegmentID}/details.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/members.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "GET"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.get( path : "/segments/{SegmentID}/details.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/members.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/members.{Format}?apikey=")!
var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": {
    "Paging": {
      "PageSize": 500,
      "CurrentPage": 1,
      "TotalResults": 2,
      "TotalPageCount": 1,
      "SortExpression": null,
      "SortIsAscending": false
    },
    "Subscribers": [
      {
        "ID": "07111755-8ee4-1111-ad2b-1111899c6f",
        "Name": "Paul",
        "Email": "paul@email.com",
        "CreatedOn": "/Date(1461777177393+0100)/",
        "UpdatedOn": "/Date(1461777177393+0100)/",
        "UnsubscribedOn": null,
        "UnsubscribedFromID": null,
        "SubscribeType": 1,
        "SubscribeMethod": 2,
        "CustomFields": [
          {
            "CustomFieldID": "63705cf2-7cbb-4ac1-a246-1a8c1b416026",
            "Name": "CheckBox",
            "Value": "True"
          },
          {
            "CustomFieldID": "63705cf2-7cbb-4ac1-a246-1a8c1b416026",
            "Name": "Date",
            "Value": "4/12/2016 12:00:00 AM"
          },
          {
            "CustomFieldID": "9df6dcc4-bef2-47e7-93af-86889b6b6d6a",
            "Name": "Age",
            "Value": "25"
          },
          {
            "CustomFieldID": "0d2199aa-65fc-448c-b9fe-199e3b72ebc5",
            "Name": "Some custom field",
            "Value": "Something2"
          },
          {
            "CustomFieldID": "46721a6b-09aa-46ff-bab1-a0b75dea24cf",
            "Name": "Some custom field 2",
            "Value": "Text2"
          }
        ],
        "RemovedOn": null
      },
      {
        "ID": "0bb00735-7ec7-41de-ab04-d622f67340c4",
        "Name": "John",
        "Email": "john@email.com",
        "CreatedOn": "/Date(1461777334373+0100)/",
        "UpdatedOn": "/Date(1461783253670+0100)/",
        "UnsubscribedOn": null,
        "UnsubscribedFromID": null,
        "SubscribeType": 1,
        "SubscribeMethod": 0,
        "CustomFields": [
          {
            "CustomFieldID": "0bb00735-7ec7-41de-ab04-d622f67340c4",
            "Name": "Country",
            "Value": "UK"
          },
          {
            "CustomFieldID": "46721a6b-09aa-46ff-bab1-a0b75dea24cf",
            "Name": "Status",
            "Value": "single"
          }
        ],
        "RemovedOn": null
      }
    ]
  }
}

Create an empty segment

Abstract

Describes the request and response details of this Moosend API endpoint to create an empty segment in a specific email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list where the segment is created.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the segment.

MatchType

body

string

false

Specifies how subscribers are returned by your segment based on matching criteria:

  • All (Default) - returns subscribers that match all the given criteria.

  • Any - returns subscribers that match any of the given criteria.

FetchType

body

string

false

Specifies how many criteria-matching subscribers are contained in your segment:

  • All - returns all criteria matching subscribers.

  • Top - returns only a maximum number of subscribers defined in FetchValue.

  • TopPercent - returns only a percentage of subscribers defined in FetchValue.

FetchValue

body

integer

false

Specifies the maximum number for FetchType:Top or percentage for FetchType:TopPercent of members to be contained in the created segment. If not specified, 0 is assumed.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - the ID of the segment created.

Request
POST https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=

Request body:
{
  "Name": "New Customers",
  "MatchType": "All",
  "FetchType": "Top",
  "FetchValue": "200"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
  \"Name\":\"New Customers\",
  \"MatchType\":\"All\",
  \"FetchType\":\"Top\",
  \"FetchValue\":\"200\"
}" \
'https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"New Customers\",  \"MatchType\": \"All\",  \"FetchType\": \"Top\",  \"FetchValue\": \"200\"}");
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'New Customers',
  'MatchType': 'All',
  'FetchType': 'Top',
  'FetchValue': '200'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"New Customers\",  \"MatchType\": \"All\",  \"FetchType\": \"Top\",  \"FetchValue\": \"200\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "New Customers",  "MatchType": "All",  "FetchType": "Top",  "FetchValue": "200"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "New Customers",
    "MatchType": "All",
    "FetchType": "Top",
    "FetchValue": "200"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"New Customers\",
  \"MatchType\": \"All\",
  \"FetchType\": \"Top\",
  \"FetchValue\": \"200\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "New Customers",
  "MatchType": "All",
  "FetchType": "Top",
  "FetchValue": "200"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"New Customers\",\n  \"MatchType\": \"All\",\n  \"FetchType\": \"Top\",\n  \"FetchValue\": \"200\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"New Customers\",  \"MatchType\": \"All\",  \"FetchType\": \"Top\",  \"FetchValue\": \"200\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("segments/create.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""New Customers\"",
  \""MatchType\"": \""All\"",
  \""FetchType\"": \""Top\"",
  \""FetchValue\"": \""200\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "New Customers",
  "MatchType": "All",
  "FetchType": "Top",
  "FetchValue": "200"
}')
response = client.post( path : "/segments/create.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"New Customers\",\n  \"MatchType\": \"All\",\n  \"FetchType\": \"Top\",\n  \"FetchValue\": \"200\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"New Customers\",\n  \"MatchType\": \"All\",\n  \"FetchType\": \"Top\",\n  \"FetchValue\": \"200\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": 10199
}

Create a segment with criteria

Abstract

Describes the request and response details of this Moosend API endpoint to create a segment with criteria in a specific email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list where the segment is created.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Name

body

string

true

The name of the segment.

MatchType

body

string

false

Specifies how subscribers are returned by your segment based on matching criteria:

  • All (Default) - returns subscribers that match all the given criteria.

  • Any - returns subscribers that match any of the given criteria.

FetchType

body

string

false

Specifies how many criteria-matching subscribers are contained in your segment:

  • All - returns all criteria matching subscribers.

  • Top - returns only a maximum number of subscribers defined in FetchValue.

  • TopPercent - returns only a percentage of subscribers defined in FetchValue.

FetchValue

body

integer

false

Specifies the maximum number for FetchType:Top or percentage for FetchType:TopPercent of members to be contained in the created segment. If not specified, 0 is assumed.

Criteria

body

array

true

An array containing the criteria parameters used to filter the email list:

  • Field - the criterion used to filter the email list. See Field values.

  • Comparer - the operator that defines how to compare a Field with its Value. See Comparer values.

  • Value - the search term used to filter the specified Field.

  • LastXMinutes - constrains the results by the time that has elapsed.

  • DateFrom to DateTo - constrains the results by a date span.

  • Date Function - the value used with custom fields of dateTime data type. See DateFunction values.

Field values

Select one of the following Field values to filter the email list:

  • DateAdded - filters subscribers by the date they were added to the email list.

  • DateUpdated - filters subscribers by the date they were last updated in the email list.

  • RecipientName - filters subscribers by name.

  • RecipientEmail - filters subscribers by their email address.

  • SubscribeMethod - filters subscribers by their subscription method.

  • CustomField - filters subscribers by the value of a custom field.

  • MailingList - filters subscribers by the email list they belong to.

  • CampaignsOpened - filters subscribers by the number of campaigns they have opened within the past 60 days.

  • LinksClicked - filters subscribers by the number of links they have clicked from the campaigns sent to them within the past 60 days.

  • CampaignName - filters subscribers by the name of the campaign they have opened.

  • LinkURL - filters subscribers by the URL of the link they have clicked.

  • CampaignSent - filters subscribers by the campaign they have received or not received.

  • Platform - filters subscribers by the platform they use.

  • OperatingSystems - filters subscribers by the operating system they use.

  • EmailClient - filters subscribers by the email client they use.

  • WebBrowser - filters subscribers by the web browser they use.

  • MobileBrowser - filters subscribers by the mobile browser they use.

  • AddedAnythingToCart - filters subscribers by their cart history in a tracked website.

  • ViewedProduct - filters subscribers by their browsing history in a tracked website.

  • PurchasedProduct - filters subscribers by their purchase history in a tracked website.

Comparer values

Select one of the following Comparer operators to compare a criterion field with its value:

  • Is - finds subscribers where the Field is exactly equal to the specified Value.

  • IsNot - finds subscribers where the Field is not equal to the specified Value

  • Contains - finds subscribers where the Field contains the specified Value.

  • DoesNotContain - finds subscribers where the Field does not contain the specified Value.

  • StartsWith - finds subscribers where the Field starts with the specified Value.

  • DoesNotStartWith - finds subscribers where the Field does not start with the specified Value.

  • EndsWith - finds subscribers where the Field ends with the specified Value.

  • DoesNotEndWith - finds subscribers where the Field does not end with the specified Value.

  • IsGreaterThan - finds subscribers where the Field is greater than the specified Value.

  • IsGreaterThanOrEqualTo - finds subscribers where the Field is greater than or equal to the specified Value.

  • IsLessThan - finds subscribers where the Field is less than the specified Value.

  • IsLessThanOrEqualTo - finds subscribers where the Field is less than or equal to the specified Value.

  • IsBefore - finds subscribers where the Field is before the specified Value.

  • IsAfter - finds subscribers where the Field is after the specified Value.

  • IsEmpty - finds subscribers where the Field has no Value.

  • IsNotEmpty - finds subscribers where the Field contains a Value.

  • IsTrue - finds subscribers where the condition defined by the Field is true.

  • IsFalse - finds subscribers where the condition defined by the Field is false.

DateFunction values

Select one of the following to use with fields of DateTime data type.

  • Year - the four-digit year part of the date.

  • Month - the month part of the date from 1 to 12.

  • Day - the day part of the date from 1 to 31.

  • WeekDay - the day of the week from 1 to 7. For example, 1 for Sunday, 2 for Monday, and so on.

  • DaysPassed - the number of days that have passed until now.

  • HoursPassed - the number of hours that have passed until now.

  • MinutesPassed - the number of minutes that have passed until now.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - the ID of the segment created.

Request
POST https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=

Request body:
{
  "Name": "Engaged and Verified",
  "MatchType": "All",
  "FetchType": "All",
  "Criteria": [
    {
      "Field": "VerifiedForDoubleOptIn",
      "Comparer": "IsTrue"
    },
    {
      "Field": "LinksClicked",
      "Comparer": "Is",
      "Value": "2",
      "LastXMinutes": 43200
    }
  ]
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
  \"Name\":\"Engaged and Verified\",
  \"MatchType\":\"All\",
  \"FetchType\":\"All\",
  \"Criteria\": [
      {
        \"Field\":\"VerifiedForDoubleOptIn\",
        \"Comparer\":\"IsTrue\"
      },
      {
        \"Field\":\"LinksClicked\",
        \"Comparer\":\"Is\",
        \"Value\":\"2\",
        \"LastXMinutes\":43200
      }
    ]
}" \
'https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey='
Request
// Maven : Add these dependecies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"Engaged and Verified\",  \"MatchType\": \"All\",  \"FetchType\": \"All\",  \"Criteria\": [    {      \"Field\": \"VerifiedForDoubleOptIn\",      \"Comparer\": \"IsTrue\"    },    {      \"Field\": \"LinksClicked\",      \"Comparer\": \"Is\",      \"Value\": \"2\",      \"LastXMinutes\": 43200    }  ]}");
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
 
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'Engaged and Verified',
  'MatchType': 'All',
  'FetchType': 'All',
  'Criteria': [
    {
      'Field': 'VerifiedForDoubleOptIn',
      'Comparer': 'IsTrue'
    },
    {
      'Field': 'LinksClicked',
      'Comparer': 'Is',
      'Value': '2',
      'LastXMinutes': 43200
    }
  ]
};

request.send(JSON.stringify(body));
Request
 
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"Engaged and Verified\",  \"MatchType\": \"All\",  \"FetchType\": \"All\",  \"Criteria\": [    {      \"Field\": \"VerifiedForDoubleOptIn\",      \"Comparer\": \"IsTrue\"    },    {      \"Field\": \"LinksClicked\",      \"Comparer\": \"Is\",      \"Value\": \"2\",      \"LastXMinutes\": 43200    }  ]}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
 
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "Engaged and Verified",  "MatchType": "All",  "FetchType": "All",  "Criteria": [    {      "Field": "VerifiedForDoubleOptIn",      "Comparer": "IsTrue"    },    {      "Field": "LinksClicked",      "Comparer": "Is",      "Value": "2",      "LastXMinutes": 43200    }  ]}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
 
from urllib2 import Request, urlopen

values = """
  {
    "Name": "Engaged and Verified",
    "MatchType": "All",
    "FetchType": "All",
    "Criteria": [
      {
        "Field": "VerifiedForDoubleOptIn",
        "Comparer": "IsTrue"
      },
      {
        "Field": "LinksClicked",
        "Comparer": "Is",
        "Value": "2",
        "LastXMinutes": 43200
      }
    ]
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"Engaged and Verified\",
  \"MatchType\": \"All\",
  \"FetchType\": \"All\",
  \"Criteria\": [
    {
      \"Field\": \"VerifiedForDoubleOptIn\",
      \"Comparer\": \"IsTrue\"
    },
    {
      \"Field\": \"LinksClicked\",
      \"Comparer\": \"Is\",
      \"Value\": \"2\",
      \"LastXMinutes\": 43200
    }
  ]
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
 
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "Engaged and Verified",
  "MatchType": "All",
  "FetchType": "All",
  "Criteria": [
    {
      "Field": "VerifiedForDoubleOptIn",
      "Comparer": "IsTrue"
    },
    {
      "Field": "LinksClicked",
      "Comparer": "Is",
      "Value": "2",
      "LastXMinutes": 43200
    }
  ]
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"Engaged and Verified\",\n  \"MatchType\": \"All\",\n  \"FetchType\": \"All\",\n  \"Criteria\": [\n    {\n      \"Field\": \"VerifiedForDoubleOptIn\",\n      \"Comparer\": \"IsTrue\"\n    },\n    {\n      \"Field\": \"LinksClicked\",\n      \"Comparer\": \"Is\",\n      \"Value\": \"2\",\n      \"LastXMinutes\": 43200\n    }\n  ]\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
 
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"Engaged and Verified\",  \"MatchType\": \"All\",  \"FetchType\": \"All\",  \"Criteria\": [    {      \"Field\": \"VerifiedForDoubleOptIn\",      \"Comparer\": \"IsTrue\"    },    {      \"Field\": \"LinksClicked\",      \"Comparer\": \"Is\",      \"Value\": \"2\",      \"LastXMinutes\": 43200    }  ]}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("segments/create.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
 
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""Engaged and Verified\"",
  \""MatchType\"": \""All\"",
  \""FetchType\"": \""All\"",
  \""Criteria\"": [
    {
      \""Field\"": \""VerifiedForDoubleOptIn\"",
      \""Comparer\"": \""IsTrue\""
    },
    {
      \""Field\"": \""LinksClicked\"",
      \""Comparer\"": \""Is\"",
      \""Value\"": \""2\"",
      \""LastXMinutes\"": 43200
    }
  ]
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
 
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "Engaged and Verified",
  "MatchType": "All",
  "FetchType": "All",
  "Criteria": [
    {
      "Field": "VerifiedForDoubleOptIn",
      "Comparer": "IsTrue"
    },
    {
      "Field": "LinksClicked",
      "Comparer": "Is",
      "Value": "2",
      "LastXMinutes": 43200
    }
  ]
}')
response = client.post( path : "/segments/create.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
 
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"Engaged and Verified\",\n  \"MatchType\": \"All\",\n  \"FetchType\": \"All\",\n  \"Criteria\": [\n    {\n      \"Field\": \"VerifiedForDoubleOptIn\",\n      \"Comparer\": \"IsTrue\"\n    },\n    {\n      \"Field\": \"LinksClicked\",\n      \"Comparer\": \"Is\",\n      \"Value\": \"2\",\n      \"LastXMinutes\": 43200\n    }\n  ]\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
 
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/segments/create.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"Engaged and Verified\",\n  \"MatchType\": \"All\",\n  \"FetchType\": \"All\",\n  \"Criteria\": [\n    {\n      \"Field\": \"VerifiedForDoubleOptIn\",\n      \"Comparer\": \"IsTrue\"\n    },\n    {\n      \"Field\": \"LinksClicked\",\n      \"Comparer\": \"Is\",\n      \"Value\": \"2\",\n      \"LastXMinutes\": 43200\n    }\n  ]\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": 10199
}

Update a segment

Abstract

Describes the request and response details of this Moosend API endpoint to update a segment in a specific email list.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list that contains the segment.

SegmentID

path

string

true

The ID of the segment to be updated.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Name

body

string

false

The name of the segment.

If not specified, the existing name is retained.

MatchType

body

string

false

Specifies how subscribers are returned by your segment based on matching criteria.

If not specified, All is assumed.

  • All (Default) - returns subscribers that match all the given criteria.

  • Any - returns subscribers that match any of the given criteria.

FetchType

body

string

false

Specifies how many criteria-matching subscribers are contained in your segment.

If not specified, All is assumed.

  • All - returns all criteria matching subscribers.

  • Top - returns only a maximum number of subscribers defined in FetchValue.

  • TopPercent - returns only a percentage of subscribers defined in FetchValue.

FetchValue

body

integer

false

Specifies the maximum number for FetchType:Top or percentage for FetchType:TopPercent of members to be contained in the created segment.

If not specified, 0 is assumed.

Criteria

body

array

false

An array containing the criteria parameters used to filter the email list.

If not specified, existing criteria are retained.

  • Field - the criterion used to filter the email list. See Field values.

  • Comparer - the operator that defines how to compare a Field with its Value. See Comparer values.

  • Value - the search term used to filter the specified Field.

  • LastXMinutes - constrains the results by the time that has elapsed.

  • DateFrom toDateTo - constrains the results by a date span.

  • Date Function - the value used with custom fields of dateTime data type. See DateFunction values.

Field values

Select one of the following Field values to filter the email list:

  • DateAdded - filters subscribers by the date they were added to the email list.

  • DateUpdated - filters subscribers by the date they were last updated in the email list.

  • RecipientName - filters subscribers by name.

  • RecipientEmail - filters subscribers by their email address.

  • SubscribeMethod - filters subscribers by their subscription method.

  • CustomField - filters subscribers by the value of a custom field.

  • MailingList - filters subscribers by the email list they belong to.

  • CampaignsOpened - filters subscribers by the number of campaigns they have opened within the past 60 days.

  • LinksClicked - filters subscribers by the number of links they have clicked from the campaigns sent to them within the past 60 days.

  • CampaignName - filters subscribers by the name of the campaign they have opened.

  • LinkURL - filters subscribers by the URL of the link they have clicked.

  • CampaignSent - filters subscribers by the campaign they have received or not received.

  • Platform - filters subscribers by the platform they use.

  • OperatingSystems - filters subscribers by the operating system they use.

  • EmailClient - filters subscribers by the email client they use.

  • WebBrowser - filters subscribers by the web browser they use.

  • MobileBrowser - filters subscribers by the mobile browser they use.

  • AddedAnythingToCart - filters subscribers by their cart history in a tracked website.

  • ViewedProduct - filters subscribers by their browsing history in a tracked website.

  • PurchasedProduct - filters subscribers by their purchase history in a tracked website.

Comparer values

Select one of the following Comparer operators to compare a criterion field with its value:

  • Is - finds subscribers where the Field is exactly equal to the specified Value.

  • IsNot - finds subscribers where the Field is not equal to the specified Value

  • Contains - finds subscribers where the Field contains the specified Value.

  • DoesNotContain - finds subscribers where the Field does not contain the specified Value.

  • StartsWith - finds subscribers where the Field starts with the specified Value.

  • DoesNotStartWith - finds subscribers where the Field does not start with the specified Value.

  • EndsWith - finds subscribers where the Field ends with the specified Value.

  • DoesNotEndWith - finds subscribers where the Field does not end with the specified Value.

  • IsGreaterThan - finds subscribers where the Field is greater than the specified Value.

  • IsGreaterThanOrEqualTo - finds subscribers where the Field is greater than or equal to the specified Value.

  • IsLessThan - finds subscribers where the Field is less than the specified Value.

  • IsLessThanOrEqualTo - finds subscribers where the Field is less than or equal to the specified Value.

  • IsBefore - finds subscribers where the Field is before the specified Value.

  • IsAfter - finds subscribers where the Field is after the specified Value.

  • IsEmpty - finds subscribers where the Field has no Value.

  • IsNotEmpty - finds subscribers where the Field contains a Value.

  • IsTrue - finds subscribers where the condition defined by the Field is true.

  • IsFalse - finds subscribers where the condition defined by the Field is false.

DateFunction values

Select one of the following to use with fields of DateTime data type.

  • Year - the four-digit year part of the date.

  • Month - the month part of the date from 1 to 12.

  • Day - the day part of the date from 1 to 31.

  • WeekDay - the day of the week from 1 to 7. For example, 1 for Sunday, 2 for Monday, and so on.

  • DaysPassed - the number of days that have passed until now.

  • HoursPassed - the number of hours that have passed until now.

  • MinutesPassed - the number of minutes that have passed until now.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - this is null if successful.

Request
POST https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/update.{Format}?apikey=

Request body:
{
  "Name": "Customer Tracking and Opener",
  "MatchType": "Any",
  "FetchType": "All",
  "Criteria": [
    {
      "Field": "AddedAnythingToCart",
      "Comparer": "IsTrue",
      "Times": 2,
      "ProductCode": "123",
      "LastXMinutes": 4320,
      "WebsiteId": "12345678-1234-abdc-efgh-1231bc456efg789hij"
    },
    {
      "Field": "OpenedAnyCampaign",
      "Comparer": "IsTrue",
      "DateFrom": "2019-09-01",
      "DateTo": "2020-12-01"
    }
  ]
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
  \"Name\":\"Customer Tracking and Opener\",
  \"MatchType\":\"Any\",
  \"FetchType\":\"All\",
  \"Criteria\": [
      {
        \"Field\":\"AddedAnythingToCart\",
        \"Comparer\":\"IsTrue\",
        \"Times\":2,
        \"ProductCode\":\"123\",
        \"LastXMinutes\":4320,
        \"WebsiteId\":\"12345678-1234-abdc-efgh-1231bc456efg789hij\"
      },
      {
        \"Field\":\"OpenedAnyCampaign\",
        \"Comparer\":\"IsTrue\",
        \"DateFrom\":\"2019-09-01\",
        \"DateTo\":\"2020-12-01\"
      }
    ]
}" \
'https://{hostname}/v3/lists/{MailingListID}/segments/SegmentID/update.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Name\": \"Customer Tracking and Opener\",  \"MatchType\": \"Any\",  \"FetchType\": \"All\",  \"Criteria\": [    {      \"Field\": \"AddedAnythingToCart\",      \"Comparer\": \"IsTrue\",      \"Times\": 2,      \"ProductCode\": \"123\",      \"LastXMinutes\": 4320,      \"WebsiteId\": \"12345678-1234-abdc-efgh-1231bc456efg789hij\"    },    {      \"Field\": \"OpenedAnyCampaign\",      \"Comparer\": \"IsTrue\",      \"DateFrom\": \"2019-09-01\",      \"DateTo\": \"2020-12-01\"    }  ]}");
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/segments/SegmentID/update.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/lists/{MailingListID}/segments/SegmentID/update.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Name': 'Customer Tracking and Opener',
  'MatchType': 'Any',
  'FetchType': 'All',
  'Criteria': [
    {
      'Field': 'AddedAnythingToCart',
      'Comparer': 'IsTrue',
      'Times': 2,
      'ProductCode': '123',
      'LastXMinutes': 4320,
      'WebsiteId': '12345678-1234-abdc-efgh-1231bc456efg789hij'
    },
    {
      'Field': 'OpenedAnyCampaign',
      'Comparer': 'IsTrue',
      'DateFrom': '2019-09-01',
      'DateTo': '2020-12-01'
    }
  ]
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/lists/{MailingListID}/segments/SegmentID/update.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Name\": \"Customer Tracking and Opener\",  \"MatchType\": \"Any\",  \"FetchType\": \"All\",  \"Criteria\": [    {      \"Field\": \"AddedAnythingToCart\",      \"Comparer\": \"IsTrue\",      \"Times\": 2,      \"ProductCode\": \"123\",      \"LastXMinutes\": 4320,      \"WebsiteId\": \"12345678-1234-abdc-efgh-1231bc456efg789hij\"    },    {      \"Field\": \"OpenedAnyCampaign\",      \"Comparer\": \"IsTrue\",      \"DateFrom\": \"2019-09-01\",      \"DateTo\": \"2020-12-01\"    }  ]}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Name": "Customer Tracking and Opener",  "MatchType": "Any",  "FetchType": "All",  "Criteria": [    {      "Field": "AddedAnythingToCart",      "Comparer": "IsTrue",      "Times": 2,      "ProductCode": "123",      "LastXMinutes": 4320,      "WebsiteId": "12345678-1234-abdc-efgh-1231bc456efg789hij"    },    {      "Field": "OpenedAnyCampaign",      "Comparer": "IsTrue",      "DateFrom": "2019-09-01",      "DateTo": "2020-12-01"    }  ]}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/lists/{MailingListID}/segments/SegmentID/update.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Name": "Customer Tracking and Opener",
    "MatchType": "Any",
    "FetchType": "All",
    "Criteria": [
      {
        "Field": "AddedAnythingToCart",
        "Comparer": "IsTrue",
        "Times": 2,
        "ProductCode": "123",
        "LastXMinutes": 4320,
        "WebsiteId": "12345678-1234-abdc-efgh-1231bc456efg789hij"
      },
      {
        "Field": "OpenedAnyCampaign",
        "Comparer": "IsTrue",
        "DateFrom": "2019-09-01",
        "DateTo": "2020-12-01"
      }
    ]
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/lists/{MailingListID}/segments/SegmentID/update.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/segments/SegmentID/update.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Name\": \"Customer Tracking and Opener\",
  \"MatchType\": \"Any\",
  \"FetchType\": \"All\",
  \"Criteria\": [
    {
      \"Field\": \"AddedAnythingToCart\",
      \"Comparer\": \"IsTrue\",
      \"Times\": 2,
      \"ProductCode\": \"123\",
      \"LastXMinutes\": 4320,
      \"WebsiteId\": \"12345678-1234-abdc-efgh-1231bc456efg789hij\"
    },
    {
      \"Field\": \"OpenedAnyCampaign\",
      \"Comparer\": \"IsTrue\",
      \"DateFrom\": \"2019-09-01\",
      \"DateTo\": \"2020-12-01\"
    }
  ]
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Name": "Customer Tracking and Opener",
  "MatchType": "Any",
  "FetchType": "All",
  "Criteria": [
    {
      "Field": "AddedAnythingToCart",
      "Comparer": "IsTrue",
      "Times": 2,
      "ProductCode": "123",
      "LastXMinutes": 4320,
      "WebsiteId": "12345678-1234-abdc-efgh-1231bc456efg789hij"
    },
    {
      "Field": "OpenedAnyCampaign",
      "Comparer": "IsTrue",
      "DateFrom": "2019-09-01",
      "DateTo": "2020-12-01"
    }
  ]
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/lists/{MailingListID}/segments/SegmentID/update.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Name\": \"Customer Tracking and Opener\",\n  \"MatchType\": \"Any\",\n  \"FetchType\": \"All\",\n  \"Criteria\": [\n    {\n      \"Field\": \"AddedAnythingToCart\",\n      \"Comparer\": \"IsTrue\",\n      \"Times\": 2,\n      \"ProductCode\": \"123\",\n      \"LastXMinutes\": 4320,\n      \"WebsiteId\": \"12345678-1234-abdc-efgh-1231bc456efg789hij\"\n    },\n    {\n      \"Field\": \"OpenedAnyCampaign\",\n      \"Comparer\": \"IsTrue\",\n      \"DateFrom\": \"2019-09-01\",\n      \"DateTo\": \"2020-12-01\"\n    }\n  ]\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/lists/{MailingListID}/segments/SegmentID/update.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Name\": \"Customer Tracking and Opener\",  \"MatchType\": \"Any\",  \"FetchType\": \"All\",  \"Criteria\": [    {      \"Field\": \"AddedAnythingToCart\",      \"Comparer\": \"IsTrue\",      \"Times\": 2,      \"ProductCode\": \"123\",      \"LastXMinutes\": 4320,      \"WebsiteId\": \"12345678-1234-abdc-efgh-1231bc456efg789hij\"    },    {      \"Field\": \"OpenedAnyCampaign\",      \"Comparer\": \"IsTrue\",      \"DateFrom\": \"2019-09-01\",      \"DateTo\": \"2020-12-01\"    }  ]}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("segments/create.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/segments/SegmentID/update.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Name\"": \""Customer Tracking and Opener\"",
  \""MatchType\"": \""Any\"",
  \""FetchType\"": \""All\"",
  \""Criteria\"": [
    {
      \""Field\"": \""AddedAnythingToCart\"",
      \""Comparer\"": \""IsTrue\"",
      \""Times\"": 2,
      \""ProductCode\"": \""123\"",
      \""LastXMinutes\"": 4320,
      \""WebsiteId\"": \""12345678-1234-abdc-efgh-1231bc456efg789hij\""
    },
    {
      \""Field\"": \""OpenedAnyCampaign\"",
      \""Comparer\"": \""IsTrue\"",
      \""DateFrom\"": \""2019-09-01\"",
      \""DateTo\"": \""2020-12-01\""
    }
  ]
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Name": "Customer Tracking and Opener",
  "MatchType": "Any",
  "FetchType": "All",
  "Criteria": [
    {
      "Field": "AddedAnythingToCart",
      "Comparer": "IsTrue",
      "Times": 2,
      "ProductCode": "123",
      "LastXMinutes": 4320,
      "WebsiteId": "12345678-1234-abdc-efgh-1231bc456efg789hij"
    },
    {
      "Field": "OpenedAnyCampaign",
      "Comparer": "IsTrue",
      "DateFrom": "2019-09-01",
      "DateTo": "2020-12-01"
    }
  ]
}')
response = client.post( path : "/segments/create.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/segments/SegmentID/update.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Name\": \"Customer Tracking and Opener\",\n  \"MatchType\": \"Any\",\n  \"FetchType\": \"All\",\n  \"Criteria\": [\n    {\n      \"Field\": \"AddedAnythingToCart\",\n      \"Comparer\": \"IsTrue\",\n      \"Times\": 2,\n      \"ProductCode\": \"123\",\n      \"LastXMinutes\": 4320,\n      \"WebsiteId\": \"12345678-1234-abdc-efgh-1231bc456efg789hij\"\n    },\n    {\n      \"Field\": \"OpenedAnyCampaign\",\n      \"Comparer\": \"IsTrue\",\n      \"DateFrom\": \"2019-09-01\",\n      \"DateTo\": \"2020-12-01\"\n    }\n  ]\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/segments/SegmentID/update.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Name\": \"Customer Tracking and Opener\",\n  \"MatchType\": \"Any\",\n  \"FetchType\": \"All\",\n  \"Criteria\": [\n    {\n      \"Field\": \"AddedAnythingToCart\",\n      \"Comparer\": \"IsTrue\",\n      \"Times\": 2,\n      \"ProductCode\": \"123\",\n      \"LastXMinutes\": 4320,\n      \"WebsiteId\": \"12345678-1234-abdc-efgh-1231bc456efg789hij\"\n    },\n    {\n      \"Field\": \"OpenedAnyCampaign\",\n      \"Comparer\": \"IsTrue\",\n      \"DateFrom\": \"2019-09-01\",\n      \"DateTo\": \"2020-12-01\"\n    }\n  ]\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}

Add criteria to a segment

Abstract

Describes the request and response details of this Moosend API endpoint to add criteria or rules to a specific segment.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list that contains the segment.

SegmentID

path

string

true

The ID of the segment.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Field

body

string

true

The criterion used to filter the email list. See Field values.

Comparer

body

string

false

The operator that defines how to compare a Field with its Value. See Comparer values.

Value

body

string

false

The search term used to filter the specified Field.

LastXMinutes

body

integer

false

Constrains the results by the time that has elapsed.

DateFrom to DateTo

body

date

false

Constrains the results by a date span.

DateFunction

body

string

false

The value used with custom fields of dateTime data type. See DateFunction values.

Field values

Select one of the following Field values to filter the email list:

  • DateAdded - filters subscribers by the date they were added to the email list.

  • DateUpdated - filters subscribers by the date they were last updated in the email list.

  • RecipientName - filters subscribers by name.

  • RecipientEmail - filters subscribers by their email address.

  • SubscribeMethod - filters subscribers by their subscription method.

  • CustomField - filters subscribers by the value of a custom field.

  • MailingList - filters subscribers by the email list they belong to.

  • CampaignsOpened - filters subscribers by the number of campaigns they have opened within the past 60 days.

  • LinksClicked - filters subscribers by the number of links they have clicked from the campaigns sent to them within the past 60 days.

  • CampaignName - filters subscribers by the name of the campaign they have opened.

  • LinkURL - filters subscribers by the URL of the link they have clicked.

  • CampaignSent - filters subscribers by the campaign they have received or not received.

  • Platform - filters subscribers by the platform they use.

  • OperatingSystems - filters subscribers by the operating system they use.

  • EmailClient - filters subscribers by the email client they use.

  • WebBrowser - filters subscribers by the web browser they use.

  • MobileBrowser - filters subscribers by the mobile browser they use.

  • AddedAnythingToCart - filters subscribers by their cart history in a tracked website.

  • ViewedProduct - filters subscribers by their browsing history in a tracked website.

  • PurchasedProduct - filters subscribers by their purchase history in a tracked website.

Comparer values

Select one of the following Comparer operators to compare a criterion field with its value:

  • Is - finds subscribers where the Field is exactly equal to the specified Value.

  • IsNot - finds subscribers where the Field is not equal to the specified Value

  • Contains - finds subscribers where the Field contains the specified Value.

  • DoesNotContain - finds subscribers where the Field does not contain the specified Value.

  • StartsWith - finds subscribers where the Field starts with the specified Value.

  • DoesNotStartWith - finds subscribers where the Field does not start with the specified Value.

  • EndsWith - finds subscribers where the Field ends with the specified Value.

  • DoesNotEndWith - finds subscribers where the Field does not end with the specified Value.

  • IsGreaterThan - finds subscribers where the Field is greater than the specified Value.

  • IsGreaterThanOrEqualTo - finds subscribers where the Field is greater than or equal to the specified Value.

  • IsLessThan - finds subscribers where the Field is less than the specified Value.

  • IsLessThanOrEqualTo - finds subscribers where the Field is less than or equal to the specified Value.

  • IsBefore - finds subscribers where the Field is before the specified Value.

  • IsAfter - finds subscribers where the Field is after the specified Value.

  • IsEmpty - finds subscribers where the Field has no Value.

  • IsNotEmpty - finds subscribers where the Field contains a Value.

  • IsTrue - finds subscribers where the condition defined by the Field is true.

  • IsFalse - finds subscribers where the condition defined by the Field is false.

DateFunction values

Select one of the following to use with fields of DateTime data type.

  • Year - the four-digit year part of the date.

  • Month - the month part of the date from 1 to 12.

  • Day - the day part of the date from 1 to 31.

  • WeekDay - the day of the week from 1 to 7. For example, 1 for Sunday, 2 for Monday, and so on.

  • DaysPassed - the number of days that have passed until now.

  • HoursPassed - the number of hours that have passed until now.

  • MinutesPassed - the number of minutes that have passed until now.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - the ID of the new criteria added.

Request
POST https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/add.{Format}?apikey=

Request body:
{
  "Field": "DateAdded",
  "DateFunction": "Year",
  "Comparer": "Is",
  "Value": "2020"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Field\":\"DateAdded\",
    \"DateFunction\": \"Year\",
    \"Comparer\":\"Is\",\"Value\":\"2020\"
}" \
'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/add.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Field\": \"DateAdded\",  \"DateFunction\": \"Year\",  \"Comparer\": \"Is\",  \"Value\": \"2020\"}");
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/add.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/add.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Field': 'DateAdded',
  'DateFunction': 'Year',
  'Comparer': 'Is',
  'Value': '2020'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/add.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Field\": \"DateAdded\",  \"DateFunction\": \"Year\",  \"Comparer\": \"Is\",  \"Value\": \"2020\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Field": "DateAdded",  "DateFunction": "Year",  "Comparer": "Is",  "Value": "2020"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/add.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Field": "DateAdded",
    "DateFunction": "Year",
    "Comparer": "Is",
    "Value": "2020"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/add.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/add.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Field\": \"DateAdded\",
  \"DateFunction\": \"Year\",
  \"Comparer\": \"Is\",
  \"Value\": \"2020\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Field": "DateAdded",
  "DateFunction": "Year",
  "Comparer": "Is",
  "Value": "2020"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/add.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Field\": \"DateAdded\",\n  \"DateFunction\": \"Year\",\n  \"Comparer\": \"Is\",\n  \"Value\": \"2020\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/add.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Field\": \"DateAdded\",  \"DateFunction\": \"Year\",  \"Comparer\": \"Is\",  \"Value\": \"2020\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("segments/create.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/add.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Field\"": \""DateAdded\"",
  \""DateFunction\"": \""Year\"",
  \""Comparer\"": \""Is\"",
  \""Value\"": \""2020\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Field": "DateAdded",
  "DateFunction": "Year",
  "Comparer": "Is",
  "Value": "2020"
}')
response = client.post( path : "/segments/create.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/add.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Field\": \"DateAdded\",\n  \"DateFunction\": \"Year\",\n  \"Comparer\": \"Is\",\n  \"Value\": \"2020\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/add.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Field\": \"DateAdded\",\n  \"DateFunction\": \"Year\",\n  \"Comparer\": \"Is\",\n  \"Value\": \"2020\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": 15783
}

Update segment criteria

Abstract

Describes the request and response details of this Moosend API endpoint to update the criteria or rules in a specific segment.

Request

Parameter

In

Type

Required

Description

Accept

header

string

true

Determines the expected format and data type to retrieve the response data.

Value: application/json

MailingListID

path

string

true

The ID of the email list that contains the segment.

SegmentID

path

string

true

The ID of the segment.

CriteriaID

path

number(double)

true

The ID of the criteria of a segment to be updated.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Field

body

string

true

The criterion used to filter the email list. See Field values.

Comparer

body

string

false

The operator that defines how to compare a Field with its Value. See Comparer values.

Value

body

string

false

The search term used to filter the specified Field.

LastXMinutes

body

integer

false

Constrains the results by the time that has elapsed.

DateFrom to DateTo

body

date

false

Constrains the results by a date span.

DateFunction

body

string

false

The value used with custom fields of dateTime data type. See DateFunction values.

Field values

Select one of the following Field values to filter the email list:

  • DateAdded - filters subscribers by the date they were added to the email list.

  • DateUpdated - filters subscribers by the date they were last updated in the email list.

  • RecipientName - filters subscribers by name.

  • RecipientEmail - filters subscribers by their email address.

  • SubscribeMethod - filters subscribers by their subscription method.

  • CustomField - filters subscribers by the value of a custom field.

  • MailingList - filters subscribers by the email list they belong to.

  • CampaignsOpened - filters subscribers by the number of campaigns they have opened within the past 60 days.

  • LinksClicked - filters subscribers by the number of links they have clicked from the campaigns sent to them within the past 60 days.

  • CampaignName - filters subscribers by the name of the campaign they have opened.

  • LinkURL - filters subscribers by the URL of the link they have clicked.

  • CampaignSent - filters subscribers by the campaign they have received or not received.

  • Platform - filters subscribers by the platform they use.

  • OperatingSystems - filters subscribers by the operating system they use.

  • EmailClient - filters subscribers by the email client they use.

  • WebBrowser - filters subscribers by the web browser they use.

  • MobileBrowser - filters subscribers by the mobile browser they use.

  • AddedAnythingToCart - filters subscribers by their cart history in a tracked website.

  • ViewedProduct - filters subscribers by their browsing history in a tracked website.

  • PurchasedProduct - filters subscribers by their purchase history in a tracked website.

Comparer values

Select one of the following Comparer operators to compare a criterion field with its value:

  • Is - finds subscribers where the Field is exactly equal to the specified Value.

  • IsNot - finds subscribers where the Field is not equal to the specified Value

  • Contains - finds subscribers where the Field contains the specified Value.

  • DoesNotContain - finds subscribers where the Field does not contain the specified Value.

  • StartsWith - finds subscribers where the Field starts with the specified Value.

  • DoesNotStartWith - finds subscribers where the Field does not start with the specified Value.

  • EndsWith - finds subscribers where the Field ends with the specified Value.

  • DoesNotEndWith - finds subscribers where the Field does not end with the specified Value.

  • IsGreaterThan - finds subscribers where the Field is greater than the specified Value.

  • IsGreaterThanOrEqualTo - finds subscribers where the Field is greater than or equal to the specified Value.

  • IsLessThan - finds subscribers where the Field is less than the specified Value.

  • IsLessThanOrEqualTo - finds subscribers where the Field is less than or equal to the specified Value.

  • IsBefore - finds subscribers where the Field is before the specified Value.

  • IsAfter - finds subscribers where the Field is after the specified Value.

  • IsEmpty - finds subscribers where the Field has no Value.

  • IsNotEmpty - finds subscribers where the Field contains a Value.

  • IsTrue - finds subscribers where the condition defined by the Field is true.

  • IsFalse - finds subscribers where the condition defined by the Field is false.

DateFunction values

Select one of the following to use with fields of DateTime data type.

  • Year - the four-digit year part of the date.

  • Month - the month part of the date from 1 to 12.

  • Day - the day part of the date from 1 to 31.

  • WeekDay - the day of the week from 1 to 7. For example, 1 for Sunday, 2 for Monday, and so on.

  • DaysPassed - the number of days that have passed until now.

  • HoursPassed - the number of hours that have passed until now.

  • MinutesPassed - the number of minutes that have passed until now.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - the ID of the updated segment.

Request
POST https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/{CriteriaID}/update.{Format}?apikey=

Request body:
{
  "Field": "LinkURL",
  "Comparer": "is",
  "Value": "https://www.yourpage.com/"
}
Request
curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --header "Accept: application/json" \
     --data-binary "{
    \"Field\":\"LinkURL\",
    \"Comparer\":\"is\",
    \"Value\":\"https://www.yourpage.com/\"
}" \
'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/{CriteriaID}/update.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{  \"Field\": \"LinkURL\",  \"Comparer\": \"is\",  \"Value\": \"https://www.yourpage.com/\"}");
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/{CriteriaID}/update.{Format}?apikey=")
  .request(MediaType.APPLICATION_JSON_TYPE)
  .header("Accept", "application/json")
  .post(payload);

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('POST', 'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/{CriteriaID}/update.{Format}?apikey=');

request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

var body = {
  'Field': 'LinkURL',
  'Comparer': 'is',
  'Value': 'https://www.yourpage.com/'
};

request.send(JSON.stringify(body));
Request
var request = require('request');

request({
  method: 'POST',
  url: 'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/{CriteriaID}/update.{Format}?apikey=',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: "{  \"Field\": \"LinkURL\",  \"Comparer\": \"is\",  \"Value\": \"https://www.yourpage.com/\"}"
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;
my $data = '{  "Field": "LinkURL",  "Comparer": "is",  "Value": "https://www.yourpage.com/"}';

$ua->default_header("Content-Type" => "application/json");
$ua->default_header("Accept" => "application/json");

my $response = $ua->post("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/{CriteriaID}/update.{Format}?apikey=", Content => $data);

print $response->as_string;
Request
from urllib2 import Request, urlopen

values = """
  {
    "Field": "LinkURL",
    "Comparer": "is",
    "Value": "https://www.yourpage.com/"
  }
"""

headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}
request = Request('https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/{CriteriaID}/update.{Format}?apikey=', data=values, headers=headers)

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/{CriteriaID}/update.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"Field\": \"LinkURL\",
  \"Comparer\": \"is\",
  \"Value\": \"https://www.yourpage.com/\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

values = '{
  "Field": "LinkURL",
  "Comparer": "is",
  "Value": "https://www.yourpage.com/"
}'

headers = {
  :content_type => 'application/json',
  :accept => 'application/json'
}

response = RestClient.post 'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/{CriteriaID}/update.{Format}?apikey=', values, headers
puts response
Request
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	body := []byte("{\n  \"Field\": \"LinkURL\",\n  \"Comparer\": \"is\",\n  \"Value\": \"https://www.yourpage.com/\"\n}")

	req, _ := http.NewRequest("POST", "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/{CriteriaID}/update.{Format}?apikey=", bytes.NewBuffer(body))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  
  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
  
    using (var content = new StringContent("{  \"Field\": \"LinkURL\",  \"Comparer\": \"is\",  \"Value\": \"https://www.yourpage.com/\"}", System.Text.Encoding.Default, "application/json"))
    {
      using (var response = await httpClient.PostAsync("segments/create.{Format}{?apikey}", content))
      {
        string responseData = await response.Content.ReadAsStringAsync();
      }
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/{CriteriaID}/update.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "POST"

request.ContentType = "application/json"
request.Accept = "application/json"

Using writer = New System.IO.StreamWriter(request.GetRequestStream())
  Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes("{
  \""Field\"": \""LinkURL\"",
  \""Comparer\"": \""is\"",
  \""Value\"": \""https://www.yourpage.com/\""
}")
  request.ContentLength = byteArray.Length
  writer.Write(byteArray)
  writer.Close()
End Using
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

def emptyHeaders = [:]
emptyHeaders."Content-Type" = "application/json"
emptyHeaders."Accept" = "application/json"

def jsonObj = new JsonSlurper().parseText('{
  "Field": "LinkURL",
  "Comparer": "is",
  "Value": "https://www.yourpage.com/"
}')
response = client.post( path : "/segments/create.{Format}{?apikey}",
                        body : jsonObj,
                        headers: emptyHeaders,
                        contentType : JSON )

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/{CriteriaID}/update.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPBody:[@"{\n  \"Field\": \"LinkURL\",\n  \"Comparer\": \"is\",\n  \"Value\": \"https://www.yourpage.com/\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/criteria/{CriteriaID}/update.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = """
"{\n  \"Field\": \"LinkURL\",\n  \"Comparer\": \"is\",\n  \"Value\": \"https://www.yourpage.com/\"\n}"
""".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": 15783
}

Delete a segment

Abstract

Describes the request and response details of this Moosend API endpoint to delete a segment in a mailing list.

Request

Parameter

In

Type

Required

Description

MailingListID

path

string

true

The ID of the email list that contains the segment.

SegmentID

path

string

true

The ID of the segment to be deleted.

Format

path

string

true

The supported file format for getting a response.

Possible values: json and xml.

apikey

query

string

true

The API key of your account.

Response

Status

Description

Headers

Schema

200 OK

The request is successful.

Content-Type:application/json

Accept:application/json

N/A

  • Code - the response code. This is 0 if successful.

  • Error - the response error message. This is null if successful.

  • Context - the response context. This is null if successful.

Request
DELETE https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/delete.{Format}?apikey=
Request
curl --include \
     --request DELETE \
'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/delete.{Format}?apikey='
Request
// Maven : Add these dependencies to your pom.xml (java6+)
// <dependency>
//     <groupId>org.glassfish.jersey.core</groupId>
//     <artifactId>jersey-client</artifactId>
//     <version>2.8</version>
// </dependency>
// <dependency>
//     <groupId>org.glassfish.jersey.media</groupId>
//     <artifactId>jersey-media-json-jackson</artifactId>
//     <version>2.8</version>
// </dependency>

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;

Client client = ClientBuilder.newClient();
Response response = client.target("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/delete.{Format}?apikey=")
  .request(MediaType.TEXT_PLAIN_TYPE)
  .delete();

System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
Request
var request = new XMLHttpRequest();

request.open('DELETE', 'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/delete.{Format}?apikey=');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};

request.send();
Request
var request = require('request');

request({
  method: 'DELETE',
  url: 'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/delete.{Format}?apikey=',
}, function (error, response, body) {
  console.log('Status:', response.statusCode);
  console.log('Headers:', JSON.stringify(response.headers));
  console.log('Response:', body);
});
Request
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
use LWP::UserAgent;
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);

my $ua   = LWP::UserAgent->new;

my $response = $ua->delete("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/delete.{Format}?apikey=");

print $response->as_string;
Request
from urllib2 import Request, urlopen

request = Request('https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/delete.{Format}?apikey=')
request.get_method = lambda: 'DELETE'

response_body = urlopen(request).read()
print response_body
Request
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/delete.{Format}?apikey=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

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

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
Request
require 'rubygems' if RUBY_VERSION < '1.9'
require 'rest_client'

response = RestClient.delete 'https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/delete.{Format}?apikey='
puts response
Request
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := &http.Client{}

	req, _ := http.NewRequest("DELETE", "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/delete.{Format}?apikey=", nil)

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Errored when sending request to the server")
		return
	}

	defer resp.Body.Close()
	resp_body, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(resp.Status)
	fmt.Println(string(resp_body))
}
Request
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://{hostname}/v3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  using(var response = await httpClient.DeleteAsync("segments/create.{Format}{?apikey}"))
  {
 
        string responseData = await response.Content.ReadAsStringAsync();
  }
}
Request
Dim request = TryCast(System.Net.WebRequest.Create("https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/delete.{Format}?apikey="), System.Net.HttpWebRequest)

request.Method = "DELETE"

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
  Using reader = New System.IO.StreamReader(response.GetResponseStream())
    responseContent = reader.ReadToEnd()
  End Using
End Using
Request
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.5.0')
def client = new RESTClient("https://{hostname}/v3")

response = client.delete( path : "/segments/create.{Format}{?apikey}")

println("Status:" + response.status)

if (response.data) {
  println("Content Type: " + response.contentType)
  println("Body:\n" + JsonOutput.prettyPrint(JsonOutput.toJson(response.data)))
}
Request
NSURL *URL = [NSURL URLWithString:@"https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/delete.{Format}?apikey="];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"DELETE"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);
                              }];
[task resume];
Request
import Foundation

// NOTE: Uncommment following two lines for use in a Playground
// import PlaygroundSupport
// PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://{hostname}/v3/lists/{MailingListID}/segments/{SegmentID}/delete.{Format}?apikey=")!
var request = URLRequest(url: url)
request.httpMethod = "DELETE"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  if let response = response {
    print(response)

    if let data = data, let body = String(data: data, encoding: .utf8) {
      print(body)
    }
  } else {
    print(error ?? "Unknown error")
  }
}

task.resume()
Response
json
{
  "Code": 0,
  "Error": null,
  "Context": null
}