Automating with APIs and Webhooks
Most automation today means making services talk to each other: post to Slack when a payment arrives, create an invoice when a contract is signed, sync users to a newsletter.
Calling an API with Python
import os
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['API_TOKEN']}"
session.mount("https://", HTTPAdapter(max_retries=Retry(
total=4, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET", "POST"],
)))
resp = session.get("https://api.example.com/v1/orders", params={"status": "paid"}, timeout=15)
resp.raise_for_status()
for order in resp.json()["data"]:
print(order["id"], order["total"])
- Always set a timeout; without one, a stuck connection hangs your job forever.
- Retry with backoff on rate limits (429) and server errors (5xx), not on 4xx client errors.
- Handle pagination: loop while the response includes a
nextcursor.
Sending a notification
requests.post(os.environ["SLACK_WEBHOOK_URL"], json={"text": "Backup completed"}, timeout=10)
Receiving webhooks
A webhook is an API calling you when something happens (Stripe payment succeeded, GitHub push). Rules for a safe receiver:
- Verify the signature. Anyone can POST to your URL. Providers sign the body with a shared secret.
- Respond fast (under a few seconds) and do slow work in the background.
- Be idempotent. Providers retry, so the same event can arrive twice. Store event IDs and skip duplicates.
import hmac, hashlib
def verify(body: bytes, header_sig: str, secret: str) -> bool:
expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, header_sig)
compare_digest avoids timing attacks. For Stripe, use its library: stripe.Webhook.construct_event(payload, sig_header, secret).
No-code and low-code options
Zapier, Make and n8n (self-hostable) connect hundreds of apps without code. They are perfect for business workflows like "new form submission → CRM → welcome email". Write code when you need custom logic, high volume or tight security.
Exercise
Write a script that fetches your public GitHub repositories with the GitHub REST API (/users/<name>/repos), handles pagination, and posts a summary of the five most recently updated ones to a Slack or Discord webhook.
I tuoi progressi sono salvati solo in questo browser.
Invia per la revisione (10 punti)