r/learnpython • • 4d 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!

3 Upvotes

6 comments sorted by

2

u/Greedy_Ad_7658 4d ago

Agree with the other reply that a manual loop is fine here. A few things I'd change in the code itself:

  • raise_for_status() sits inside the loop, so a real 429 or 503 raises immediately and never gets retried. Either catch requests.HTTPError and decide per status code, or mount an HTTPAdapter with Retry for the HTTP-level errors and keep your loop only for the 200-with-error-body case. Note Retry skips POST by default, so you need allowed_methods=["POST"] and only if the endpoint is safe to repeat.
  • Add jitter to the backoff (random.uniform(0, 2 ** attempt)) so several scripts don't retry in lockstep.
  • Split it in two: a small function that makes one request and returns (result, retry_after or None), and the loop that decides whether to wait. Then the retry policy is testable without mocking the network, and the markdown vs JSON branch lives in one place.
  • Cap the total time, not just the attempt count. With timeout=60 and 3 attempts you can sit there for minutes.

1

u/CleemBeigne-55 4d ago

a manual loop is totally fine here, especially when the retry wait time depends on custom response headers and payload values. and yeah definitely pass the session in as an argument (or wrap the whole thing in a small client class) so you can easily mock it out in tests later.

1

u/Sufficient-Tale6131 3d ago

On the Retry-After question: yes, wrapping it in int() will blow up if the server sends an HTTP-date instead of a delay in seconds. That header is allowed to be either form. A small helper that tries int first, and on ValueError uses email.utils.parsedate_to_datetime to turn the date into seconds from now, then clamps it (0 if it's already past, and some max so a bad header can't stall you for hours) is enough. Fall back to your default of 2 if parsing fails completely.

The others already covered the loop vs tenacity and passing in the session, so I won't rehash that. urllib3 won't help with the 200-plus-JSON-error case anyway.

1

u/LegalDebate5423 3d ago

A small explicit loop is a good fit for the JSON error envelope. Keep transport retries separate, since `raise_for_status()` currently exits before your loop can retry HTTP errors. Parse `Retry-After` defensively because it can be seconds or an HTTP date, and cap the wait. Injecting the session makes unit tests easier. Also inject the sleep function so retry tests stay fast. Since this is POST, only retry when repeating the request is safe for that API.