SeleniumHQ/selenium · error · APIRequestFailure
{response.status} {response.status_text}: {response.url}
Error message
{response.status} {response.status_text}: {response.url} What it means
`APIRequestFailure` is raised when an API request (via `APIRequestContext` or `APIRequestContext.new_context`) returns a non-2xx status AND `fail_on_status_code` is True. The message shows the status code, status text, and final URL (after redirects). This mirrors Playwright's API testing failure semantics. When `fail_on_status_code` is False, the response object is returned instead and you inspect `.ok`/`.status` yourself.
Source
Thrown at py/selenium/webdriver/common/api_request_context.py:505
body = self._prepare_body(headers, kwargs)
url = self._append_params(url, kwargs)
resp = self._execute_request(method, url, headers, body, kwargs)
# After redirects, associate cookies with the final destination's
# origin, not the initial request URL.
final_url = _resolve_redirect_url(resp, url)
# Process response cookies
set_cookie_headers = _get_set_cookie_headers(resp)
if set_cookie_headers:
self._handle_response_cookies(set_cookie_headers, final_url)
response = self._build_response(resp, final_url)
fail = kwargs.get("fail_on_status_code", self._fail_on_status_code)
if fail and not response.ok:
raise APIRequestFailure(response)
return response
class APIRequestContext(_BaseRequestContext):
"""Makes HTTP requests with automatic browser cookie synchronization.
Cookies from the browser session are sent with API requests, and cookies
from API responses are synced back to the browser.
Args:
driver: The WebDriver instance to sync cookies with.
base_url: Optional base URL prepended to relative request paths.
extra_headers: Optional headers included in every request.
timeout: Default request timeout in seconds.
max_redirects: Maximum number of redirects to follow.
fail_on_status_code: If True, raise APIRequestFailure for non-2xx responses.
"""View on GitHub (pinned to aa36b38e69)
Solutions
- Set `fail_on_status_code=False` and inspect `response.ok`/`response.status` yourself for conditional handling.
- Wrap the call in try/except APIRequestFailure and read `e.response.status` to branch.
- Fix the upstream endpoint/auth so it returns 2xx.
- Add retry with backoff for transient 5xx/429.
Example fix
// before
resp = api_context.get(url) # raises APIRequestFailure on non-2xx
// after
resp = api_context.get(url, fail_on_status_code=False)
if not resp.ok:
print("got", resp.status, resp.url) Defensive patterns
Strategy: try-catch
Validate before calling
resp = api_context.get(url, fail_on_status_code=False)
if not resp.ok:
handle_error(resp.status, resp.url, resp.text()) Type guard
def is_failing_status(resp) -> bool:
return not (200 <= resp.status <= 299) Try / catch
from selenium.webdriver.common.api_request_context import APIRequestFailure
try:
resp = api_context.get(url)
except APIRequestFailure as e:
if e.response.status in (401, 403):
refresh_auth()
elif e.response.status >= 500:
retry()
else:
raise Prevention
- Use fail_on_status_code=False for robust branching on status.
- Retry transient 5xx/429 with backoff.
- Inspect e.response.status to differentiate error classes.
When it happens
Trigger: `api_context.get("https://api.example.com/missing", fail_on_status_code=True)` hitting a 404; a 500 from the server; auth failure (401/403); or any non-2xx when the context was constructed with `fail_on_status_code=True`.
Common situations: Endpoint returns an error during integration tests; expired auth token causing 401; rate limiting (429); a mistyped URL returning 404; server-side 500 during load.
Related errors
- Download unavailable (HTTP {r.status}): {url}
- Failed to download {url}: HTTP {r.status}
- Fetch failed (HTTP {response.status}): {url}
- Unsuccessful response ({}) for URL {}
- Pattern must be an instance of UrlPattern. Received: '${patt
AI-assisted analysis of SeleniumHQ/selenium@aa36b38e69 (2026-08-14).
Data as JSON: /api/errors/eed29feba4cf38e6.
Report an issue: GitHub.