I needed a quick and simple script to monitor some of the API’s I manage. Since I already build in methods that fully test the webservice and backend database, I just had to wrap a single call and check the results from this method. Also I don’t want to rely on my servers being able to send mail, so I added support for AWS SES.
And the code…
#!/usr/bin/env python
import os
import sys
import time
import random
import string
import json
import hashlib
import socket
import urllib
import urllib2
from operator import itemgetter
from pprint import pprint
import StringIO
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import boto
from boto.ses import SESConnection
## config
AWS_ACCESS_KEY = 'XXX'
AWS_SECRET_KEY = 'XXX'
TO_ADDRESS = 'XXX@example.com'
FROM_ADDRESS = 'XXX@example.com'
API_ENDPOINT = 'http://example.com/api/system/health'
def send_alert(subject, body):
## ses connect
try:
ses = SESConnection(AWS_ACCESS_KEY, AWS_SECRET_KEY)
result = ses.send_email(FROM_ADDRESS, subject, body, TO_ADDRESS)
return True
except:
return False
def test_api():
subject = 'ALERT: api outage'
try:
url = API_ENDPOINT
headers = {}
params = {}
url = url + '?' + urllib.urlencode(params)
req = urllib2.Request(url, None, headers)
response = json.load(urllib2.urlopen(req))
if response['meta']['status'] != 'OK':
send_alert(subject, 'api not OK')
except:
send_alert(subject, 'api call failed')
return True
def main():
test_api()
if __name__ == '__main__':
sys.exit(main())