Module Reference

This page covers the documentation of individual methods and classes provided by the module. For general usage and examples, refer to the User Guide.

API Client Classes

class pdpyras.PDSession(api_key: str, debug=False)

Base class for making HTTP requests to PagerDuty APIs

This is an opinionated wrapper of requests.Session, with a few additional features:

  • The client will reattempt the request with auto-increasing cooldown/retry intervals, with attempt limits configurable through the retry attribute.

  • When making requests, headers specified ad-hoc in calls to HTTP verb functions will not replace, but will be merged into, default headers.

  • The request URL, if it doesn’t already start with the REST API base URL, will be prepended with the default REST API base URL.

  • It will only perform requests with methods as given in the permitted_methods list, and will raise PDClientError for any other HTTP methods.

  • api_key – REST API access token to use for HTTP requests

  • debug (bool) – Sets print_debug. Set to True to enable verbose command line output.


Setter hook for setting or updating the API key.

Child classes should implement this to perform additional steps.

property api_key

API Key property getter.

Returns the _api_key attribute’s value.

property auth_header

Generates the header with the API credential used for authentication.

log = None

A logging.Logger object for logging messages. By default it is configured without any handlers and so no messages will be emitted. See logger objects

max_http_attempts = 10

The number of times that the client will retry after error statuses, for any that are defined greater than zero in retry.

max_network_attempts = 3

The number of times that connecting to the API will be attempted before treating the failure as non-transient; a PDClientError exception will be raised if this happens.


Modify the user-supplied parameters.

Current behavior:

  • If a parameter’s value is of type list, and the parameter name does not already end in “[]”, then the square brackets are appended to keep in line with the requirement that all set filters’ parameter names end in “[]”.


Compose the URL whether it is a path or an already-complete URL

parent = None

The super object (requests.Session)

permitted_methods = ()

A tuple of the methods permitted by the API which the client implements.

For instance:

  • The REST API accepts GET, POST, PUT and DELETE.

  • The Events API and Change Events APIs only accept POST.


Perform supplemental actions immediately after receiving a response.

This method is called once per request not including retries, and can be extended in child classes.

prepare_headers(method, user_headers={})

Append special additional per-request headers.

  • method – The HTTP method, in upper case.

  • user_headers – Headers that can be specified to override default values.

property print_debug

Printing debug flag

If set to True, the logging level of log is set to logging.DEBUG and all log messages are emitted to sys.stderr. If set to False, the logging level of log is set to logging.NOTSET and the debugging log handler that prints messages to sys.stderr is removed. This value thus can be toggled to enable and disable verbose command line output.

It is False by default and it is recommended to keep it that way in production settings.

request(method, url, **kwargs)

Make a generic PagerDuty API request.

  • method (str) – The request method to use. Case-insensitive. May be one of get, put, post or delete.

  • url (str) – The path/URL to request. If it does not start with the base URL, the base URL will be prepended.

  • **kwargs

    Custom keyword arguments to pass to requests.Session.request.


the HTTP response object

Return type:


retry = {}

A dict defining the retry behavior for each HTTP response status code.

Note, any value set for this class variable will not be reflected in instances and so it must be set separately for each instance.

Each key in this dictionary is an int representing a HTTP response code. The behavior is specified by the int value at each key as follows:

  • -1 to retry infinitely

  • 0 to return the requests.Response object and exit (which is the default behavior)

  • n, where n > 0, to retry n times (or up to max_http_attempts total for all statuses, whichever is encountered first), and raise a PDClientError after that many attempts. For each successive attempt, the wait time will increase by a factor of sleep_timer_base.

The default behavior is to retry infinitely on a 429, and return the response in any other case (assuming a HTTP response was received from the server).

sleep_timer = 1.5

Default initial cooldown time factor for rate limiting and network errors.

Each time that the request makes a followup request, there will be a delay in seconds equal to this number times sleep_timer_base to the power of how many attempts have already been made so far, unless stagger_cooldown is nonzero.

sleep_timer_base = 2

After each retry, the time to sleep before reattempting the API connection and request will increase by a factor of this amount.

property stagger_cooldown

Randomizing factor for wait times between retries during rate limiting.

If set to number greater than 0, the sleep time for rate limiting will (for each successive sleep) be adjusted by a factor of one plus a uniformly-distributed random number between 0 and 1 times this number, on top of the base sleep timer sleep_timer_base.

For example:

  • If this is 1, and sleep_timer_base is 2 (default), then after each status 429 response, the sleep time will change overall by a random factor between 2 and 4, whereas if it is zero, it will change by a factor of 2.

  • If sleep_timer_base is 1, then the cooldown time will be adjusted by a random factor between one and one plus this number.

If the number is set to zero, then this behavior is effectively disabled, and the cooldown factor (by which the sleep time is adjusted) will just be sleep_timer_base

Setting this to a nonzero number helps avoid the “thundering herd” effect that can potentially be caused by many API clients making simultaneous concurrent API requests and consequently waiting for the same amount of time before retrying. It is currently zero by default for consistent behavior with previous versions.

timeout = 60

This is the value sent to Requests as the timeout parameter that determines the TCP read timeout.

property trunc_key

Truncated key for secure display/identification purposes.

class pdpyras.APISession(api_key, default_from=None, auth_type='token', debug=False)

PagerDuty REST API v2 session object class.

Implements the most generic and oft-implemented aspects of PagerDuty’s REST API v2 as an opinionated wrapper of requests.Session.

Inherits from PDSession.

  • api_key – REST API access token to use for HTTP requests

  • default_from (str or None) – The default email address to use in the From header when making API calls using an account-level API access key.

  • auth_type – The type of credential in use. If authenticating with an OAuth access token, this must be set to oauth2 or bearer.

  • debug (bool) – Sets print_debug. Set to True to enable verbose command line output.


api_call_counts = None

A dict object recording the number of API calls per endpoint

property api_key_access

Memoized API key access type getter.

Will be “user” if the API key is a user-level token (all users should have permission to create an API key with the same permissions as they have in the PagerDuty web UI).

If the API key in use is an account-level API token (as only a global administrator user can create), this property will be “account”.

api_time = None

A dict object recording the total time of API calls to each endpoint

property auth_type

Defines the method of API authentication.

By default this is “token”; if “oauth2”, the API key will be used.

default_from = None

The default value to use as the From request header

default_page_size = 100

This will be the default number of results requested in each page when iterating/querying an index (the limit parameter).

dict_all(path, **kw)

Returns a dictionary of all objects from a given index endpoint.

With the exception of by, all keyword arguments passed to this method are also passed to iter_all; see the documentation on that method for further details.

  • path – The index endpoint URL to use.

  • by – The attribute of each object to use for the key values of the dictionary. This is id by default. Please note, there is no uniqueness validation, so if you use an attribute that is not distinct for the data set, this function will omit some data in the results.

find(resource, query, attribute='name', params=None)

Finds an object of a given resource type exactly matching a query.

Returns a dict if a result is found. The structure will be that of an entry in the index endpoint schema’s array of results. Otherwise, it will return None if no result is found or an error is encountered.

Works by querying a given resource index endpoint using the query parameter. To use this function on any given resource, the resource’s index must support the query parameter; otherwise, the function may not work as expected. If the index ignores the parameter, for instance, this function will take much longer to return; results will not be constrained to those matching the query, and so every result in the index will be downloaded and compared against the query up until a matching result is found or all results have been checked.

  • resource (str) – The name of the resource endpoint to query, i.e. escalation_policies

  • query (str) – The string to query for in the the index.

  • attribute (str) – The property of each result to compare against the query value when searching for an exact match. By default it is name, but when searching for user by email (for example) it can be set to email

  • params (dict or None) – Optional additional parameters to use when querying.

Return type:


iter_all(url, params=None, page_size=None, item_hook=None, total=False)

Iterator for the contents of an index endpoint or query.

Automatically paginates and yields the results in each page, until all matching results have been yielded or a HTTP error response is received.

If the URL to use supports cursor-based pagintation, then this will return iter_cursor with the same keyword arguments. Otherwise, it implements classic pagination, a.k.a. numeric pagination.

Each yielded value is a dict object representing a result returned from the index. For example, if requesting the /users endpoint, each yielded value will be an entry of the users array property in the response.

  • url (str) – The index endpoint URL to use.

  • params (dict or None) – Additional URL parameters to include.

  • page_size (int or None) – If set, the page_size argument will override the default_page_size parameter on the session and set the limit parameter to a custom value (default is 100), altering the number of pagination results. The actual number of results in the response will still take precedence, if it differs; this parameter and default_page_size only dictate what is requested of the API.

  • item_hook – Callable object that will be invoked for each iteration, i.e. for printing progress. It will be called with three parameters: a dict representing a given result in the iteration, an int representing the number of the item in the series, and an int (or str, as of v5.0.0) representing the total number of items in the series. If the total isn’t knowable, the value passed is “?”.

  • total (bool) – If True, the total parameter will be included in API calls, and the value for the third parameter to the item hook will be the total count of records that match the query. Leaving this as False confers a small performance advantage, as the API in this case does not have to compute the total count of results in the query.

iter_cursor(url, params=None, item_hook=None)

Iterator for results from an endpoint using cursor-based pagination.

  • url – The index endpoint URL to use.

  • params – Query parameters to include in the request.

  • item_hook – A callable object that accepts 3 positional arguments; see

jget(resource, **kw)

Performs a GET request, returning the JSON-decoded body as a dictionary

jpost(resource, **kw)

Performs a POST request, returning the JSON-decoded body as a dictionary

jput(resource, **kw)

Performs a PUT request, returning the JSON-decoded body as a dictionary

list_all(url, **kw)

Returns a list of all objects from a given index endpoint.

All keyword arguments passed to this function are also passed directly to iter_all; see the documentation on that method for details.


url – The index endpoint URL to use.

persist(resource, attr, values, update=False)

Finds or creates and returns a resource with a matching attribute

Given a resource name, an attribute to use as an idempotency key and a set of attribute:value pairs as a dict, create a resource with the specified attributes if it doesn’t exist already and return the resource persisted via the API (whether or not it already existed).

  • resource (str) – The URL to use when creating the new resource or searching for an existing one. The underlying AP must support entity wrapping to use this method with it.

  • attr (str) – Name of the attribute to use as the idempotency key. For instance, “email” when the resource is “users” will not create the user if a user with the email address given in values already exists.

  • values (dict) – The content of the resource to be created, if it does not already exist. This must contain an item with a key that is the same as the attr argument.

  • update (bool) – (New in 4.4.0) If set to True, any existing resource will be updated with the values supplied.

Return type:


postprocess(response: Response, suffix=None)

Records performance information / request metadata about the API call.

rdelete(resource, **kw)

Delete a resource.

  • resource (str or dict) – The path/URL to which to send the request, or a dict object representing an API resource that contains an item with key self whose value is the URL of the resource.

  • **kw

    Custom keyword arguments to pass to requests.Session.delete

rget(resource, **kw)

Wrapped-entity-aware GET function.

Retrieves a resource via GET and returns the wrapped entity in the response.

  • resource (str or dict) – The path/URL to which to send the request, or a dict object representing an API resource that contains an item with key self whose value is the URL of the resource.

  • **kw

    Custom keyword arguments to pass to requests.Session.get


Dictionary representation of the object.

Return type:


rpost(url, **kw)

Wrapped-entity-aware POST function.

Creates a resource and returns the created entity if successful.

  • path (str) – The path/URL to which to send the POST request, which should be an index endpoint.

  • **kw

    Custom keyword arguments to pass to


Dictionary representation of the created object

Return type:


rput(resource, **kw)

Wrapped-entity-aware PUT function.

Update an individual resource, returning the wrapped entity.

  • resource – The path/URL to which to send the request, or a dict object representing an API resource that contains an item with key self whose value is the URL of the resource.

  • **kw

    Custom keyword arguments to pass to requests.Session.put


Dictionary representation of the updated object

Return type:


property subdomain

Subdomain of the PagerDuty account of the API access token.


str or None

property total_call_count

The total number of API calls made by this instance.

property total_call_time

The total time spent making API calls.

property trunc_token

Truncated token for secure display/identification purposes.

url = ''

Base URL of the REST API

class pdpyras.EventsAPISession(api_key: str, debug=False)

Session class for submitting events to the PagerDuty v2 Events API.

Implements methods for submitting events to PagerDuty through the Events API and inherits from pdpyras.PDSession. For more details on usage of this API, refer to the Events API v2 documentation

Inherits from PDSession.


Acknowledge an alert via Events API.


dedup_key – The deduplication key of the alert to set to the acknowledged state.

post(*args, **kw)

Override of

Adds the routing_key parameter to the body before sending.

prepare_headers(method, user_headers={})

Add user agent and content type headers for Events API requests.


user_headers – User-supplied headers that will override defaults


Resolve an alert via Events API.


dedup_key – The deduplication key of the alert to resolve.

send_event(action, dedup_key=None, **properties)

Send an event to the v2 Events API.


  • action (str) – The action to perform through the Events API: trigger, acknowledge or resolve.

  • dedup_key (str) – The deduplication key; used for determining event uniqueness and associating actions with existing incidents.

  • **properties

    Additional properties to set, i.e. if action is trigger this would include payload.


The deduplication key of the incident, if any.

trigger(summary, source, dedup_key=None, severity='critical', payload=None, custom_details=None, images=None, links=None)

Trigger an incident

  • summary (str) – Summary / brief description of what is wrong.

  • source (str) – A human-readable name identifying the system that is affected.

  • dedup_key (str) – The deduplication key; used for determining event uniqueness and associating actions with existing incidents.

  • severity (str) – Alert severity. Sets the payload.severity property.

  • payload (dict) – Set the payload directly. Can be used in conjunction with other parameters that also set payload properties; these properties will be merged into the default payload, and any properties in this parameter will take precedence except with regard to custom_details.

  • custom_details (dict) – The payload.custom_details property of the payload. Will override the property set in the payload parameter if given.

  • images (list) – Set the images property of the event.

  • links (list) – Set the links property of the event.

Return type:


class pdpyras.ChangeEventsAPISession(api_key: str, debug=False)

Session class for submitting change events to the PagerDuty v2 Change Events API.

Implements methods for submitting change events to PagerDuty’s change events API. See the Change Events API documentation for more details.

Inherits from PDSession.

prepare_headers(method, user_headers={})

Add user agent and content type headers for Change Events API requests.


Send a change event to the v2 Change Events API.




Properties to set, i.e. payload and links


The response ID

submit(summary, source=None, custom_details=None, links=None, timestamp=None)

Submit an incident change

  • summary (str) – Summary / brief description of the change.

  • source (str) – A human-readable name identifying the source of the change.

  • custom_details (dict) – The payload.custom_details property of the payload.

  • links (list) – Set the links property of the event.

  • timestamp (str) – Specifies an event timestamp. Must be an ISO8601-format date/time.

Return type:



class pdpyras.PDClientError(message, response=None)

General API errors base class.

Note, the name of this class does not imply it solely includes errors experienced by the client or HTTP status 4xx responses, but descendants can include issues with the API backend.

response = None

The HTTP response object, if a response was successfully received.

In the case of network errors, this property will be None.

class pdpyras.PDHTTPError(message, response: Response)

Error class representing errors strictly associated with HTTP responses.

This class was created to make it easier to more cleanly handle errors by way of a class that is guaranteed to have its response be a valid requests.Response object.

Whereas, the more generic PDClientError could also be used to denote such things as non-transient network errors wherein no response was recevied from the API.

For instance, instead of this:

    user = session.rget('/users/PABC123')
except pdpyras.PDClientError as e:
    if e.response is not None:
        print("HTTP error: "+str(e.response.status_code))
        raise e

one could write this:

    user = session.rget('/users/PABC123')
except pdpyras.PDHTTPError as e:
    print("HTTP error: "+str(e.response.status_code))
class pdpyras.PDServerError(message, response: Response)

Error class representing failed expectations made of the server

This is raised in cases where the response schema differs from the expected schema because of an API bug, or because it’s an early access endpoint and changes before GA, or in cases of HTTP status 5xx where a successful response is required.

class pdpyras.URLError

Exception class for unsupported URLs or malformed input.

Client Defaults

These are properties of the module that configure default behavior for the API client. There should be no need for the end user to modify them.


Explicit list of supported canonical REST API v2 paths


Explicit list of paths that support cursor-based pagination


Wrapped entities antipattern handling configuration.

When trying to determine the entity wrapper name, this dictionary is first checked for keys that apply to a given request method and canonical API path based on a matching logic. If no keys are found that match, it is assumed that the API endpoint follows classic entity wrapping conventions, and the wrapper name can be inferred based on those conventions (see infer_entity_wrapper). Any new API that does not follow these conventions should therefore be given an entry in this dictionary in order to properly support it for entity wrapping.

Each of the keys should be a capitalized HTTP method (or * to match any method), followed by a space, followed by a canonical path i.e. as returned by canonical_path and included in CANONICAL_PATHS. Each value is either a tuple with request and response body wrappers (if they differ), a string (if they are the same for both cases) or None (if wrapping is disabled and the data is to be marshaled or unmarshaled as-is). Values in tuples can also be None to denote that either the request or response is unwrapped.

An endpoint, under the design logic of this client, is said to have entity wrapping if the body (request or response) has only one property containing the content requested or transmitted, apart from properties used for pagination. If there are any secondary content-bearing properties (other than those used for pagination), entity wrapping should be disabled to avoid discarding those properties from responses or preventing the use of those properties in request bodies.

pdpyras.ITERATION_LIMIT = 10000.0

The maximum position of a result in classic pagination.

The offset plus limit parameter may not exceed this number. This is enforced server-side and is not something the client may override. Rather, this value is used to short-circuit pagination in order to avoid a HTTP 400 error.

See: Pagination.

pdpyras.TEXT_LEN_LIMIT = 100

The longest permissible length of API content to include in error messages.

pdpyras.TIMEOUT = 60

The default timeout in seconds for any given HTTP request.

Modifying this value will not affect any preexisting API session instances. Rather, it will only affect new instances. It is recommended to use PDSession.timeout to configure the timeout for a given session.


These are generic functions used by the API session classes and are not on their own typically needed, but which are documented for the benefit of anyone who may find use in them.

URL Handling

URL related functions.

pdpyras.canonical_path(base_url: str, url: str)

Returns the canonical REST API path corresponding to a URL.

This is used to identify and classify URLs according to which particular API within REST API v2 it belongs to.

Explicitly supported canonical paths are defined in the list CANONICAL_PATHS and are the path part of any given API’s URL. The path for a given API is what is shown at the top of its reference page, i.e. /users/{id}/contact_methods for retrieving a user’s contact methods (GET) or creating a new one (POST).

  • base_url – The base URL of the API

  • url – A non-normalized URL (a path or full URL)

Return type:


pdpyras.endpoint_matches(endpoint_pattern: str, method: str, path: str)

Returns true if a method and path match an endpoint pattern.

This is the filtering logic used for finding the appropriate entry in ENTITY_WRAPPER_CONFIG to use for a given method and API path.

  • endpoint_pattern – The endpoint pattern in the form METHOD PATH where METHOD is the HTTP method in uppercase or * to match all methods, and PATH is a canonical API path.

  • method – The HTTP method.

  • path – The canonical API path (i.e. as returned by canonical_path())

Return type:


pdpyras.is_path_param(path_node: str)

Returns true if a given node in a canonical path represents a parameter.


path_node – The node (value between slashes) in the path

Return type:


pdpyras.normalize_url(base_url: str, url: str)

Normalize a URL to a complete API URL.

The url argument may be a path relative to the base URL or a full URL.

  • url – The URL to normalize

  • baseurl – The base API URL, excluding any trailing slash, i.e. “


The full API endpoint URL

Return type:


Entity Wrapping

Functions that implement entity wrapping logic.

pdpyras.entity_wrappers(method: str, path: str)

Obtains entity wrapping information for a given endpoint (path and method)

Returns a 2-tuple. The first element is the wrapper name that should be used for the request body, and the second is the wrapper name to be used for the response body. For either elements, if None is returned, that signals to disable wrapping and pass the user-supplied request body or API response body object unmodified.

  • method – The HTTP method

  • path – A canonical API path i.e. as returned by canonical_path

Return type:


pdpyras.infer_entity_wrapper(method: str, path: str)

Infer the entity wrapper name from the endpoint using orthodox patterns.

This is based on patterns that are broadly applicable but not universal in the v2 REST API, where the wrapper name is predictable from the path and method. This is the default logic applied to determine the wrapper name based on the path if there is no explicit entity wrapping defined for the given path in ENTITY_WRAPPER_CONFIG.

  • method – The HTTP method

  • path – A canonical API path i.e. as returned by canonical_path

Return type:


pdpyras.unwrap(response: Response, wrapper)

Unwraps and returns a wrapped entity.

  • response – The response object

  • wrapper (str or None) – The entity wrapper

Function Decorators

Intended for use with functions based on the HTTP verb functions of subclasses of requests.Session, i.e. that would otherwise return a requests.Response object.


Makes methods return the full response body object after decoding from JSON.

Intended for use on functions that take a URL positional argument followed by keyword arguments and return a requests.Response object.


Decorator that validates HTTP responses.


API call decorator that allows passing a resource dict as the path/URL

Most resources returned by the API will contain a self attribute that is the URL of the resource itself.

Using this decorator allows the implementer to pass either a URL/path or such a resource dictionary as the path argument, thus eliminating the need to re-construct the resource URL or hold it in a temporary variable.


Automatically wrap request entities and unwrap response entities.

Used for methods APISession.rget, APISession.rpost and APISession.rput. It makes them always return an object representing the resource entity in the response (whether wrapped in a root-level property or not) rather than the full response body. When making a post / put request, and passing the json keyword argument to specify the content to be JSON-encoded as the body, that keyword argument can be either the to-be-wrapped content or the full body including the entity wrapper, and the json keyword argument will be normalized to include the wrapper.

Methods using this decorator will raise a PDHTTPError with its response property being being the requests.Response object in the case of any error (as of version 4.2 this is subclassed as PDHTTPError), so that the implementer can access it by catching the exception, and thus design their own custom logic around different types of error responses.


method – Method being decorated. Must take one positional argument after self that is the URL/path to the resource, followed by keyword any number of keyword arguments, and must return an object of class requests.Response, and be named after the HTTP method but with “r” prepended.


A callable object; the reformed method


Miscellaneous functions

pdpyras.deprecated_kwarg(deprecated_name: str, details=None)

Raises a warning if a deprecated keyword argument is used.

  • deprecated_name – The name of the deprecated function

  • details – An optional message to append to the deprecation message

pdpyras.http_error_message(r: Response, context=None)

Formats a message describing a HTTP error.

  • r – The response object.

  • context – A description of when the error was received, or None to not include it

pdpyras.last_4(secret: str)

Returns an abbreviation of the input

pdpyras.plural_name(obj_type: str)

Pluralizes a name, i.e. the API name from the type property


obj_type – The object type, i.e. user or user_reference


The name of the resource, i.e. the last part of the URL for the resource’s index URL

Return type:


pdpyras.successful_response(r: Response, context=None) Response

Validates the response as successful.

Returns the response if it was successful; otherwise, raises an exception.

  • r – Response object corresponding to the response received.

  • context – A description of when the HTTP request is happening, for error reporting


The response object, if it was successful

pdpyras.truncate_text(text: str)

Truncates a string longer than TEXT_LEN_LIMIT


text – The string to truncate if longer than the limit.

pdpyras.try_decoding(r: Response)

JSON-decode a response body

Returns the decoded body if successful; raises PDServerError otherwise.


r – The response object