r/learnpython • u/SuperExperience6689 • 1h 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:
- This API returns HTTP
200 OKeven 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). - When I request Markdown output (
format="markdown"), the response comes back astext/markdownwith no JSON wrapper, so blindly callingresp.json()crashed withJSONDecodeError.
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:
- Since
urllib3.Retry(viaHTTPAdapter) only retries on HTTP-level status codes like429/503, is a manualfor attemptloop the normal way to handle HTTP-200 JSON error envelopes, or is a library liketenacitycleaner? - Is
int(resp.headers.get("Retry-After", "2"))risky if a server ever sends an HTTP-date string instead of integer seconds? - Should I pass
sessionintosearch_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
•
u/Greedy_Ad_7658 36m ago
Agree with the other reply that a manual loop is fine here. A few things I'd change in the code itself:
•
u/InevitablePure4177 52m 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.