API, MailHog, Logging &
Exception-Handling Guide
Reliable Helpdesk Workflows • Verified Notifications • Secure Logs • Bounded Recovery
Edition September -2027
Format Concept guide + reusable patterns + 12 guided exercises + solutions
Workflow Detect → validate → remediate → verify → ticket → notify → audit → rerun
Focus Correctness, security, observability, and repeatability
Alignment boundary: This is an independently created D522 course-support guide, not an official WGU rubric, assessment, or
completed submission. Confirm the current lab URL, HTTP method, authentication, JSON schema, SMTP host/port, recipient,
approved DNS baseline, filenames, and evidence requirements inside your own course environment. Generic examples must never
replace course-provided values.
Independent course-support resource | September 2026 Page 1
,WGU D522 | API, MailHog, Logging & Exception Handling
1. How the Components Fit Together
Task 2 extends the discovery/audit logic from Task 1. A defensible automation does not jump from detection to a success
message. It preserves state, performs only an authorized correction, independently reads the live state again, records the result
through the approved Helpdesk API, sends a notification through the lab SMTP service, and creates a traceable audit record.
Component Input Success output Failure boundary
Audit/detection Live device state + Structured compliance result Do not remediate on ambiguous state
approved baseline
Remediation Verified noncompliance + Change attempt result Never claim success from write alone
preserved state
Validation Fresh post-change live Verified expected value Rollback/recovery if required
read
Helpdesk API Verified result + Ticket ID/status Classify HTTP and transport failures
deterministic key
MailHog/email Verified result + ticket Delivered message visible in lab Separate send failure from remediation
reference UI
Logging/audit Events from every stage One-run trace Never log secrets
Golden rule
Notification and ticket status must be driven by verified outcomes. A script that reports “fixed” before a fresh live validation can
create false evidence and misleading downstream records.
Suggested result model
from dataclasses import dataclass
@dataclass(frozen=True)
class DeviceResult:
device_id: str
expected_dns: str
before_dns: str | None
change_attempted: bool
after_dns: str | None
verified: bool
ticket_id: str | None = None
email_sent: bool = False
error_code: str | None = None
Independent course-support resource | September 2026 Page 2
, WGU D522 | API, MailHog, Logging & Exception Handling
2. API Foundations for the Helpdesk Workflow
2.1 Request contract
Treat every API call as a contract: method, URL, authentication, headers, timeout, request body, expected status, response
schema, and side-effect rules must all be explicit.
Contract item Question to answer
Method Does the lab require POST, PUT, PATCH, or another method?
URL What exact supplied base URL and path are authorized?
Authentication Which supplied token/header method is required?
Payload Which fields, types, and permitted values are required?
Timeout How long may connection and response waits last?
Response Which status codes and JSON fields prove success?
Idempotence How are duplicate records prevented on rerun?
2.2 A bounded request wrapper
from __future__ import annotations
import requests
class HelpdeskError(RuntimeError):
pass
def create_ticket(base_url: str, token: str, payload: dict,
timeout: tuple[float, float] = (3.05, 10.0)) -> str:
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/json",
"Content-Type": "application/json",
}
try:
response = requests.post(
f"{base_url.rstrip('/')}/tickets",
headers=headers,
json=payload,
timeout=timeout,
)
response.raise_for_status()
except requests.Timeout as exc:
raise HelpdeskError("helpdesk timeout") from exc
except requests.ConnectionError as exc:
raise HelpdeskError("helpdesk connection failure") from exc
except requests.HTTPError as exc:
status = exc.response.status_code if exc.response is not None else None
raise HelpdeskError(f"helpdesk HTTP failure: {status}") from exc
try:
ticket_id = response.json()["id"]
except (ValueError, KeyError, TypeError) as exc:
raise HelpdeskError("invalid helpdesk success response") from exc
return str(ticket_id)
The tuple timeout separates connection and read limits. Use values allowed by the lab. Never omit a timeout from network
automation.
Independent course-support resource | September 2026 Page 3