PagerDuty Python Client
The `pagerduty` library provides lightweight Python clients for PagerDuty's REST API v2 and Events API v2, built on top of the `httpx` HTTP client. It is the official and actively maintained successor to the `pdpyras` library, offering features like connection pooling, authentication, pagination, and configurable retry logic. The current version is 6.2.1, with a regular release cadence addressing bug fixes, new features, and API endpoint support.
Warnings
- breaking The `pdpyras` library has been deprecated and replaced by `python-pagerduty` (installed as `pagerduty`). This involves a module rename (e.g., `import pdpyras` becomes `import pagerduty`) and significant class renames (e.g., `pdpyras.APISession` is now `pagerduty.RestApiV2Client`, `pdpyras.EventsAPISession` is now `pagerduty.EventsApiV2Client`). Projects should migrate to the new library and its updated class names.
- breaking Version 6.0.0 switched the underlying HTTP client from `requests` to `httpx`. While the developer interface is largely similar, this change introduces breaking changes, particularly in how the client is configured to use a proxy server.
- gotcha When using an account-level PagerDuty API key (created by an administrator), certain API actions, especially those that take action on incidents (e.g., acknowledge, resolve), require a `From` header. This header's value must be the email address of a valid PagerDuty user, otherwise, requests may result in an HTTP 400 error.
- gotcha For PagerDuty accounts located in the EU service region, the API URL might need to be explicitly configured. While v6.2.0 introduced improvements for supporting EU regions, older versions or specific configurations might still require setting the `api_url` parameter during client initialization to the appropriate EU endpoint (e.g., `https://api.eu.pagerduty.com`).
Install
-
pip install pagerduty
Imports
- RestApiV2Client
from pagerduty import RestApiV2Client
- EventsApiV2Client
from pagerduty import EventsApiV2Client
Quickstart
import os
from pagerduty import RestApiV2Client
# PagerDuty API Key (recommended: user-scoped or service-specific key)
PAGERDUTY_API_KEY = os.environ.get('PAGERDUTY_API_KEY', 'YOUR_PAGERDUTY_API_KEY')
# 'From' email header is required for some actions (e.g., resolving incidents)
# when using an account-level API key.
PAGERDUTY_FROM_EMAIL = os.environ.get('PAGERDUTY_FROM_EMAIL', 'your_user@example.com')
if not PAGERDUTY_API_KEY or PAGERDUTY_API_KEY == 'YOUR_PAGERDUTY_API_KEY':
print("Error: PAGERDUTY_API_KEY environment variable not set or placeholder used.")
exit(1)
try:
# Initialize the REST API client
# For account-level API keys, pass default_from for actions requiring a 'From' header
client = RestApiV2Client(PAGERDUTY_API_KEY, default_from=PAGERDUTY_FROM_EMAIL)
# Example: List users
print("Fetching PagerDuty users...")
users_response = client.get('/users')
if users_response.is_success:
users = users_response.json().get('users', [])
for user in users:
print(f"User ID: {user['id']}, Name: {user['name']}, Email: {user['email']}")
print(f"Successfully fetched {len(users)} users.")
else:
print(f"Error fetching users: {users_response.status_code} - {users_response.text}")
# Example: Create an incident (requires a service API key, not account-level)
# This example requires a valid `service_id` and `from` email and a user with permissions
# incident_data = {
# "incident": {
# "type": "incident",
# "title": "Test Incident from Python Client",
# "service": {"id": "PXXXXXX", "type": "service_reference"},
# "priority": {"id": "PXXXXXX", "type": "priority_reference"}, # Optional
# "body": {"type": "text", "details": "This is a test incident created via the Python client."}
# }
# }
# create_incident_response = client.post('/incidents', json=incident_data, headers={'From': PAGERDUTY_FROM_EMAIL})
# if create_incident_response.is_success:
# print(f"Incident created: {create_incident_response.json()['incident']['id']}")
# else:
# print(f"Error creating incident: {create_incident_response.status_code} - {create_incident_response.text}")
except Exception as e:
print(f"An error occurred: {e}")