How to add contacts using API

One of the most requested uses cases is "how can I create contacts in my MoonMail account programmatically?" This is very easy to do with MoonMail GraphQL API.

In this guide we will create a dynamic segment that will include all contacts that have attribute Type equal to Customer, but you can choose any attribute that you want.

1. Creating a dynamic segment for your contacts.

If you don't know how to do a mutation, please check GraphQL API section first.

mutation {
createSegment(
input: {
Name: "My customers"
Dimensions: {
Attributes: {Key: "Type", AttributeType: INCLUSIVE, Values: "Customer"}
}
}
) {
Dimensions {
Attributes {
Key
Values
AttributeType
}
}
Id
Name
}
}

In this mutation we create a segment with name "My customers" and specify Dimensions to include all contacts that have attribute Type equal to Customer.

2. Adding your contacts to the created segment.

To add contacts to this segment you need to specify attribute Type with value Customer. You can also provide additional attributes and metrics when you add new contacts. Contacts can be included in multiple dynamic segments at once based on different attribute filters.

mutation PutContacts($input: PutContactsInput!) {
putContacts(input: $input) {
Address
Attributes {
Key
Value
}
CreationDate
Id
Metrics {
Key
Value
}
UserAttributes {
Key
Value
}
}
}

Provide the following GraphQL variables:

{
"input": {
"Contacts": [
{
"Address": "contact1@example.com",
"Attributes": [{"Key": "Type", "Value": "Customer"}],
"UserAttributes": [{"Key": "Name", "Value": "Customer 1"}]
},
{
"Address": "contact2@example.com",
"Attributes": [{"Key": "Type", "Value": "Customer"}],
"UserAttributes": [{"Key": "Name", "Value": "Customer 2"}]
},
{
"Address": "contact3@example.com",
"Attributes": [{"Key": "Type", "Value": "Customer"}],
"UserAttributes": [{"Key": "Name", "Value": "Customer 3"}]
}
]
}
}
note

You can use MoonMail JS SDK or Client API to add new contacts from your website or application.

Now you can use your new segment to send a campaign to those contacts.