🐍 The Python SDK — app6.4
Developer CourseModule 6: The Python SDKapp6.4
Reading10 min

Error Handling, Retries, and Production Patterns

🐍 Module 6: The Python SDK

Error Handling, Retries, and Production Patterns

Production code is different from lab code. It needs to handle failures gracefully.

The 3 Error Categories

CategoryHTTP CodesWhat to Do
Client error400, 401, 403, 404Fix your code (bad request, wrong key)
Rate limit429Back off and retry with exponential delay
Server error500, 502, 503Retry with backoff — the server will recover

Exponential Backoff with Jitter

import time, random

def api_call_with_retry(fn, max_retries=5):
    for attempt in range(max_retries):
        try:
            return fn()
        except Exception as e:
            if "429" in str(e) or "5" in str(getattr(e, 'status', '')):
                delay = (2 ** attempt) + random.uniform(0, 1)
                print(f"  Retry in {delay:.1f}s (attempt {attempt + 1})")
                time.sleep(delay)
            else:
                raise  # Client errors should not be retried
    raise Exception(f"Failed after {max_retries} retries")

Production Patterns

1. Environment variables for secrets:

import os
api_key = os.environ["EAT_KEY"]  # Never hardcode

2. Logging instead of print:

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("energy-app")
logger.info(f"Battery SOC: {soc}%")

3. Graceful shutdown:

import signal
running = True
def handler(sig, frame): global running; running = False
signal.signal(signal.SIGTERM, handler)
while running: ...

4. Health checks:

# Verify connectivity before starting main loop
try:
    client.sites.list()
    logger.info("API connection verified")
except Exception as e:
    logger.error(f"Cannot reach API: {e}")
    sys.exit(1)

Log in to track your progress and earn certifications.