Skip to content

Instantly share code, notes, and snippets.

@billyoverton
Last active December 29, 2015 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save billyoverton/7673241 to your computer and use it in GitHub Desktop.
Save billyoverton/7673241 to your computer and use it in GitHub Desktop.
Playing around with the pager duty REST api.
import http.client
import base64
import json
import urllib
class api:
"""Provides a wrapper to the PagerDuty Notification system's REST API
Details of the API can be found at
http://developer.pagerduty.com/documentation/rest/incidents/count
"""
authorization = None
api_host = None
api_base = None
def __init__(self, subdomain, token=None, username=None, password=None):
self.api_host = '%s.pagerduty.com' % subdomain
self.api_base = '/api/v1'
# Sets the authentication method. Preferences Token auth over Basic
if token is not None:
self.authorization = "Token token=%s" % token
elif username is not None and password is not None:
userpair = '%s:%s' % (username, password)
self.authorization = "Basic %s" % base64.encodebytes(userpair.encode()).decode().replace('\n','')
else:
raise ValueError("A complete authentication method must be provided. Either Token or Basic")
def incidents_count(self, paramaters=None):
"""Returns the current number of incidents
Defaults to all incidents within the last 30 days. Optional paramaters
can be provided per PagerDutie's API documentation:
http://developer.pagerduty.com/documentation/rest/incidents/count
"""
url = self.api_base + '/incidents/count'
return self.__get(url, paramaters)['total']
def incidents(self, paramaters=None):
"""Returns incidents.
Defaults to all incidents within the last 30 days. Optional paramaters
can be provided per PagerDutie's API documentaiton
http://developer.pagerduty.com/documentation/rest/incidents/list
"""
url = self.api_base + '/incidents'
return self.__get(url, paramaters)
def incident(self, id):
"""Returns incident identifed by id"""
url = self.api_base + '/incidents/' + str(id)
return self.__get(url)
def __get(self, url, paramaters=None):
header = {'Content-type':'application/json',
'Authorization': self.authorization}
# If we received paramaters to send, encode them for the data portion below
if paramaters is not None:
url = url + '?' + urllib.parse.urlencode(paramaters)
conn = http.client.HTTPSConnection(self.api_host)
conn.request("GET", url, headers=header)
response = conn.getresponse()
status = response.status
data = response.read()
conn.close()
return json.loads(data.decode('utf-8'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment