#!/usr/bin/env python3 """Time four read-only MetaBridgeAPI requests over one HTTPS connection. Set METABRIDGE_API_KEY, ORG_ID, and ACCOUNT_ID in your environment, then run: python3 examples/python/read-account.py ORG_ID and ACCOUNT_ID are vendor UUIDs; ACCOUNT_ID is not the broker login. The key needs accounts:read. Only status, timing, socket reuse, and request IDs are printed. Response bodies are consumed but never printed. Requests are not retried. The first request includes connection setup; later requests reuse the socket when the server keeps it open. /me may not have a request_events entry. """ import http.client import os import sys import time import uuid HOST = "metabridgeapi.com" TIMEOUT_SECONDS = 10 MAX_RESPONSE_BYTES = 2_000_000 def required_env(name): value = os.environ.get(name) if not value: raise ValueError(f"Set {name} in your environment.") return value def environment_uuid(name): value = required_env(name) try: return str(uuid.UUID(value)) except ValueError: raise ValueError(f"{name} must be a vendor UUID.") from None def read_account(api_key, organization_id, account_id): prefix = f"/api/v1/organizations/{organization_id}/accounts" routes = ( ("me", "/api/v1/me"), ("accounts", prefix), ("details", f"{prefix}/{account_id}/details"), ("capabilities", f"{prefix}/{account_id}/capabilities"), ) headers = {"Authorization": f"Bearer {api_key}", "Accept": "application/json"} connection = http.client.HTTPSConnection(HOST, timeout=TIMEOUT_SECONDS) try: for label, path in routes: reuse = "reused" if connection.sock is not None else "cold" started = time.perf_counter() connection.request("GET", path, headers=headers) response = connection.getresponse() body = response.read(MAX_RESPONSE_BYTES + 1) elapsed_ms = (time.perf_counter() - started) * 1000 try: request_id = str(uuid.UUID(response.getheader("X-Request-Id", ""))) except ValueError: request_id = "-" print( f"{label}: status={response.status} elapsed_ms={elapsed_ms:.1f} " f"connection={reuse} request_id={request_id}", flush=True, ) if len(body) > MAX_RESPONSE_BYTES: print("Response exceeded the size limit; stopped.", file=sys.stderr) return 1 if response.status != 200: print("Request was unsuccessful; stopped without retrying.", file=sys.stderr) return 1 return 0 except (OSError, http.client.HTTPException): print("HTTPS request failed; stopped without retrying.", file=sys.stderr) return 1 finally: connection.close() def main(): try: api_key = required_env("METABRIDGE_API_KEY") if ( not api_key.startswith("vnd_") or len(api_key) > 4096 or not api_key.isascii() or any(ord(character) <= 32 or ord(character) == 127 for character in api_key) ): raise ValueError("METABRIDGE_API_KEY must contain a valid vendor API key.") organization_id = environment_uuid("ORG_ID") account_id = environment_uuid("ACCOUNT_ID") except ValueError as error: print(error, file=sys.stderr) return 1 return read_account(api_key, organization_id, account_id) if __name__ == "__main__": sys.exit(main())