Practical Example: Querying Real-Time Monitoring Alerts
π·οΈ APIs and HTTP Requests / JSON Responses
π§ Context Introduction
Monitoring systems generate alerts when something goes wrongβlike a server going down, high CPU usage, or disk space running low. As an engineer, you often need to pull these alerts programmatically to check system health, build dashboards, or trigger automated responses. In this example, we'll use Python to query a real-time monitoring API and work with the JSON response it returns.
βοΈ What We Are Building
We will write a Python script that:
- Connects to a monitoring system's API endpoint
- Sends a request to fetch current alerts
- Parses the JSON response
- Displays the alerts in a readable format
This mimics what you might do with tools like Prometheus, Datadog, Grafana, or a custom monitoring platform.
π οΈ Key Concepts Before We Start
- API Endpoint: A URL where the monitoring system listens for requests
- HTTP GET Request: Used to retrieve data from the API
- JSON Response: The data format returned by most modern APIsβstructured as key-value pairs
- Authentication: Some APIs require a token or key to verify your identity
- Status Codes: HTTP codes like 200 (success) or 401 (unauthorized) tell you if the request worked
π Step-by-Step Breakdown
1οΈβ£ Import Required Libraries
You need the requests library to make HTTP calls and json (built-in) to handle the response. If requests is not installed, you can add it using pip install requests.
2οΈβ£ Define the API Endpoint and Headers
Create a variable for the API URL. If authentication is required, include an Authorization header with your API token. For example:
- api_url = "https://monitoring.example.com/api/v1/alerts"
- headers = {"Authorization": "Bearer YOUR_API_TOKEN_HERE"}
3οΈβ£ Send the GET Request
Use the requests.get() method with the URL and headers. Store the result in a variable like response.
4οΈβ£ Check the Response Status
Before processing data, verify the request succeeded. Check response.status_code equals 200. If not, print an error message and stop.
5οΈβ£ Parse the JSON Data
Use response.json() to convert the JSON response into a Python dictionary or list. This makes it easy to access specific fields.
6οΈβ£ Extract and Display Alerts
Loop through the alerts in the parsed data. For each alert, print relevant details such as:
- Alert name or ID
- Severity level (critical, warning, info)
- Timestamp
- Description or message
π΅οΈ Example Script Logic (Without Code Blocks)
Here is how the script logic flows in plain text:
Step 1: Import the requests library.
Step 2: Set the api_url variable to the monitoring endpoint.
Step 3: Set the headers dictionary with your API token.
Step 4: Call requests.get(api_url, headers=headers) and assign the result to response.
Step 5: Check if response.status_code equals 200. If not, print "Failed to fetch alerts. Status code: [code]".
Step 6: Parse the JSON using alerts_data = response.json().
Step 7: Assume the JSON structure contains a key called "alerts" which is a list. Loop through each alert in alerts_data["alerts"].
Step 8: For each alert, print the name, severity, timestamp, and message fields.
Expected Output Example (formatted inline):
- Alert: CPU Overload | Severity: Critical | Time: 2025-03-15 14:32:10 | Message: CPU usage exceeded 95%
- Alert: Disk Space Low | Severity: Warning | Time: 2025-03-15 14:28:45 | Message: /dev/sda1 at 88% capacity
- Alert: Service Down | Severity: Critical | Time: 2025-03-15 14:15:00 | Message: nginx service not responding
π Comparison Table: Common JSON Fields in Monitoring Alerts
| Field Name | Description | Example Value |
|---|---|---|
| id | Unique identifier for the alert | "alert-12345" |
| name | Short title of the alert | "High CPU Usage" |
| severity | How critical the alert is | "critical", "warning", "info" |
| timestamp | When the alert was triggered | "2025-03-15T14:32:10Z" |
| message | Detailed description | "CPU usage at 97% for 5 minutes" |
| source | Which system generated the alert | "server-01", "aws-east-1" |
| status | Current state of the alert | "active", "acknowledged", "resolved" |
π§ͺ Testing and Validation Tips
- Start by testing the API endpoint directly in your browser or a tool like Postman to see the raw JSON structure
- If you get a 401 error, your token may be expired or incorrect
- If you get a 404, double-check the URL path
- Print the raw response.text first to see what the API actually returns before parsing JSON
- Handle cases where the JSON structure differs from what you expect (e.g., missing keys)
π Next Steps for Engineers
Once you can fetch alerts, consider extending the script to:
- Filter alerts by severity (e.g., only show critical ones)
- Send notifications via email or Slack when new critical alerts appear
- Save alerts to a file or database for historical analysis
- Build a simple dashboard that refreshes every minute
- Combine alerts from multiple monitoring systems into one view
β Summary
Querying real-time monitoring alerts with Python is a practical skill that helps you automate infrastructure health checks. By making an HTTP GET request, parsing the JSON response, and extracting key fields, you can quickly turn raw API data into actionable information. This pattern applies to almost any modern monitoring tool and is a foundation for building more advanced automation and observability workflows.
This example shows how to fetch and process real-time monitoring alerts from an API endpoint using Python.
π’ Example 1: Fetching a single alert from a monitoring API
This demonstrates the simplest way to request one alert record from a monitoring system.
import requests
response = requests.get("https://api.monitoring.example.com/alerts/1")
alert = response.json()
print(alert)
π€ Output: {'id': 1, 'severity': 'critical', 'message': 'CPU usage above 95%', 'timestamp': '2024-03-15T10:30:00Z'}
π‘ Example 2: Fetching all active alerts
This shows how to retrieve a list of all currently active alerts from the monitoring system.
import requests
response = requests.get("https://api.monitoring.example.com/alerts?status=active")
alerts = response.json()
print(alerts)
π€ Output: [{'id': 1, 'severity': 'critical', 'message': 'CPU usage above 95%'}, {'id': 2, 'severity': 'warning', 'message': 'Disk space at 80%'}]
π΅ Example 3: Filtering alerts by severity level
This demonstrates how to request only critical alerts from the monitoring API.
import requests
response = requests.get("https://api.monitoring.example.com/alerts?severity=critical")
critical_alerts = response.json()
print(critical_alerts)
π€ Output: [{'id': 1, 'severity': 'critical', 'message': 'CPU usage above 95%'}, {'id': 3, 'severity': 'critical', 'message': 'Memory leak detected'}]
π£ Example 4: Counting alerts by severity
This shows how to process the JSON response to count how many alerts exist for each severity level.
import requests
response = requests.get("https://api.monitoring.example.com/alerts")
alerts = response.json()
critical_count = 0
warning_count = 0
info_count = 0
for alert in alerts:
if alert["severity"] == "critical":
critical_count = critical_count + 1
elif alert["severity"] == "warning":
warning_count = warning_count + 1
else:
info_count = info_count + 1
print(critical_count)
print(warning_count)
print(info_count)
π€ Output: 3 5 2
π΄ Example 5: Extracting alert messages for a specific time window
This demonstrates how to fetch alerts from the last hour and print only their messages.
import requests
from datetime import datetime, timedelta
one_hour_ago = datetime.utcnow() - timedelta(hours=1)
response = requests.get("https://api.monitoring.example.com/alerts?since=" + one_hour_ago.isoformat())
recent_alerts = response.json()
for alert in recent_alerts:
print(alert["message"])
π€ Output: CPU usage above 95%
Disk space at 80%
Network latency spike detected
Comparison Table
| Example | What It Does | Key Concept |
|---|---|---|
| Example 1 | Fetches a single alert | Basic GET request + JSON parse |
| Example 2 | Fetches all active alerts | Query parameter filtering |
| Example 3 | Filters by severity | URL parameter filtering |
| Example 4 | Counts alerts by severity | JSON list iteration |
| Example 5 | Extracts messages by time | Date filtering + field extraction |
π§ Context Introduction
Monitoring systems generate alerts when something goes wrongβlike a server going down, high CPU usage, or disk space running low. As an engineer, you often need to pull these alerts programmatically to check system health, build dashboards, or trigger automated responses. In this example, we'll use Python to query a real-time monitoring API and work with the JSON response it returns.
βοΈ What We Are Building
We will write a Python script that:
- Connects to a monitoring system's API endpoint
- Sends a request to fetch current alerts
- Parses the JSON response
- Displays the alerts in a readable format
This mimics what you might do with tools like Prometheus, Datadog, Grafana, or a custom monitoring platform.
π οΈ Key Concepts Before We Start
- API Endpoint: A URL where the monitoring system listens for requests
- HTTP GET Request: Used to retrieve data from the API
- JSON Response: The data format returned by most modern APIsβstructured as key-value pairs
- Authentication: Some APIs require a token or key to verify your identity
- Status Codes: HTTP codes like 200 (success) or 401 (unauthorized) tell you if the request worked
π Step-by-Step Breakdown
1οΈβ£ Import Required Libraries
You need the requests library to make HTTP calls and json (built-in) to handle the response. If requests is not installed, you can add it using pip install requests.
2οΈβ£ Define the API Endpoint and Headers
Create a variable for the API URL. If authentication is required, include an Authorization header with your API token. For example:
- api_url = "https://monitoring.example.com/api/v1/alerts"
- headers = {"Authorization": "Bearer YOUR_API_TOKEN_HERE"}
3οΈβ£ Send the GET Request
Use the requests.get() method with the URL and headers. Store the result in a variable like response.
4οΈβ£ Check the Response Status
Before processing data, verify the request succeeded. Check response.status_code equals 200. If not, print an error message and stop.
5οΈβ£ Parse the JSON Data
Use response.json() to convert the JSON response into a Python dictionary or list. This makes it easy to access specific fields.
6οΈβ£ Extract and Display Alerts
Loop through the alerts in the parsed data. For each alert, print relevant details such as:
- Alert name or ID
- Severity level (critical, warning, info)
- Timestamp
- Description or message
π΅οΈ Example Script Logic (Without Code Blocks)
Here is how the script logic flows in plain text:
Step 1: Import the requests library.
Step 2: Set the api_url variable to the monitoring endpoint.
Step 3: Set the headers dictionary with your API token.
Step 4: Call requests.get(api_url, headers=headers) and assign the result to response.
Step 5: Check if response.status_code equals 200. If not, print "Failed to fetch alerts. Status code: [code]".
Step 6: Parse the JSON using alerts_data = response.json().
Step 7: Assume the JSON structure contains a key called "alerts" which is a list. Loop through each alert in alerts_data["alerts"].
Step 8: For each alert, print the name, severity, timestamp, and message fields.
Expected Output Example (formatted inline):
- Alert: CPU Overload | Severity: Critical | Time: 2025-03-15 14:32:10 | Message: CPU usage exceeded 95%
- Alert: Disk Space Low | Severity: Warning | Time: 2025-03-15 14:28:45 | Message: /dev/sda1 at 88% capacity
- Alert: Service Down | Severity: Critical | Time: 2025-03-15 14:15:00 | Message: nginx service not responding
π Comparison Table: Common JSON Fields in Monitoring Alerts
| Field Name | Description | Example Value |
|---|---|---|
| id | Unique identifier for the alert | "alert-12345" |
| name | Short title of the alert | "High CPU Usage" |
| severity | How critical the alert is | "critical", "warning", "info" |
| timestamp | When the alert was triggered | "2025-03-15T14:32:10Z" |
| message | Detailed description | "CPU usage at 97% for 5 minutes" |
| source | Which system generated the alert | "server-01", "aws-east-1" |
| status | Current state of the alert | "active", "acknowledged", "resolved" |
π§ͺ Testing and Validation Tips
- Start by testing the API endpoint directly in your browser or a tool like Postman to see the raw JSON structure
- If you get a 401 error, your token may be expired or incorrect
- If you get a 404, double-check the URL path
- Print the raw response.text first to see what the API actually returns before parsing JSON
- Handle cases where the JSON structure differs from what you expect (e.g., missing keys)
π Next Steps for Engineers
Once you can fetch alerts, consider extending the script to:
- Filter alerts by severity (e.g., only show critical ones)
- Send notifications via email or Slack when new critical alerts appear
- Save alerts to a file or database for historical analysis
- Build a simple dashboard that refreshes every minute
- Combine alerts from multiple monitoring systems into one view
β Summary
Querying real-time monitoring alerts with Python is a practical skill that helps you automate infrastructure health checks. By making an HTTP GET request, parsing the JSON response, and extracting key fields, you can quickly turn raw API data into actionable information. This pattern applies to almost any modern monitoring tool and is a foundation for building more advanced automation and observability workflows.
Interactive Views
You are currently in π All-in-One mode. Use the tabs at the top to switch to π Theory Only or π» Code Only views.
This example shows how to fetch and process real-time monitoring alerts from an API endpoint using Python.
π’ Example 1: Fetching a single alert from a monitoring API
This demonstrates the simplest way to request one alert record from a monitoring system.
import requests
response = requests.get("https://api.monitoring.example.com/alerts/1")
alert = response.json()
print(alert)
π€ Output: {'id': 1, 'severity': 'critical', 'message': 'CPU usage above 95%', 'timestamp': '2024-03-15T10:30:00Z'}
π‘ Example 2: Fetching all active alerts
This shows how to retrieve a list of all currently active alerts from the monitoring system.
import requests
response = requests.get("https://api.monitoring.example.com/alerts?status=active")
alerts = response.json()
print(alerts)
π€ Output: [{'id': 1, 'severity': 'critical', 'message': 'CPU usage above 95%'}, {'id': 2, 'severity': 'warning', 'message': 'Disk space at 80%'}]
π΅ Example 3: Filtering alerts by severity level
This demonstrates how to request only critical alerts from the monitoring API.
import requests
response = requests.get("https://api.monitoring.example.com/alerts?severity=critical")
critical_alerts = response.json()
print(critical_alerts)
π€ Output: [{'id': 1, 'severity': 'critical', 'message': 'CPU usage above 95%'}, {'id': 3, 'severity': 'critical', 'message': 'Memory leak detected'}]
π£ Example 4: Counting alerts by severity
This shows how to process the JSON response to count how many alerts exist for each severity level.
import requests
response = requests.get("https://api.monitoring.example.com/alerts")
alerts = response.json()
critical_count = 0
warning_count = 0
info_count = 0
for alert in alerts:
if alert["severity"] == "critical":
critical_count = critical_count + 1
elif alert["severity"] == "warning":
warning_count = warning_count + 1
else:
info_count = info_count + 1
print(critical_count)
print(warning_count)
print(info_count)
π€ Output: 3 5 2
π΄ Example 5: Extracting alert messages for a specific time window
This demonstrates how to fetch alerts from the last hour and print only their messages.
import requests
from datetime import datetime, timedelta
one_hour_ago = datetime.utcnow() - timedelta(hours=1)
response = requests.get("https://api.monitoring.example.com/alerts?since=" + one_hour_ago.isoformat())
recent_alerts = response.json()
for alert in recent_alerts:
print(alert["message"])
π€ Output: CPU usage above 95%
Disk space at 80%
Network latency spike detected
Comparison Table
| Example | What It Does | Key Concept |
|---|---|---|
| Example 1 | Fetches a single alert | Basic GET request + JSON parse |
| Example 2 | Fetches all active alerts | Query parameter filtering |
| Example 3 | Filters by severity | URL parameter filtering |
| Example 4 | Counts alerts by severity | JSON list iteration |
| Example 5 | Extracts messages by time | Date filtering + field extraction |