Skip to content

Commit

Permalink
Merge pull request #123 from thinkingserious/api_v3_client
Browse files Browse the repository at this point in the history
Api v3 client - ASM Groups endpoint
  • Loading branch information
thinkingserious committed Sep 24, 2015
2 parents 5496688 + 4d018fc commit ceb2763
Show file tree
Hide file tree
Showing 10 changed files with 215 additions and 61 deletions.
48 changes: 43 additions & 5 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,44 @@ add_content_id
message.add_attachment('image.png', open('./image.png', 'rb'))
message.add_content_id('image.png', 'ID_IN_HTML')
message.set_html('<html><body>TEXT BEFORE IMAGE<img src="cid:ID_IN_HTML"></img>AFTER IMAGE</body></html>')
WEB API v3
----------

`APIKeys`_
~~~~~~~~~~

List all API Keys belonging to the authenticated user.

.. code:: python
client = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
status, msg = client.apikeys.get()
`Advanced Suppression Manager (ASM)`_
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Advanced Suppression Manager gives your recipients more control over the types of emails they want to receive by letting them opt out of messages from a certain type of email.

More information_.

.. _information: https://sendgrid.com/docs/API_Reference/Web_API_v3/Advanced_Suppression_Manager/index.html

ASM Groups
~~~~~~~~~~

Retrieve all suppression groups associated with the user.

.. code:: python
client = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
status, msg = client.asm_groups.get()
Get a single record.

.. code:: python
status, msg = client.asm_groups.get(record_id)
SendGrid's `X-SMTPAPI`_
-----------------------
Expand Down Expand Up @@ -402,16 +440,16 @@ Tests
pyenv install 2.6.9
pyenv install 2.7.8
pyenv install 3.2.6
pyenv local 3.2.6 2.7.8 2.6.9
pyenv rehash
virtualenv venv
source venv/bin/activate #or . ./activate.sh
python setup.py install
**Run the tests:**

.. code:: python
virtualenv venv
source venv/bin/activate #or . ./activate.sh
python setup.py install
pyenv local 3.2.6 2.7.8 2.6.9
pyenv rehash
tox
Deploying
Expand Down
7 changes: 6 additions & 1 deletion example_v3_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@

client = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))

status, msg = client.asm_groups.get([66,67,50])
print status
print msg

"""
name = "My Amazing API Key"
status, msg = client.apikeys.post(name)
msg = json.loads(msg)
Expand All @@ -29,7 +35,6 @@
print status
print msg
"""
# Get a list of all valid API Keys from your account
status, msg = client.apikeys.get()
print status
Expand Down
4 changes: 3 additions & 1 deletion sendgrid/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from .exceptions import SendGridClientError, SendGridServerError
from .resources.apikeys import APIKeys
from .resources.asm_groups import ASMGroups

class SendGridAPIClient(object):

Expand All @@ -32,6 +33,7 @@ def __init__(self, apikey, **opts):
self.proxies = opts.get('proxies', None)

self.apikeys = APIKeys(self)
self.asm_groups = ASMGroups(self)

@property
def apikey(self):
Expand Down Expand Up @@ -70,7 +72,7 @@ def _build_request(self, url, json_header=False, method='GET', data=None):
return response.getcode(), body

def get(self, api):
url = self.host + api.base_endpoint
url = self.host + api.endpoint
response, body = self._build_request(url, False, 'GET')
return response, body

Expand Down
1 change: 0 additions & 1 deletion sendgrid/resources/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@

56 changes: 56 additions & 0 deletions sendgrid/resources/asm_groups.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
class ASMGroups(object):
"""Advanced Suppression Manager gives your recipients more control over the types of emails they want to receive
by letting them opt out of messages from a certain type of email.
Groups are specific types of email you would like your recipients to be able to unsubscribe from or subscribe to.
For example: Daily Newsletters, Invoices, System Alerts.
"""

def __init__(self, client, **opts):
"""
Constructs SendGrid ASM object.
See https://sendgrid.com/docs/API_Reference/Web_API_v3/Advanced_Suppression_Manager/index.html and
https://sendgrid.com/docs/API_Reference/Web_API_v3/Advanced_Suppression_Manager/groups.html
"""
self._name = None
self._base_endpoint = "/v3/asm/groups"
self._endpoint = "/v3/asm/groups"
self._client = client

@property
def base_endpoint(self):
return self._base_endpoint

@property
def endpoint(self):
endpoint = self._endpoint
return endpoint

@endpoint.setter
def endpoint(self, value):
self._endpoint = value

@property
def client(self):
return self._client

# Retrieve all suppression groups associated with the user.
def get(self, id=None):
if id == None:
return self.client.get(self)

if isinstance(id, int):
self._endpoint = self._base_endpoint + "/" + str(id)
return self.client.get(self)

if len(id) > 1:
count = 0
for i in id:
if count == 0:
self._endpoint = self._endpoint + "?id=" + str(i)
else:
self._endpoint = self._endpoint + "&id=" + str(i)
count = count + 1

return self.client.get(self)
1 change: 0 additions & 1 deletion test/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@

37 changes: 37 additions & 0 deletions test/base_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import sendgrid
from sendgrid.client import SendGridAPIClient
try:
import urllib.request as urllib_request
from urllib.parse import urlencode
from urllib.error import HTTPError
except ImportError: # Python 2
import urllib2 as urllib_request
from urllib2 import HTTPError
from urllib import urlencode

class BaseTest():
def __init__(self):
pass

class MockSendGridAPIClientRequest(SendGridAPIClient):
def __init__(self, apikey, **opts):
super(MockSendGridAPIClientRequest, self).__init__(apikey, **opts)
self._req = None

def _build_request(self, url=None, json_header=False, method='GET', data=None):
req = urllib_request.Request(url)
req.get_method = lambda: method
req.add_header('User-Agent', self.useragent)
req.add_header('Authorization', 'Bearer ' + self.apikey)
if json_header:
req.add_header('Content-Type', 'application/json')
body = data
if method == 'POST':
response = 201
if method == 'PATCH':
response = 200
if method == 'DELETE':
response = 204
if method == 'GET':
response = 200
return response, body
35 changes: 35 additions & 0 deletions test/test_api_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from .base_test import BaseTest, MockSendGridAPIClientRequest
import os
try:
import unittest2 as unittest
except ImportError:
import unittest
try:
from StringIO import StringIO
except ImportError: # Python 3
from io import StringIO

import sendgrid
from sendgrid.client import SendGridAPIClient
from sendgrid.version import __version__

SG_KEY = os.getenv('SG_KEY') or 'SENDGRID_APIKEY'

class TestSendGridAPIClient(unittest.TestCase):
def setUp(self):
self.client = MockSendGridAPIClientRequest
self.client = SendGridAPIClient(SG_KEY)

def test_apikey_init(self):
self.assertEqual(self.client.apikey, SG_KEY)

def test_useragent(self):
useragent = 'sendgrid/' + __version__ + ';python_v3'
self.assertEqual(self.client.useragent, useragent)

def test_host(self):
host = 'https://api.sendgrid.com'
self.assertEqual(self.client.host, host)

if __name__ == '__main__':
unittest.main()
53 changes: 1 addition & 52 deletions test/test_apikeys.py
Original file line number Diff line number Diff line change
@@ -1,71 +1,20 @@
from .base_test import BaseTest, MockSendGridAPIClientRequest
import os
try:
import unittest2 as unittest
except ImportError:
import unittest
import json
import sys
try:
from StringIO import StringIO
except ImportError: # Python 3
from io import StringIO
try:
import urllib.request as urllib_request
from urllib.parse import urlencode
from urllib.error import HTTPError
except ImportError: # Python 2
import urllib2 as urllib_request
from urllib2 import HTTPError
from urllib import urlencode

import sendgrid
from sendgrid import SendGridClient, Mail
from sendgrid.exceptions import SendGridClientError, SendGridServerError
from sendgrid.sendgrid import HTTPError
from sendgrid.client import SendGridAPIClient
from sendgrid.version import __version__

SG_KEY = os.getenv('SG_KEY') or 'SENDGRID_APIKEY'

class MockSendGridAPIClientRequest(SendGridAPIClient):
def __init__(self, apikey, **opts):
super(MockSendGridAPIClientRequest, self).__init__(apikey, **opts)
self._req = None

def _build_request(self, url=None, json_header=False, method='GET', data=None):
req = urllib_request.Request(url)
req.get_method = lambda: method
req.add_header('User-Agent', self.useragent)
req.add_header('Authorization', 'Bearer ' + self.apikey)
if json_header:
req.add_header('Content-Type', 'application/json')
body = data
if method == 'POST':
response = 201
if method == 'PATCH':
response = 200
if method == 'DELETE':
response = 204
if method == 'GET':
response = 200
return response, body

class TestSendGridAPIClient(unittest.TestCase):
def setUp(self):
self.client = MockSendGridAPIClientRequest
self.client = SendGridAPIClient(SG_KEY)

def test_apikey_init(self):
self.assertEqual(self.client.apikey, SG_KEY)

def test_useragent(self):
useragent = 'sendgrid/' + __version__ + ';python_v3'
self.assertEqual(self.client.useragent, useragent)

def test_host(self):
host = 'https://api.sendgrid.com'
self.assertEqual(self.client.host, host)

class TestAPIKeys(unittest.TestCase):
def setUp(self):
SendGridAPIClient = MockSendGridAPIClientRequest
Expand Down
34 changes: 34 additions & 0 deletions test/test_asm_groups.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from .base_test import BaseTest, MockSendGridAPIClientRequest
import os
try:
import unittest2 as unittest
except ImportError:
import unittest
try:
from StringIO import StringIO
except ImportError: # Python 3
from io import StringIO

import sendgrid
from sendgrid.client import SendGridAPIClient
from sendgrid.version import __version__

SG_KEY = os.getenv('SG_KEY') or 'SENDGRID_APIKEY'

class TestASMGroups(unittest.TestCase):
def setUp(self):
SendGridAPIClient = MockSendGridAPIClientRequest
self.client = SendGridAPIClient(SG_KEY)

def test_apikeys_init(self):
self.asm_groups = self.client.asm_groups
self.assertEqual(self.asm_groups.base_endpoint, "/v3/asm/groups")
self.assertEqual(self.asm_groups.endpoint, "/v3/asm/groups")
self.assertEqual(self.asm_groups.client, self.client)

def test_asm_groups_get(self):
status, msg = self.client.apikeys.get()
self.assertEqual(status, 200)

if __name__ == '__main__':
unittest.main()

0 comments on commit ceb2763

Please sign in to comment.