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 raisePDClientError
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¶
API Key property getter.
Returns the _api_key attribute’s value.
- 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
PDClientError
exception will be raised if this happens.
- normalize_params(params) 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
- normalize_url(url) 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)¶
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={}) 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, url, **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 pdpyras.APISession(api_key: str, 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
.- Parameters:
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
orbearer
.debug (bool) – Sets
print_debug
. Set to True to enable verbose command line output.
- Members:
- 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.
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: str, **kw) dict ¶
Dictionary representation of resource collection results
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.
- find(resource, query, attribute='name', params=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 (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 toemail
params (dict or None) – 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.
- iter_all(url, params=None, page_size=None, item_hook=None, total=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 (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 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 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[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
- 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) 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.
- 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).
- Parameters:
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:
dict
- postprocess(response: Response, suffix=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
- rdelete(resource, **kw)¶
Delete a resource.
- Parameters:
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.
- Parameters:
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
- Returns:
Dictionary representation of the requested object
- rpost(url, **kw)¶
Wrapped-entity-aware POST function.
Creates a resource and returns the created entity if successful.
- Parameters:
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
requests.Session.post
- Returns:
Dictionary representation of the created object
- 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:
Dictionary representation of the updated object
- property subdomain: str¶
Subdomain of the PagerDuty account of the API access token.
- Type:
str or None
- 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 token for secure display/identification purposes.
- url = 'https://api.pagerduty.com'¶
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 documentationInherits from
PDSession
.- acknowledge(dedup_key) 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, user_headers={}) 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 ¶
Resolve an alert via Events API.
- Parameters:
dedup_key – The deduplication key of the alert to resolve.
- send_event(action, dedup_key=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
- trigger(summary, source, dedup_key=None, severity='critical', payload=None, custom_details=None, images=None, links=None) str ¶
Trigger an incident
- 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.
- class pdpyras.ChangeEventsAPISession(api_key: str, debug=False)¶
Session class for submitting 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={}) dict ¶
Add user agent and content type headers for Change Events API requests.
- Parameters:
user_headers – User-supplied headers that will override defaults
- Returns:
The final list of headers to use in the request
- send_change_event(**properties)¶
Send a change event to the v2 Change Events API.
See: https://developer.pagerduty.com/docs/events-api-v2/send-change-events/
- Parameters:
**properties –
Properties to set, i.e.
payload
andlinks
- Returns:
The response ID
- submit(summary, source=None, custom_details=None, links=None, timestamp=None) str ¶
Submit an incident change
- Parameters:
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.
- Returns:
The response ID
Errors¶
- 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:
try: user = session.rget('/users/PABC123') except pdpyras.PDClientError 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 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.
- pdpyras.CANONICAL_PATHS¶
Explicit list of supported canonical REST API v2 paths
- pdpyras.CURSOR_BASED_PAGINATION_PATHS¶
Explicit list of paths that support cursor-based pagination
- pdpyras.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
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 bycanonical_path
and included inCANONICAL_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.
- 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.
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.
- pdpyras.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
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.
- pdpyras.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
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
- pdpyras.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
- pdpyras.normalize_url(base_url: str, url: str) 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.- Parameters:
url – The URL to normalize
baseurl – The base API URL, excluding any trailing slash, i.e. “https://api.pagerduty.com”
- Returns:
The full API endpoint URL
Entity Wrapping¶
Functions that implement entity wrapping logic.
- pdpyras.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.
- pdpyras.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
ENTITY_WRAPPER_CONFIG
.- Parameters:
method – The HTTP method
path – A canonical API path i.e. as returned by
canonical_path
- pdpyras.unwrap(response: Response, wrapper) dict | list ¶
Unwraps a wrapped entity.
- Parameters:
response – The response object
wrapper (str or None) – The entity wrapper
- 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.
- pdpyras.auto_json(method)¶
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.
- pdpyras.requires_success(method)¶
Decorator that validates HTTP responses.
- pdpyras.resource_url(method)¶
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.
- pdpyras.wrapped_entities(method)¶
Automatically wrap request entities and unwrap response entities.
Used for methods
APISession.rget
,APISession.rpost
andAPISession.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
PDHTTPError
with itsresponse
property being being the requests.Response object in the case of any error (as of version 4.2 this is subclassed asPDHTTPError
), 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
- pdpyras.deprecated_kwarg(deprecated_name: str, details=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
- pdpyras.http_error_message(r: Response, context=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
- pdpyras.last_4(secret: str) str ¶
Truncate a sensitive value to its last 4 characters
- Parameters:
secret – text to truncate
- Returns:
The truncated text
- pdpyras.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
- pdpyras.successful_response(r: Response, context=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
- pdpyras.truncate_text(text: str) str ¶
Truncates a string longer than
TEXT_LEN_LIMIT
- Parameters:
text – The string to truncate if longer than the limit.
- pdpyras.try_decoding(r: Response) dict | list | str ¶
JSON-decode a response body
Returns the decoded body if successful; raises
PDServerError
otherwise.- Parameters:
r – The response object