Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 15 / Topic 6 of 6

Putting it together: route webhook events with match

Real-world example: a payment provider sends webhook events: small JSON messages like "payment succeeded" or "refund issued", posted to your server as they happen. Once parsed (Part 8), a webhook event is a plain dict. TypedDict describes the shape of each event kind for mypy; match picks the right handler at run time, using the "type" key and the shape of the rest of the dict. This replaces a long if event["type"] == ...: elif ... chain with one readable block.

from typing import Literal, TypedDict

class PaymentSucceeded(TypedDict):
    type: Literal["payment.succeeded"]
    order_id: str
    amount: float

class RefundIssued(TypedDict):
    type: Literal["refund.issued"]
    order_id: str
    amount: float
    partial: bool

WebhookEvent = PaymentSucceeded | RefundIssued   # a "discriminated union"

def handle_event(event: WebhookEvent) -> str:
    match event:
        case {"type": "payment.succeeded", "order_id": order_id, "amount": amount}:
            return f"Order {order_id}: payment received, ₹{amount:,.2f}"
        case {"type": "refund.issued", "order_id": order_id, "amount": amount, "partial": True}:
            return f"Order {order_id}: partial refund of ₹{amount:,.2f}"
        case {"type": "refund.issued", "order_id": order_id, "amount": amount, "partial": False}:
            return f"Order {order_id}: full refund of ₹{amount:,.2f}"
        case {"type": event_type}:
            return f"Unhandled event type: {event_type}"
        case _:
            return "Malformed event: missing 'type'"

Output for a mixed batch (full list in the example file):

Order ORD-101: payment received, ₹1,760.00
Order ORD-102: payment failed (card_declined)
Order ORD-103: partial refund of ₹500.00
Order ORD-104: full refund of ₹1,299.00
Customer CUST-9: annual plan renewed, ₹4,999.00
Customer CUST-3: monthly plan renewed, ₹499.00
Unhandled event type: refund.requested
Malformed event: missing 'type'

Every member of WebhookEvent shares the "type" key: that is what makes it a discriminated union. match checks "type" first in each case, so an event never falls into the wrong handler just because it happens to share a field name (order_id, amount) with another kind. The two catch-all cases keep the router honest: a known-but-unhandled type ("refund.requested") is reported differently from an event with no "type" at all (someone sent you the wrong kind of message, or a ping).

Full program: examples/06_webhook_router.py.

Exercise 6: Route food-delivery webhook events, then summarise a batch

Scenario: A food-delivery app's webhook sends events like order.placed, order.cancelled and delivery.completed. You need a router (one handler per event shape), plus a quick count of how many events of each type arrived. What to do: Inside main():

  1. Write TypedDicts OrderPlaced (type: Literal["order.placed"], order_id: str, amount: float), OrderCancelled (type: Literal["order.cancelled"], order_id: str, reason: str), DeliveryCompleted (type: Literal["delivery.completed"], order_id: str, rating: NotRequired[int]).
  2. Write handle_event(event) -> str with a match on the "type" key:
    • "order.placed" → f"Order {order_id}: placed, ₹{amount:,.2f}"
    • "order.cancelled" → f"Order {order_id}: cancelled ({reason})"
    • "delivery.completed" with a rating that is <= 2 (guard) → f"Order {order_id}: delivered, rating {rating} -- needs follow-up"
    • "delivery.completed" with any other rating → f"Order {order_id}: delivered, rating {rating}"
    • "delivery.completed" with no rating key → f"Order {order_id}: delivered, no rating yet"
    • any other known "type" → f"Unhandled event type: {event_type}"
    • no "type" key at all → "Malformed event: missing 'type'"
  3. Write summarize(events: list[dict]) -> dict[str, int] returning a dict of event type (or "unknown" if missing) to count, sorted by key, using collections.Counter.
  4. Run both functions over:
    EVENTS = [
        {"type": "order.placed", "order_id": "FD-1", "amount": 349.0},
        {"type": "order.cancelled", "order_id": "FD-2", "reason": "restaurant_closed"},
        {"type": "delivery.completed", "order_id": "FD-1", "rating": 5},
        {"type": "delivery.completed", "order_id": "FD-3", "rating": 2},
        {"type": "delivery.completed", "order_id": "FD-4"},
        {"type": "payment.refunded", "order_id": "FD-2"},
    ]
    
    printing handle_event(event) for each event, then summarize(EVENTS).

Sample output:

Order FD-1: placed, ₹349.00
Order FD-2: cancelled (restaurant_closed)
Order FD-1: delivered, rating 5
Order FD-3: delivered, rating 2 -- needs follow-up
Order FD-4: delivered, no rating yet
Unhandled event type: payment.refunded
{'delivery.completed': 3, 'order.cancelled': 1, 'order.placed': 1, 'payment.refunded': 1}

💡 Hint: put the rating <= 2 guard case before the plain rating case, and the "no rating key" case after both -- match tries cases top to bottom and stops at the first one that fits.

Show the solution to Exercise 6
"""Exercise 6: Route food-delivery webhook events with match, and summarise a batch.

Shows: TypedDict-shaped events, match as a dispatcher, a guard, Counter.

Run:   python ex06.py   (macOS/Linux: python3 ex06.py)
"""

from collections import Counter
from typing import Literal, NotRequired, TypedDict


class OrderPlaced(TypedDict):
    type: Literal["order.placed"]
    order_id: str
    amount: float


class OrderCancelled(TypedDict):
    type: Literal["order.cancelled"]
    order_id: str
    reason: str


class DeliveryCompleted(TypedDict):
    type: Literal["delivery.completed"]
    order_id: str
    rating: NotRequired[int]


WebhookEvent = OrderPlaced | OrderCancelled | DeliveryCompleted


def handle_event(event: WebhookEvent) -> str:
    match event:
        case {"type": "order.placed", "order_id": order_id, "amount": amount}:
            return f"Order {order_id}: placed, ₹{amount:,.2f}"
        case {"type": "order.cancelled", "order_id": order_id, "reason": reason}:
            return f"Order {order_id}: cancelled ({reason})"
        case {"type": "delivery.completed", "order_id": order_id, "rating": rating} if rating <= 2:
            return f"Order {order_id}: delivered, rating {rating} -- needs follow-up"
        case {"type": "delivery.completed", "order_id": order_id, "rating": rating}:
            return f"Order {order_id}: delivered, rating {rating}"
        case {"type": "delivery.completed", "order_id": order_id}:
            return f"Order {order_id}: delivered, no rating yet"
        case {"type": event_type}:
            return f"Unhandled event type: {event_type}"
        case _:
            return "Malformed event: missing 'type'"


def summarize(events: list[dict]) -> dict[str, int]:
    counts = Counter(event.get("type", "unknown") for event in events)
    return dict(sorted(counts.items()))


EVENTS: list[dict] = [
    {"type": "order.placed", "order_id": "FD-1", "amount": 349.0},
    {"type": "order.cancelled", "order_id": "FD-2", "reason": "restaurant_closed"},
    {"type": "delivery.completed", "order_id": "FD-1", "rating": 5},
    {"type": "delivery.completed", "order_id": "FD-3", "rating": 2},
    {"type": "delivery.completed", "order_id": "FD-4"},
    {"type": "payment.refunded", "order_id": "FD-2"},
]


def main() -> None:
    for event in EVENTS:
        print(handle_event(event))  # type: ignore[arg-type]  -- real events validate first
    print(summarize(EVENTS))


if __name__ == "__main__":
    main()

Search the guide