5 Python API bugs I keep seeing (and the 2-line fixes)
DEV Community

5 Python API bugs I keep seeing (and the 2-line fixes)

These five bugs show up in almost every Python project that talks to an API. None of them is exotic, and each one has cost someone an afternoon.

1. Calling .json() on something that isn't JSON

Your API returns an HTML error page, and you get JSONDecodeError instead of the real problem.

resp = requests.get(url, timeout=10)
resp.raise_for_status()
if "application/json" not in resp.headers.get("Content-Type", ""):
    raise ValueError(f"Expected JSON, got: {resp.text[:200]}")
data = resp.json()

Now the error tells you what actually came back.

2. No timeout

requests has no default timeout. One slow server and your script hangs forever, usually inside a cron job you won't check for a week.

requests.get(url, timeout=10) # always

3. Hammering through a 429

Retrying a rate-limited request right away just extends the ban. Respect Retry-After:

import time

def get_with_backoff(url, max_tries=5):
    for attempt in range(max_tries):
        resp = requests.get(url, timeout=10)
        if resp.status_code != 429:
            return resp
        retry_after = resp.headers.get("Retry-After", "")
        wait = int(retry_after) if retry_after.isdigit() else 2 ** attempt
        time.sleep(wait)
    resp.raise_for_status()

(Retry-After can also be an HTTP date. The fallback handles that case.)

4. Only fetching page one

Your code works in testing with 12 records and silently drops data in production with 12,000.

def fetch_all(url, params=None):
    items = []
    while url:
        resp = requests.get(url, params=params, timeout=10)
        resp.raise_for_status()
        body = resp.json()
        items.extend(body["results"])
        url = body.get("next")
        params = None # the next URL already includes the query string
    return items

5. data= vs json=

requests.post(url, data={"name": "x"}) # form-encoded
requests.post(url, json={"name": "x"}) # JSON body + Content-Type header

If the API says "invalid body" and your payload looks right, this is usually why. To see what you actually sent, print resp.request.headers and resp.request.body.

Practice beats reading

You'll remember these fixes once you've hit each bug yourself. I put together Refinery, 25 broken Python/API exercises you debug yourself, if you want structured practice. Breaking your own code on purpose works too.

What's the API bug that cost you the most time? Drop it below and I'll add the good ones to a follow-up post.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.