Examples using Python

In this tutorial, different examples will be shown on how to call the DMDS (Data-Mining and Delivery Services) REST API using Python code. Always keep in mind which method (GET, POST, DELETE, etc.) is being used for each call and how we make the calls, focusing on the URI part.

Returns contact information

In this example, we will explain how to return the groups, events, and fields of a specific contact. In the call, within the URL, you need to specify the email of the user that already exists in the API database. This way, all the information of a contact, such as their name, surname, etc., will be presented to us. Additionally, it will return the groups that the contact belongs to and all their events.

import requests
r = requests.get("https://api-dmds-host/v1/contacto/email",
headers={
         'Accept':'application/json',
         'Content-type': 'application/json',
         "Authorization":"xxxxxxx"
},
)
print(r.text)-

List invalid contacts

This part of the code will show us all the users that are invalid.

import requests
r = requests.get("https://api-dmds-host/v1/contactos/invalidos/",
headers={
         'Accept':'application/json',
         'Content-type': 'application/json',
         "Authorization":"xxxxxxxxxxxx"
},
)
print(r.text)-

Create or update a contact

With the following part of the code, you can create a new contact or update an existing one. The first variable defined is the email, which acts as a primary key in the database. When updating a contact, we will always rely on their email since it is unique. You can change the group a contact belongs to by adding another existing group name in the groups section. You can also change their name, surname, etc., for all the fields you want to modify.

import requests

import json
xdata ={
   "email":"xxxxxxx@xxxx",
   "grupos":"xxxx",
   "nombre":"xxxxx",
   "apellido":"xx",
   "sexo":"x",
   "edad":"xxx",
   "invalido":"0"
}
r = requests.post("https://api-dmds-host/v1/contacto/",
   headers={
           'Accept':'application/json',
           'Content-type': 'application/json',
           "Authorization":"xxxxxxx"
   },
   data= json.dumps( xdata )
)
if r.status_code==200:
 print(r.text)
print(r.status_code, r.reason)-

Invalidate a contact

In the same update of a contact, you can invalidate or validate a contact. By default, the invalid variable is always set to zero. But if a user wants to unsubscribe or be invalidated, setting this variable to one (invalid: 1) allows us to mark this contact as invalid.

import requests
import json
xdata ={
   "email":"xxxxx",
   "grupos":"xxxxx",
   "nombre":"xxxx",
   "apellido":"xx",
   "sexo":"x",
   "edad":"xxx",
   "invalido":"1"
}
r = requests.post("https://api-dmds-host/v1/contacto/",
   headers={
           'Accept':'application/json',
           'Content-type': 'application/json',
           "Authorization":"xxxxxxxxxxx"
   },
   data= json.dumps( xdata )
)
if r.status_code==200:
 print(r.text)
print(r.status_code, r.reason)

Send an email

To send an email, we will differentiate the types we want to send. First, there are two different calls for sending an email to a single recipient and another for sending to multiple recipients. For that, the change is very basic: replacing contact with contacts. Two other calls differ between sending HTML inline or via URI. Generic call

import requests
r = requests.post("https://api-dmds-host/v1/envio/enviar/",
  headers={'Accept':'application/json','Content-type': 'application/json',"Authorization":"xxxxxxxxx"},
  data ='{"campana_id":1234,"email":true,"contacto":{"email":"xxxxxxxxx","nombre":"xxxxx","apellido":"xxxxxx"}')
if r.status_code==200:
   print(r.text)
print(r.status_code, r.reason)

Send an email to a single recipient with HTML URI

To perform this send, some fields need to be defined, such as: the email field must always be true, as this allows us to send the email. If this value is false, messages cannot be sent. Other values to define are the campaign ID and the recipient email. Other values such as first name, last name, and subject are optional. If you want to send HTML via URI, this is added in the html_url field. Remember to set your authorization value in the headers section.

import requests
r = requests.post("https://api-dmds-host/v1/envio/send_one_uri/",
   headers={'Accept':'application/json','Content-type': 'application/json',"Authorization":"xxxxxxxxxxxxx"},
   data ='{"campana_id":1234,"email":true,"contacto":{"email":"xxx@xxx","nombre":"xxxx","apellido":"xxx"}, "html_url":"xxxxxxxxxxxxx"}')
if r.status_code==200:
     print(r.text)
print(r.status_code, r.reason)

Send an email to a single recipient with HTML inline

The difference from the previous call is in how you define the HTML within the code. There are two ways to send an email with HTML inline. One is to define the HTML code within the script:

import requests
import json
xdata ={
   "campana_id":111,
   "email": True,
   "asunto": "xxxxxxxx",
   "remitente": "xxxxxxxxx",
   "contacto":{
         "email":"xxxxxx",
         "nombre":"xxxxx",
         "apellido":"xxxxx"
   },
   "html": " <!DOCTYPE html><html><head><title>Page Title</title></head><body><h1>This is a Heading</h1><p>This is a paragraph.</p></body></html>"
}
r = requests.post("https://api-dmds-host/v1/envio/send_one_inline/",
   headers={
            'Accept':'application/json',
            'Content-type': 'application/json',
            "Authorization":"xxxxxxxx"
   },
   data= json.dumps( xdata )
)
if r.status_code==200:
   print(r.text)
print(r.status_code, r.reason)

Another way is this HTML code snippet, in a file.

import requests
import json
in_file = open("index.html", "rb") # opening for [r]eading as [b]inary
htmlfile = in_file.read()
in_file.close()
unicode_html_string = htmlfile.decode('utf-8')
xdata ={
    "campana_id":111,
    "email": True,
    "asunto": "Enviando HTML ",
    "remitente": "xxxx"xxx",
    "contacto":{
         "email":"xxx"xxxx",
         "nombre":"xxxx",
         "apellido":"xxxxx"
    },
    "html":"{}".format( unicode_html_string )
}
r = requests.post("https://api-dmds-host/v1/envio/send_one_inline/",
   headers={
           'Accept':'application/json',
           'Content-type': 'application/json',
           "Authorization":"xxxxxx"
   },
   data= json.dumps( xdata )
)
if r.status_code==200:
  print(r.text)
print(r.status_code, r.reason)

Send an email to a single recipient with raw HTML inline

Sending this type of message does not insert the tracking image (the one that allows you to know if the user opened/viewed an email), nor does it replace the URLs for click-tracking with DMDS URLs.

import requests
import json
in_file = open("index.html", "rb") # opening for [r]eading as [b]inary
htmlfile = in_file.read()
in_file.close()
unicode_html_string = htmlfile.decode('utf-8')
xdata ={
    "campana_id":111,
    "email": True,
    "asunto": "Enviando HTML ",
    "remitente": "xxxx"xxx",
    "contacto":{
         "email":"xxx"xxxx",
         "nombre":"xxxx",
         "apellido":"xxxxx"
    },
    "html":"{}".format( unicode_html_string )
}
r = requests.post("https://api-dmds-host/v1/envio/send_one_inline_raw/",
   headers={
           'Accept':'application/json',
           'Content-type': 'application/json',
           "Authorization":"xxxxxx"
   },
   data= json.dumps( xdata )
)
if r.status_code==200:
  print(r.text)
print(r.status_code, r.reason)

Send an email to a single recipient with inline XML

It allows sending an XML file. It follows the same structure as sending an HTML file; we just change the format from HTML to XML. An example of how to send an XML file is shown below:

import requests
import json
in_file = open("file.xml", "rb") # opening for [r]eading as [b]inary
xmlfile = in_file.read()
in_file.close()
unicode_xml_string = xmlfile.decode('utf-8')
xdata ={
    "campana_id":111,
    "email": True,
    "asunto": "Enviando XML",
    "remitente": "xxxxxx@xxxx",
    "contacto":{
              "email":"xxxx@xxx.com",
              "nombre":"xxxx",
              "apellido":"xxxxxx"
    },
    "xml": "{}".format( unicode_xml_string )
}
r = requests.post("https://api-dmds-host/v1/envio/send_one_inline_xml/",
   headers={
            'Accept':'application/json',
            'Content-type': 'application/json',
            "Authorization":"xxxxxxxxxxxxx"
   },
   data = json.dumps( xdata )
)
if r.status_code==200:
    print(r.text)
print(r.status_code, r.reason)

Send an email to more than one recipient with HTML URI

For this call, we will follow the same concept as the others when sending a message. In this case, we want to send to many recipients, so we will define an array of users to whom we want to send and change contact to contacts. In the example shown below, we send an email to two people, but many more can be defined.

import requests
r = requests.post("https://api-dmds-host/v1/envio/send_many_uri/",
   headers={'Accept':'application/json','Content-type': 'application/json',"Authorization":"xxxxxxxxxxx"},
   data ='{"campana_id":1234,"email":true,"contactos":[{"email":"usuario1@xxxxxx","nombre":"xxxxxx","apellido":"xxxxxx"},{"email":"usuari02@xxxxx","nombre":"xxxxxx","apellido":"xxxx"}], "html_url":"xxxxxxxxxxxxxxxxx"}')
if r.status_code==200:
   print(r.text)
print(r.status_code, r.reason)Enviar un correo a más de un destinatario con html inlineimport requests
r = requests.post("https://api-dmds-host/v1/envio/send_many_inline/",
   headers={'Accept':'application/json','Content-type': 'application/json',"Authorization":"xxxxxxx"},
   data ='{"campana_id":"xxxxxxxxxxxx","email":true,"contactos":[{"email":"usuario1@xxxxx","nombre":"xxxxx","apellido":"xxxxxx"},{"email":"usuario2@xxxxxx","nombre":"xxxx","apellido":"xxxxx"}], "html":"<html><head><title>Page Title</title></head><body><h1>This is a Heading</h1><p>This is a paragraph.</p></body></html>"}')
if r.status_code==200:
   print(r.text)
print(r.status_code, r.reason)

List global variables and their values

There are a series of global variables defined in the API. To see what these variables are and their values, we can refer to the following code.

import requests
r = requests.get("https://api-dmds-host/v1/global/",
   headers={
           'Accept':'application/json',
           'Content-type': 'application/json',
           "Authorization":"xxxxxxxx"
   },
)
if r.status_code==200:
     print(r.text)
print(r.status_code, r.reason)

Create global variables

We can always create global variables. For the creation, we will use the POST method, where we pass a variable that indicates the name of the global variable.

import requests
xdata ={
    "nombre": "xxxxxx",
    "valor": "xxxxxx"
}
r = requests.post("https://api-dmds-host/v1/global/",
  headers={
           'Accept':'application/json',
           'Content-type': 'application/json',
           "Authorization":"xxxxxxx"
  },
  data = "{"nombre": "lore ipsum", "valor":"hola"}"
)
if r.status_code==200:
    print(r.text)
print(r.status_code, r.reason)-

Delete global variables

In the same way that we create global variables, we can delete them. However, for this, we will use a method called ‘Delete’.

import requests
r = requests.delete("https://api-dmds-host/v1/global/",
   headers={'Accept':'application/json','Content-type': 'application/json',"Authorization":"xxxxxxxx"},
   data='{"nombre": "newglobal2", "valor": "xxxx"}')
if r.status_code==200:
   print(r.text)
print(r.status_code, r.reason)

List campaigns

With the same structure as listing invalid contacts or global variables, we can list all existing campaigns. For this, the GET method is used.

import requests
r = requests.get("https://api-dmds-host/v1/campania/",
   headers={
           'Accept':'application/json',
           'Content-type': 'application/json',
           "Authorization":"APIKEYxxxx"
   },
)
if r.status_code==200:
    print(r.text)
print(r.status_code, r.reason)-

Create a group

As we have seen before, when we create or modify a user, we can assign them to a group. To assign a group, we need to see if it exists. If it doesn’t, we can create it as follows.

import requests
r = requests.post("https://api-dmds-host/v1/grupo/",
headers={'Accept':'application/json','Content-type': 'application/json',"Authorization":"xxxxxxxxxxxxx"},
data='{"nombre":"xxxxx"}')
if r.status_code==200:
    print(r.text)
print(r.status_code, r.reason)-

List filters

In the API system, different filters can be created to help specify the sends. To see this list of existing filters, follow the code mentioned below.

import requests
r = requests.get("https://api-dmds-host/v1/filtros/",
   headers={
            'Accept':'application/json',
            'Content-type': 'application/json',
            "Authorization":"APIKEYxxxx"
   },
)
if r.status_code==200:
     print(r.text)
print(r.status_code, r.reason)

Revalidate contact list

In this example, a contact list is read from a text file and revalidated in case they were invalid.

import requests
import argparse
import sys
import json
import os

APIKEY=os.environ[ 'APIKEY' ]
DMDS=os.environ[ 'DMDS' ]

with open( "revalidar.txt", "r") as fd:
    while True:
        email = fd.readline().strip()
        if email == None or not email:
            break
        print( email )
        try:
            r = requests.get( f"https://api-dmds-{DMDS}.planisys.net/v1/revalidar/{email}",
                headers={
                    'Accept':'application/json',
                    'Content-type': 'application/json',
                    "Authorization":f"{APIKEY}"
                }
            )
        except Exception as e:
            print( f"ERROR: al enviar el request {str(e)}" )

Save EML file of a sent email

import argparse
import requests
import json
import sys
import os

dmds=os.environ['DMDS']
apikey=os.environ['APIKEY']

parser = argparse.ArgumentParser(usage='''retrieve eml for eeid and email''')
parser.add_argument('eeid', help='eeid')
parser.add_argument('email', help='email')
args = parser.parse_args()
eeid = args.eeid
email = args.email

try:
    response = requests.get( f"https://api-dmds-{dmds}.planisys.net/v1/eeid_eml/{eeid}/{email}",
        headers={
            'Accept':'application/json',
            'Content-type': 'application/json',
            "Authorization":apikey,
        }
)
except Exception as e:
    print( f"ERROR: {str(e)}" )

dict_resp = json.loads(response.content.decode())
eml = dict_resp['eml']
print(eml)