Opsgenie Python API v2

The Opsgenie SDK for Python provides a set of Python API functionalities regarding Opsgenie services, making it easier for Python developers to build applications that integrate with Opsgenie. Developers can build Python applications on top of APIs that take the complexity out of coding directly against a web service interface. The library provides APIs that hide much of the lower-level plumbing, including authentication, request retries, and error handling.

Before you begin, you must sign up for Opsgenie service, create an API Integration and get your API key. In order to use the Opsgenie Python SDK, you will need the API key from the API Integration you created. The API key is used to authenticate requests to the service and identify yourself as the sender of a request.

Python SDK Installation

Opsgenie's Python SDK can be installed using the pip command in the terminal as below:

pip install opsgenie-sdk

Client Initialization

You may initialize your Opsgenie client by importing the Opsgenie main API opsgenie_sdk and setting the appropriate configurations. Primarily configure your API key to begin using the SDK by entering your API key into the SDK configurations as an api_key parameter. Additional configurations can also be made and the list of configurations available can be found here.

After you set your Opsgenie configurations, you may pass it into your Opsgenie API client upon its initialization.

# Importing relevant Opsgenie SDK libraries
import opsgenie_sdk

class Example:
    def __init__(self, opsgenie_api_key):
        self.conf = opsgenie_sdk.configuration.Configuration()
        self.conf.api_key['Authorization'] = '<Your-API-Key>'

        self.api_client = opsgenie_sdk.api_client.ApiClient(configuration=self.conf)
        self.alert_api = opsgenie_sdk.AlertApi(api_client=self.api_client)

SDK Core Capabilities

Metrics Publishing Support

Opsgenie's Python SDK has capabilities to publish 3 metrics which include the following:

  • API
  • HTTP
  • SDK
    All of these metrics can be accessed by importing Observer from opsgenie_sdk.metrics.observer.
    Moreover, each of these metrics applies to every response cycle and you may choose to subscribe to any or all of these metrics. Subscribing to metrics involves first creating the MetricsObserver class and then subscribing to the relevant metrics as shown in the example code block below.
from examples import heartbeat
from opsgenie_client.metrics.observer import Observer


class MetricObserver(Observer):
    def notify(self, publisher):
        print("{}: '{}' has now metric data = {}".format(type(self).__name__, publisher.name, publisher.data))


if __name__ == '__main__':
    heartbeat = heartbeat.HeartBeat()
    metric_observer = MetricObserver()

    api_metric_publisher = heartbeat.api_client.api_metric_publisher
    api_metric_publisher.subscribe(metric_observer)

    http_metric_publisher = heartbeat.api_client.http_metric_publisher
    http_metric_publisher.subscribe(metric_observer)

    sdk_metric_publisher = heartbeat.api_client.sdk_metric_publisher
    sdk_metric_publisher.subscribe(metric_observer)

    heartbeat.ping()

As it can be seen in the above example, user's subscriber MetricObserver must extend our abstract base class Observer. This would force the subscriber to implement the abstract function notify. Now, whenever metrics are published, this function notify will be called by the corresponding metrics' publishers.

In order to subscribe to any of the metrics, you have to first access the corresponding metric's publisher. All three of the metrics' publishers can be found as properties of the ApiClient. Once you have access to the appropriate metric's publisher, then you can simply call its subscribe method, while passing in your observer as a parameter to be able to subscribe to that metric.

After this, whenever there is a new metric available, the notify function of your observer will be triggered. Inside of your notify function, you can access the name of the publisher in its name property and metric data in the data property.

You might choose to either use the same subscriber for all three of the metrics or different ones. You might also choose to have multiple subscribers subscribe to any one of the metrics.

Once subscribed, the following metrics will be published:
###Common Metrics:

NameTypeExplanation
transactionIdUUID4A random id generated at the start of each request and shared by all 3 of the metrics. This can, for example, be used to link different metrics in different observers to a single request-response cycle
durationDateTimeThe total duration taken to process the corresponding request
resourcePathStringThe end-point to which a request is made

API Metrics:

NameTypeExplanation
resultMetadataNamedTupleContains the following data:
- RequestId: Corresponds to Opsgenie API generated requestId
- ResponseTime: Corresponds to Opsgenie API generated took
- RateLimitState: Corresponds to Opsgenie API generated X-RateLimit-State
- RateLimitReason: Corresponds to Opsgenie API generated X-RateLimit-Reason
- RateLimitPeriod: Corresponds to Opsgenie API generated X-RateLimit-Period-In-Sec
- RetryCount: The number of retry request attempts made so far for each sdk call

More info about these fields can be found at:
https://docs.opsgenie.com/docs/api-rate-limiting and https://docs.opsgenie.com/docs/response
httpResponseStringThe body of the response of the API request made

HTTP Metrics:

NameTypeExplanation
retryCountIntThe number of times the request has been retried.
errorStringIf error occurs, error message, else none
statusStringStatus message of the executed request
statusCodeHTTPResponseHTTP Response code of request
requestDictThe request which was sent to the Opsgenie's API

SDK Metrics:

NameTypeExplanation
errorTypeStringThe type of the error to give a general indication about what might have gone wrong
errorMessageStringA detailed message about the error
sdkRequestDetailsDictThe request which was sent to the Opsgenie's API
sdkResultDetailsHTTPResponseThe raw HTTPResponse generated by urllib3. The user may choose to extract and parse any details from it in any way

Short API Polling Support

Alert/Incident creation, deletion, and action requests are processed asynchronously to provide higher availability and scalability. Therefore valid requests for those endpoints are responded to with HTTP status 202 - Accepted. The Get Request Status endpoint is used to track the status and alert/incident details (if any) of the request whose identifier is given.

If you want to avoid to have to manually call the Get Request Status, over and over again, to keep track of your alert/incident and call the Get Alert, or Get Incident to possibly get it, then you may choose to short poll our API like the following, using the Alert client or the Incident client, that is initialized prior to performing any Opsgenie API functionality.

# you might alternatively use an incident client as well
  alert = Example()
  
  print('Create Alert:')
  create_response = alert.create()
  print(create_response)

  print()
  
  # Changing the default max short polling retries attempt
  self.conf.short_polling_max_retries = 15
    
  print('Retrieve Result:')
  create_result = create_response.retrieve_result()
  print(json.loads(create_result.data))

  print()

  print('Retrieve Resulting Alert:')
  create_resulting_alert = create_response.retrieve_resulting_action()
  print(json.loads(create_resulting_alert.data))

  alert_id = create_response.alert_id

In the above example, calling retrieve_result function on the response object in the create_response variable will start polling our API, using an exponential backoff retry algorithm with full jitter, similar to the one described in Exponential Backoff and Jitter (AWS Architecture Blog). This function can, for example, be used to wait until the recent request of Incident/Alert creation has been successfully processed by the Opsgenie API, before you proceed to do any further operations on it. The default number of maximum retries of this algorithm is 10, which can be modified in the configuration object, as shown in the above example.

While calling the retrieve_resulting_action function would retrieve the corresponding alert or incident for you, similar to Get Alert and Get Incident. If you call this function before calling retrieve_result function then this function will make that call for you in its own execution. The end goal of this function is for you to be able to easily retrieve your newly created Alert/Incident, without having to manually track its status.

And reading the id property of the same response object would retrieve the alertId or incidentId, depending on your context, for you as well. If you try to read this property ahead of calling retrieve_result function, then this reading operation would automatically call that function, first, for you. If all you want is the id of your newly created Alert/Incident, then you can simply read this property, without having to worry about first polling the Opsgenie API, retrieving your entity, and then getting your desired id.

Configurable Logging Support

The default logging facility of Python is used. You can access and modify the loggers and some of their configurations in the Configuration singleton present in the opsgenie_client/configuration.py file like the following:

# Initialize configurations
conf = opsgenie_sdk.configuration.Configuration()

# Default Logging Settings
conf.logger = {}
conf.logger["package_logger"] = logging.getLogger("opsgenie_client")
conf.logger["urllib3_logger"] = logging.getLogger("urllib3")
# Log format
conf.logger_format = '%(asctime)s %(levelname)s %(message)s'
# Log stream handler
conf.logger_stream_handler = None
# Log file handler
conf.logger_file_handler = None
# Debug file location
conf.logger_file = None
# Debug switch
conf.debug = False

Configurable Proxy Support

In order to use a proxy, you have to modify the proxy property of the Configuration singleton present in the opsgenie_client/configuration.py file. You might also choose to use the ProxyConfiguration helper class in the opsgenie_client/proxy_configuration.py file to easily build your proxy url like the following:

from opsgenie_sdk.proxy_configuration import ProxyConfiguration

proxy_conf = ProxyConfiguration(host='1.1.1.1', port='8080', username='[email protected]', password='password', protocol='https')

# Initialize configurations
conf = opsgenie_sdk.configuration.Configuration()
# Add your proxy configurations to main configurations
conf.proxy = proxy_conf.get_proxy_url()

Configurable Retry Policy Support

Opsgenie's Python SDK incorporates retry policies to ensure that you do get the response you are looking for even if your first request failed. The SDK ensures that a request that failed is retried a total of 5 times by default. The algorithm used for retrying corresponds to the "Full Jitter" one described in the blogpost, https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ However, you can tweak the retry policy of the SDK, or even disable the retry policy. The parameters, of the configuration object, which you may use to tweak your retry policy are seen in the table below:

ParameterTypeDefaultDefinition
retry_enabledBooleanTrueAllows one to enable or disable the SDK's retry policy.
retry_countInt5Number of times a request is tried upon encountering any error response code, such as 429.
retry_http_response[String]['429', '500', '502-599']Http codes that will cause a retry if the number of times already retried is less than the retry_count set.
retry_delayFloat30Max delay in seconds between retry attempts of the full jitter algorithm.
retry_max_delayFloat60The upper limit for the amount of time, in seconds, for which the retries will be attempted for.
back_offInt1Multiplier applied to delay between attempts.

Configuring Retry Policy

There are two ways you can configure the retry policy. One way is initializing the Opsgenie Configuration object and setting the variables accordingly. The second way is by creating a retry object and passing it into the Opsgenie Configuration with the set_retry_policy function.

from opsgenie_client.configuration import Configuration

# Initializing Opsgenie Configuration Object
conf = Configuration()

# Setting configuration parameters
conf.api_key['Authorization'] = '<Your-API-Key>'
conf.debug = True
conf.retry_count = 5
conf.retry_http_response = ['5xx', '100-200', '429']
conf.retry_delay = 2
conf.retry_enabled = True

Configuring HTTP Codes

The HTTP codes that the retry policy retries a request upon is set by default to all 500 codes and 429. However, you can change the policy by using the retry_http_response parameter. The value to pass in is an array of string values, where these string values can have any of the three forms:

  • '5xx' - All the HTTP codes within the hundred range of the first digit
  • '429' - A specific HTTP code
  • '404-329' - A range of HTTP codes including the boundary codes
    Example:
    ['1xx','429', '500-530']

SDK Domains