A client that mirrors live positions, streams events and pulls a nightly report. Pseudocode, but every call is one verified above.
import os, requests, time
BASE = "https://myfleet.sawatelematics.com/api"
# ── 1. authenticate: one key, in the header, from your secret store ─────
S = requests.Session()
S.headers["Authorization"] = f"Bearer {os.environ['SAWA_API_KEY']}" # sk_live_…
S.headers["Accept-Encoding"] = "gzip"
# ── 2. live positions, every 10s ─────────────────────────────────────────
def positions():
r = S.get(f"{BASE}/get_devices_latest", timeout=60)
r.raise_for_status()
for v in r.json()["items"]:
yield {
"vehicle_id": v["id"],
"plate": v["plate_number"],
"lat": v["lat"],
"lng": v["lng"],
"speed_kph": v["speed"],
"status": v["online"], # online | ack | offline
"fixed_at": v["timestamp"], # Unix UTC — never parse v["time"]
}
# ── 3. events, incrementally ─────────────────────────────────────────────
seen = set()
def new_events():
# window wider than the poll interval, then de-duplicate on id
r = S.get(f"{BASE}/v2/events/since", params={"minutes": 2}, timeout=60)
r.raise_for_status()
for e in r.json().get("events", []):
if e["id"] not in seen:
seen.add(e["id"])
yield e
# ── 4. a report, nightly ─────────────────────────────────────────────────
def daily_report(day, device_ids):
r = S.post(f"{BASE}/v2/new-reports/daily_summary/generate",
json={"date_from": day, # YYYY-MM-DD — never a datetime
"date_to": day,
"format": "json",
"device_ids": device_ids},
timeout=300)
r.raise_for_status()
body = r.json()
if body.get("status") != 1:
raise RuntimeError(body.get("message"))
data = body["data"]
cols = data["columns"]
rows = ([row for s in data["sections"] for row in s["rows"]]
if data["layout"] == "sections" else data["rows"])
# zip by column NAME — never by a hardcoded index
return [dict(zip(cols, row)) for row in rows]
# ── 5. the same report as a PDF ──────────────────────────────────────────
def daily_report_pdf(day, device_ids, path):
r = S.post(f"{BASE}/v2/new-reports/daily_summary/generate",
json={"date_from": day, "date_to": day,
"format": "pdf", "device_ids": device_ids},
timeout=300)
r.raise_for_status()
open(path, "wb").write(r.content)
while True:
for p in positions(): ... # upsert into your store
for e in new_events(): ... # forward to your alerting
time.sleep(10)
Five rules this encodes:
- Send the key in the
Authorizationheader, never in a URL. get_devices_latest, notget_devices.- Compute from
timestamp, never fromtime. - Report dates are
YYYY-MM-DD; time of day is a separate parameter. - Zip report rows against
columnsby name.