r/learnpython • • 53m ago

Code review: Is my manual retry loop in `requests` an anti-pattern when an API returns errors inside HTTP 200?

Hi everyone, I'm on Python 3.12 (Windows) and building a small CLI script to fetch search results from a REST API.

Earlier I tried using resp.raise_for_status() + urllib3.Retry, but ran into two things that tripped me up:

  1. This API returns HTTP 200 OK even when rate-limited (status: 1029) or on upstream failures, putting the actual error code inside the JSON body and retry hints in response headers (Retry-After, X-SerpBase-Retryable).
  2. When I request Markdown output (format="markdown"), the response comes back as text/markdown with no JSON wrapper, so blindly calling resp.json() crashed with JSONDecodeError.

Here is the wrapper I wrote to handle both cases (using requests.Session and reading the key from an environment variable):

import os
import time
import requests

API_KEY = os.environ["SERPBASE_API_KEY"]
BASE_URL = "https://api.serpbase.dev"

session = requests.Session()
session.headers.update({
    "X-API-Key": API_KEY,
    "Content-Type": "application/json",
})


def search_google(query: str, as_markdown: bool = False, retries: int = 2):
    payload = {"q": query, "gl": "us", "hl": "en"}
    if as_markdown:
        payload["format"] = "markdown"

    for attempt in range(retries + 1):
        resp = session.post(f"{BASE_URL}/google/search", json=payload, timeout=60)
        resp.raise_for_status()

        content_type = resp.headers.get("Content-Type", "")
        if "text/markdown" in content_type:
            return resp.text

        data = resp.json()
        status = data.get("status")
        if status == 0:
            return data.get("organic", [])

        if status == 1029 and attempt < retries:
            wait = int(resp.headers.get("Retry-After", "2"))
            time.sleep(wait)
            continue

        retryable = resp.headers.get("X-SerpBase-Retryable") == "true"
        if retryable and attempt < retries:
            time.sleep(2 ** attempt)
            continue

        raise RuntimeError(f"API error status={status}, retryable={retryable}")

It works now, but I have three specific questions to make this more Pythonic:

  1. Since urllib3.Retry (via HTTPAdapter) only retries on HTTP-level status codes like 429/503, is a manual for attempt loop the normal way to handle HTTP-200 JSON error envelopes, or is a library like tenacity cleaner?
  2. Is int(resp.headers.get("Retry-After", "2")) risky if a server ever sends an HTTP-date string instead of integer seconds?
  3. Should I pass session into search_google() as a parameter instead of keeping it at module level, especially if I want to write unit tests later?

Thanks in advance for any pointers!

1 Upvotes

1 comment sorted by

•

u/InevitablePure4177 0m ago

A small manual loop is fine here. The JSON status is an application error, not an HTTP status, so keep that retry decision explicit. Retry-After can be a date or seconds (RFC 9110 section 10.2.3). Use email.utils.parsedate_to_datetime for dates, handle invalid values and stop if the wait exceeds your retry budget. Pass the session in and inject the sleep function so tests do not actually wait. Test 1029 then success, final retry exhaustion, Markdown, and a date header. Since this uses POST, also check whether repeated searches consume credits before enabling transport-level retries.