DEV Community

Cover image for 5 Python API bugs I keep seeing (and the 2-line fixes)
bzucker4
bzucker4

Posted on

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

(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
Enter fullscreen mode Exit fullscreen mode

5. data= vs json=

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

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.

Top comments (0)