r/learnpython • u/SuperExperience6689 • 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:
- 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!
3
Upvotes
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:
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.