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 pagerduty.ApiClient(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 raiseError
for any other HTTP methods.
- Parameters:
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.
- after_set_api_key()
Setter hook for setting or updating the API key.
Child classes should implement this to perform additional steps.
- property api_key: str
Property representing the credential used for accessing the given API.
- property auth_header: dict
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
Error
exception will be raised if this happens.
- normalize_params(params: dict) dict
Modify the user-supplied parameters to ease implementation
- Returns:
The query parameters after modification
- normalize_url(url: str) str
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.
- postprocess(response: Response)
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: str, user_headers: dict | None = None) dict
Append special additional per-request headers.
- Parameters:
method – The HTTP method, in upper case.
user_headers – Headers that can be specified to override default values.
- Returns:
The final list of headers to use in the request
- property print_debug: bool
Printing debug flag
If set to True, the logging level of
log
is set tologging.DEBUG
and all log messages are emitted tosys.stderr
. If set to False, the logging level oflog
is set tologging.NOTSET
and the debugging log handler that prints messages tosys.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: str, url: str, **kwargs) Response
Make a generic PagerDuty API request.
- Parameters:
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
.
- Returns:
The requests.Response object corresponding to the HTTP response
- retry = {}
A dict defining the retry behavior for each HTTP response status code.
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 without limit.0
has no effect; the default behavior will take effect.n
, wheren > 0
, to retryn
times (or up tomax_http_attempts
total for all statuses, whichever is encountered first), and then return the final response.
The default behavior is to retry without limit on status 429, raise an exception on a 401, and return the requests.Response object 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, unlessstagger_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: float
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: str
Truncated key for secure display/identification purposes.
- class pagerduty.OAuthTokenClient(client_secret: str, client_id: str, debug=False)
Client with helpers for performing an OAuth exchange to obtain an access token.
Tokens obtained using the client can then be used to authenticate REST API clients, e.g.
oauth_exchange_client = pagerduty.OAuthTokenClient(client_secret, client_id) oauth_response = oauth_exchange_client.get_scoped_app_token('read') client = pagerduty.RestApiV2Client(oauth_response['access_token'], auth_type='bearer')
Requires registering a PagerDuty App to obtain the necessary credentials, and must be used in the context of an OAuth2 authorization flow.
For further details, refer to:
- amended_auth_response(response: Response) dict
Amends the auth response map as necessary for other functionality.
- Parameters:
auth_response – A response from the /oauth/token endpoint as a dictionary.
- Returns:
The same response from the API in dictionary form with an additional key
expiration_date
containing the expiration date/time of the token in ISO8601 format. This value can then be used inrefresh_client
.
- authorize_url(scope: str, redirect_uri: str) str
The authorize URL in PagerDuty that the end user will visit to authorize the app
- Parameters:
scope – Scope of the OAuth grant requested
redirect_uri – The redirect URI in the application that receives the authorization code through client redirect from PagerDuty
- Returns:
The formatted authorize URL.
- early_refresh_buffer = 86400
Number of seconds before the expiration date to perform a token refresh.
Used when constructing a
RestApiV2Client
; if the current date/time is after the expiration date, or less than this number of seconds before it, a token refresh is first performed.If the application is expected to use the resulting client object for more than this amount of time between each new call to
refresh_client
, this value can be set higher.By default, this is 24 hours.
- classmethod get_authorize_url(client_id: str, scope: str, redirect_uri: str) str
Generate an authorize URL.
This method can be called directly to circumvent the need to produce a client secret that is otherwise required to instantiate an object.
This is the URL that the user initially visits in the application to authorize the application, which will ultimately redirect the user to
redirect_uri
but with the authorization code.- Parameters:
client_id – Client ID of the application
scope – Scope of the OAuth grant requested
redirect_uri – The redirect URI in the application that receives the authorization code through client redirect from PagerDuty
- Returns:
The formatted authorize URL.
- get_new_token(**kw) dict
Make a token request.
There should not be any need to call this method directly. Each of the supported types of token exchange requests are implemented in other methods:
- Returns:
The JSON response from
identity.pagerduty.com
as a dictionary after amending viaamended_auth_response
. It should contain a keyaccess_token
with the new token andexpiration_date
containing the date and time when the token will expire in ISO8601 format.
- get_new_token_from_code(auth_code: str, scope: str, redirect_uri: str) dict
Exchange an authorization code granted by the user for an access token.
- Parameters:
auth_code – The authorization code received by the application at the redirect URI provided.
scope – The scope of the authorization request.
- Redirect_uri:
The redirect URI that was used in the authorization request.
- Returns:
The JSON response from
identity.pagerduty.com
, containing a keyaccess_token
with the new token, as a dict
- get_refreshed_token(refresh_token: str) dict
Obtain a new access token using a refresh token.
- Parameters:
refresh_token – The refresh token provided in the response of the original access token, i.e. in the dict returned by
get_new_token
- Returns:
The JSON response from
identity.pagerduty.com
, containing a keyaccess_token
with the new token, as a dict
- get_scoped_app_token(scope: str)
Obtain a scoped app token.
This can be used to grant a server-side app a scoped non-user application token.
- Parameters:
scope – The scope of the authorization request.
- Returns:
The JSON response from
identity.pagerduty.com
, containing a keyaccess_token
with the new token, as a dict
- refresh_client(access_token: str, refresh_token: str, expiration_date: str, base_url: str = 'https://api.pagerduty.com', **kw) Tuple[RestApiV2Client, dict | None]
Instantiate and return a
pagerduty.RestApiV2Client
client objectPerforms a token refresh if the current time is later than
early_refresh_buffer
seconds before the expiration date.- Parameters:
access_token – The current REST API access token.
refresh_token – The refresh token required to refresh the access token.
expiration_date – The expiration date of the access token, formatted as an ISO8601 datetime string, including the timezone suffix as a UTC offset. The value contained in the
expiration_date
key of the amended response dictionary returned by any of the “get token” methods should be usable as this parameter.base_url – The value to use for the
url
attribute of the API client object.kw – Keyword arguments to pass to the constructor of the API client object.
- Returns:
A tuple containing a
pagerduty.RestApiV2Client
object as its first element and the the amended OAuth response if a refresh was performed (andNone
otherwise) as its second element.
- class pagerduty.RestApiV2Client(api_key: str, default_from: str | None = None, auth_type: str = 'token', debug: bool = False)
PagerDuty REST API v2 client class.
Implements the most generic and oft-implemented aspects of PagerDuty’s REST API v2 as an opinionated wrapper of requests.Session.
Inherits from
ApiClient
.- Parameters:
api_key – REST API access token to use for HTTP requests
default_from – 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
orbearer
.debug – Sets
print_debug
. Set to True to enable verbose command line output.
- Members:
- account_has_ability(ability: str) bool
Test that the account has an ability.
- Parameters:
ability – The named ability, i.e.
teams
.- Returns:
True or False based on whether the account has the named ability.
- api_call_counts = None
A dict object recording the number of API calls per endpoint
- property api_key_access: str
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: str
Defines the method of API authentication.
This value determines how the Authorization header will be set. By default this is “token”, which will result in the format
Token token=<api_key>
.
- 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: str, by: str = 'id', **kw) dict
Dictionary representation of all results from an index endpoint.
With the exception of
by
, all keyword arguments passed to this method are also passed toiter_all
; see the documentation on that method for further details.- Parameters:
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. If a property is named that the schema of the API requested does not have, this method will raiseKeyError
.kw – Keyword arguments to pass to
iter_all
.
- Returns:
A dictionary keyed by the values of the property of each result specified by the
by
parameter.
- find(resource: str, query: str, attribute: str = 'name', params: dict | None = None) dict | None
Finds an object of a given resource type exactly matching a query.
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 thequery
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.The comparison between the query and matching results is case-insenitive. When determining uniqueness, APIs are mostly case-insensitive, and therefore objects with similar characters but differing case can’t even exist. All results (and the search query) are for this reason reduced pre-comparison to a common form (all-lowercase strings) so that case doesn’t need to match in the query argument (which is also interpreted by the API as case-insensitive).
If said behavior differs for a given API, i.e. the uniqueness constraint on a field is case-sensitive, it should still return the correct results because the search term sent to the index in the querystring is not lower-cased.
- Parameters:
resource – The name of the resource endpoint to query, i.e.
escalation_policies
query – The string to query for in the the index.
attribute – 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 toemail
params – Optional additional parameters to use when querying.
- Returns:
The dictionary representation of the result, if found;
None
will be returned if there is no exact match result.
- get_total(url: str, params: dict | None = None) int
Gets the total count of records from a classic pagination index endpoint.
- Parameters:
url – The URL of the API endpoint to query
params – An optional dictionary indicating additional parameters to send to the endpoint, i.e. filters, time range (
since
anduntil
), etc. This may influence the total, i.e. if specifying a filter that matches a subset of possible results.
- Returns:
The total number of results from the endpoint with the parameters given.
- iter_alert_grouping_settings(service_ids: list | None = None, limit: int | None = None) Iterator[dict]
Iterator for the contents of the “List alert grouping settings” endpoint.
The API endpoint “GET /alert_grouping_settings” has its own unique method of pagination. This method provides an abstraction for it similar to what
iter_all
provides for endpoints that implement classic pagination.See: List alert grouping settings
- Parameters:
service_ids – A list of specific service IDs to which results will be constrained.
limit – The number of results retrieved per page. By default, the value
default_page_size
will be used.
- Yields:
Results from each page in the
alert_grouping_settings
response property.
- iter_all(url, params: dict | None = None, page_size: int | None = None, item_hook: callable | None = None, total: bool = False) Iterator[dict]
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 theusers
array property in the response.- Parameters:
url – The index endpoint URL to use.
params – Additional URL parameters to include.
page_size – If set, the
page_size
argument will override thedefault_page_size
parameter on the session and set thelimit
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 anddefault_page_size
only dictate what is requested of the API.item_hook – Callable object that will be invoked for each item yielded, 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 a value representing the total number of items in the series. If the total isn’t knowable, i.e. the
total
parameter isFalse
or omitted, the value passed in for the third argument will be the string value"?"
.total – 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.
- Yields:
Results from each page of results.
- iter_analytics_raw_incidents(filters: dict, order: str = 'desc', order_by: str = 'created_at', limit: int | None = None, time_zone: str | None = None) Iterator[dict]
Iterator for raw analytics data on multiple incidents.
The API endpoint
POST /analytics/raw/incidents
has its own unique method of pagination. This method provides an abstraction for it similar toiter_all
.See: Get raw data - multiple incidents
- Parameters:
filters – Dictionary representation of the required
filters
parameters.order – The order in which to sort results. Must be
asc
ordesc
.order_by – The attribute of results by which to order results. Must be
created_at
orseconds_to_resolve
.limit – The number of results to yield per page before requesting the next page. If unspecified,
default_page_size
will be used. The particular API endpoint permits values up to 1000.
- Yields:
Entries of the
data
property in the response body from each page
- iter_cursor(url: str, params: dict | None = None, item_hook: callable | None = None, page_size: int | None = None) Iterator[dict]
Iterator for results from an endpoint using cursor-based pagination.
- Parameters:
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
iter_all
for details on how this argument is used.page_size – Number of results per page of results (the
limit
parameter). If unspecified,default_page_size
will be used.
- Yields:
Results from each page of results.
- iter_history(url: str, since: datetime, until: datetime, recursion_depth: int = 0, **kw) Iterator[dict]
Yield all historical records from an endpoint in a given time interval.
This method works around the limitation of classic pagination (see
pagerduty.rest_api_v2_client.ITERATION_LIMIT
) by sub-dividing queries into lesser time intervals wherein the total number of results does not exceed the pagination limit.- Parameters:
url – Index endpoint (API URL) from which to yield results. In the event that a cursor-based pagination endpoint is given, this method calls
iter_cursor
directly, as cursor-based pagination has no such limitation.since – The beginning of the time interval. This must be a non-naïve datetime object (i.e. it must be timezone-aware), in order to format the
since
parameter when transmitting it to the API such that it unambiguously takes the time zone into account. See: datetime (Python documentation)until – The end of the time interval. A timezone-aware datetime object must be supplied for the same reason as for the
since
parameter.kw – Custom keyword arguments to pass to the iteration method. Note, if providing
params
in order to add query string parameters for filtering, thesince
anduntil
keys (if present) will be ignored.
- Yields:
All results from the resource collection API within the time range specified by
since
anduntil
.
- iter_incident_notes(incident_id: str | None = None, **kw) Iterator[dict]
Iterator for incident notes.
This is a filtered iterator for log entries of type
annotate_log_entry
.- Parameters:
incident_id – Optionally, request log entries for a specific incident. If included, the
team_ids[]
query parameter will be removed and ignored.kw – Custom keyword arguments to send to
iter_all
.
- Yields:
Incident note log entries as dictionary objects
- 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: str, **kw) list
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.- Parameters:
url – The index endpoint URL to use.
- normalize_params(params: dict) dict
Modify the user-supplied parameters to ease implementation
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 “[]”.
- Returns:
The query parameters after modification
- persist(resource: str, attr: str, values: dict, update: bool = False) dict
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).
- Parameters:
resource – 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 – 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 – 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 – (New in 4.4.0) If set to True, any existing resource will be updated with the values supplied.
- postprocess(response: Response, suffix: str | None = None)
Records performance information / request metadata about the API call.
- Parameters:
response (requests.Response) – The requests.Response object returned by the request method
suffix (str or None) – Optional suffix to append to the key
- prepare_headers(method: str, user_headers: dict | None = None) dict
Amends and combines default and user-supplied headers for a REST API request.
- Parameters:
method – The HTTP method
user_headers – Any user-supplied headers
- Returns:
A dictionary of the final headers to use in the request
- rdelete(resource, **kw)
Delete a resource.
- Parameters:
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.delete
- rget(resource, **kw)
Wrapped-entity-aware GET function.
Retrieves a resource via GET and returns the wrapped entity in the response.
- Parameters:
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.get
- Returns:
The API response after JSON-decoding and unwrapping
- rpatch(url, **kw)
Wrapped-entity-aware PATCH function.
Currently the only API endpoint that uses or supports this method is “Update Workflow Integration Connection”:
PATCH /workflows/integrations/{integration_id}/connections/{id}
It cannot use the
resource_url
decorator because the schema in that case has noself
property, and so the URL or path must be supplied.- Parameters:
path – The URL to be requested
kw – Keyword arguments to send to the request function, i.e.
params
- Returns:
The API response after JSON-decoding and unwrapping
- rpost(url, **kw)
Wrapped-entity-aware POST function.
Creates a resource and returns the created entity if successful.
- Parameters:
path – The path/URL to which to send the POST request, which should be an index endpoint.
**kw –
Custom keyword arguments to pass to
requests.Session.post
- Returns:
The API response after JSON-decoding and unwrapping
- rput(resource, **kw)
Wrapped-entity-aware PUT function.
Update an individual resource, returning the wrapped entity.
- Parameters:
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
- Returns:
The API response after JSON-decoding and unwrapping. In the case of at least one Teams API endpoint and any other future API endpoint that responds with 204 No Content, the return value will be None.
- property subdomain: str
Subdomain of the PagerDuty account of the API access token.
- property total_call_count: int
The total number of API calls made by this instance.
- property total_call_time: float
The total time spent making API calls.
- property trunc_token: str
Truncated API key for secure display/identification purposes.
- url = 'https://api.pagerduty.com'
Base URL of the REST API
- class pagerduty.EventsApiV2Client(api_key: str, debug: bool = False)
Session class for submitting events to the PagerDuty v2 Events API.
Implements methods for submitting events to PagerDuty through the Events API, including change events, and inherits from
pagerduty.ApiClient
. For more details on usage of this API, refer to the Events API v2 documentation- acknowledge(dedup_key: str) str
Acknowledge an alert via Events API.
- Parameters:
dedup_key – The deduplication key of the alert to set to the acknowledged state.
- Returns:
The deduplication key
- post(*args, **kw) Response
Override of
requests.Session.post
Adds the
routing_key
parameter to the body before sending.
- prepare_headers(method: str, user_headers: dict | None = None) dict
Add user agent and content type headers for Events API requests.
- Parameters:
user_headers – User-supplied headers that will override defaults
- Returns:
The final list of headers to use in the request
- resolve(dedup_key: str) str
Resolve an alert via Events API.
- Parameters:
dedup_key – The deduplication key of the alert to resolve.
- send_change_event(payload: dict | None = None, links: List[dict] | None = None, routing_key: str | None = None, images: List[dict] | None = None)
Send a change event to the v2 Change Events API.
See: https://developer.pagerduty.com/docs/events-api-v2/send-change-events/
- Parameters:
payload – A dictionary object with keys
summary
,source
,timestamp
andcustom_details
as described in the above documentation.links – A list of dictionary objects each with keys
href
andtext
representing the target and display text of each linkrouting_key – (Deprecated) the routing key. The parameter is set automatically to the
ApiClient.api_key
property in the final payload and this argument is ignored.images – Optional list of images to attach to the change event.
- send_event(action: str, dedup_key: str | None = None, **properties) str
Send an event to the v2 Events API.
See: https://v2.developer.pagerduty.com/docs/send-an-event-events-api-v2
- Parameters:
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
istrigger
this would includepayload
.
- Returns:
The deduplication key of the incident
- submit(summary: str, source: str | None = None, custom_details: dict | None = None, links: List[dict] | None = None, timestamp: str | None = None)
Submit a change event.
See: https://developer.pagerduty.com/docs/send-change-event
This is a wrapper method for
send_change_event
that composes an event payload from keyword arguments and an auto-generated event timestamp. To send an event with a wholly custom payload, usesend_change_event
instead.- Parameters:
summary (str) – Summary / brief description of the change, for
payload.summary
.source (str) – A human-readable name identifying the source of the change, for the
payload.source
event property.custom_details (dict) – A dictionary object to use as the
payload.custom_details
property.links (list) – A list of dict objects to use as the
links
property of the event.timestamp (str) – Specifies an event timestamp. Must be an ISO8601-format date/time.
- trigger(summary: str, source: str, dedup_key: str | None = None, severity: str = 'critical', payload: str | None = None, custom_details: dict | None = None, images: List[dict] | None = None, links: List[dict] | None = None) str
Send an alert-triggering event
- Parameters:
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 thepayload
parameter if given.images (list) – Set the
images
property of the event.links (list) – Set the
links
property of the event.
- Returns:
The deduplication key of the incident, if any.
Errors
- class pagerduty.Error(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 pagerduty.HttpError(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
Error
could also be used to denote such things as non-transient network errors wherein no response was received from the API. For instance, instead of this:try: user = session.rget('/users/PABC123') except pagerduty.Error as e: if e.response is not None: print("HTTP error: "+str(e.response.status_code)) else: raise e
one could write this:
try: user = session.rget('/users/PABC123') except pagerduty.HttpError as e: print("HTTP error: "+str(e.response.status_code))
- class pagerduty.ServerHttpError(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 pagerduty.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.
- pagerduty.rest_api_v2_client.CANONICAL_PATHS
Explicit list of supported canonical REST API v2 paths
- pagerduty.rest_api_v2_client.CURSOR_BASED_PAGINATION_PATHS
Explicit list of paths that support cursor-based pagination
- pagerduty.rest_api_v2_client.ENTITY_WRAPPER_CONFIG
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
pagerduty.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 bypagerduty.canonical_path
and included inpagerduty.rest_api_v2_client.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) orNone
(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.
- pagerduty.rest_api_v2_client.ITERATION_LIMIT = 10000
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 reproduced in the client to enable short-circuiting pagination, so that the client can avoid the HTTP 400 error that will result if the sum of the limit and offset parameters exceeds it.
See: Pagination.
- pagerduty.common.TEXT_LEN_LIMIT = 100
The longest permissible length of API content to include in error messages.
- pagerduty.api_client.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
ApiClient.timeout
to configure the timeout for a given session.
Functions
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.
- pagerduty.canonical_path(base_url: str, url: str) str
The canonical path from the API documentation 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
pagerduty.rest_api_v2.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).- Parameters:
base_url – The base URL of the API
url – A non-normalized URL (a path or full URL)
- Returns:
The canonical REST API v2 path corresponding to a URL.
- pagerduty.endpoint_matches(endpoint_pattern: str, method: str, path: str) bool
Whether an endpoint (method and canonical path) matches a given pattern
This is the filtering logic used for finding the appropriate entry in
pagerduty.rest_api_v2_client.ENTITY_WRAPPER_CONFIG
to use for a given method and API path.- Parameters:
endpoint_pattern – The endpoint pattern in the form
METHOD PATH
whereMETHOD
is the HTTP method in uppercase or*
to match all methods, andPATH
is a canonical API path.method – The HTTP method.
path – The canonical API path (i.e. as returned by
canonical_path()
)
- Returns:
True or False based on whether the pattern matches the endpoint
- pagerduty.is_path_param(path_node: str) bool
Whether a part of a canonical path represents a variable parameter
- Parameters:
path_node – The node (value between slashes) in the path
- Returns:
True if the node is an arbitrary variable, False if it is a fixed value
- pagerduty.normalize_url(base_url: str, url: str) str
Normalize a URL or path to be a complete API URL before query parameters.
The
url
argument may be a path relative to the base URL or a full URL.- Parameters:
url – The URL or path to normalize to a full URL.
base_url – The base API URL, excluding any trailing slash, i.e. “https://api.pagerduty.com”
- Returns:
The full API URL.
Entity Wrapping
Functions that implement entity wrapping logic.
- pagerduty.entity_wrappers(method: str, path: str) tuple
Obtains entity wrapping information for a given endpoint (path and method)
- Parameters:
method – The HTTP method
path – A canonical API path i.e. as returned by
canonical_path
- 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.
- pagerduty.infer_entity_wrapper(method: str, path: str) 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
pagerduty.rest_api_v2_client.ENTITY_WRAPPER_CONFIG
.- Parameters:
method – The HTTP method
path – A canonical API path i.e. from
pagerduty.rest_api_v2_client.CANONICAL_PATHS
- pagerduty.unwrap(response: Response, wrapper: str | None) dict | list
Unwraps a wrapped entity from a HTTP response.
- Parameters:
response – The response object.
wrapper – The entity wrapper (string), or None to skip unwrapping
- Returns:
The value associated with the wrapper key in the JSON-decoded body of the response, which is expected to be a dictionary (map).
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.
- pagerduty.auto_json(method: callable) callable
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.
- pagerduty.requires_success(method: callable) callable
Decorator that validates HTTP responses.
- pagerduty.resource_url(method: callable) callable
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.
- pagerduty.wrapped_entities(method: callable) callable
Automatically wrap request entities and unwrap response entities.
Used for methods
RestApiV2Client.rget
,RestApiV2Client.rpost
andRestApiV2Client.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 thejson
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 thejson
keyword argument will be normalized to include the wrapper.Methods using this decorator will raise a
HttpError
with itsresponse
property being being the requests.Response object in the case of any error (as of version 4.2 this is subclassed asHttpError
), so that the implementer can access it by catching the exception, and thus design their own custom logic around different types of error responses.- Parameters:
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.- Returns:
A callable object; the reformed method
Helpers
Miscellaneous functions
- pagerduty.deprecated_kwarg(deprecated_name: str, details: str | None = None, method: str | None = None)
Raises a warning if a deprecated keyword argument is used.
- Parameters:
deprecated_name – The name of the deprecated function
details – An optional message to append to the deprecation message
method – An optional method name
- pagerduty.http_error_message(r: Response, context: str | None = None) str
Formats a message describing a HTTP error.
- Parameters:
r – The response object.
context – A description of when the error was received, or None to not include it
- Returns:
The message to include in the HTTP error
- pagerduty.last_4(secret: str) str
Truncate a sensitive value to its last 4 characters
- Parameters:
secret – text to truncate
- Returns:
The truncated text
- pagerduty.plural_name(obj_type: str) str
Pluralizes a name, i.e. the API name from the
type
property- Parameters:
obj_type – The object type, i.e.
user
oruser_reference
- Returns:
The name of the resource, i.e. the last part of the URL for the resource’s index URL
- pagerduty.successful_response(r: Response, context: str | None = None) Response
Validates the response as successful.
Returns the response if it was successful; otherwise, raises an exception.
- Parameters:
r – Response object corresponding to the response received.
context – A description of when the HTTP request is happening, for error reporting
- Returns:
The response object, if it was successful
- pagerduty.truncate_text(text: str) str
Truncates a string longer than
pagerduty.common.TEXT_LEN_LIMIT
- Parameters:
text – The string to truncate if longer than the limit.
- pagerduty.try_decoding(r: Response) dict | list | str | None
JSON-decode a response body
Returns the decoded body if successful; raises
ServerHttpError
otherwise.- Parameters:
r – The response object