Advertisement
Guest User

Requests example for ActiveCampaign API

a guest
Nov 26th, 2014
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. import requests
  2.  
  3. def format_url_keys(name, items):
  4.     return ['{name}[{x}]'.format(name=name, x=x) for x in items]
  5.  
  6. def get_formatted_fields(name, keys, values=None):
  7.     values = values is not None and values or keys
  8.     return dict(zip(format_url_keys(name, keys), values))
  9.  
  10.  
  11. api_url = "http://mailer.blah.com.au/admin/api.php"
  12. api_key = "..."
  13.  
  14. # define the request paramaters for a 'subscriber_view' call
  15. # the 'id' is an email
  16. view_params = {'api_key': api_key, 'api_action': 'subscriber_view',
  17.                       'api_output': 'json', 'id': user.email}
  18.  
  19. # do our GET call to the API
  20. r = requests.get(api_url, params=view_params)
  21. # get the returned JSON as dict
  22. subscriber = r.json()
  23.  
  24. # if the subscriber dict doesn't have 'lists' then it is not subscribed to anything
  25. if not 'lists' in subscriber:
  26.                     add_params = {'api_key': api_key, 'api_action': 'subscriber_add',
  27.                       'api_output': 'json'}
  28.                     # the payload should be the subscriber details and any lists
  29.                     add_payload = {'email': user.email,
  30.                                     'first_name': user.firstName,
  31.                                     'last_name': user.lastName}
  32.                     # this bit is confusing, AC has a very weird way of handling listids and status
  33.                     # listids is just a list of ids as strings and yep both p and status are required
  34.                     add_payload.update(get_formatted_fields('p', listids, listids))
  35.                     add_payload.update(get_formatted_fields('status', listids, [1] * len(listids)))
  36.  
  37.                     # finally do the call
  38.                     r = requests.post(api_url, params=add_params, data=add_payload)
  39.                     result = r.json()
  40.                     # any logging or result verification etc.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement