{"id":"28027f65d3a4d5fe","repo":"psf/requests","slug":"self-status-code-client-error-reason-for-url","errorCode":null,"errorMessage":"{self.status_code} Client Error: {reason} for url: {self.url}","messagePattern":"(.+?) Client Error: (.+?) for url: (.+?)","errorType":"http","errorClass":"HTTPError","httpStatus":400,"severity":"error","filePath":"src/requests/models.py","lineNumber":1171,"sourceCode":"            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n        else:\n            reason = self.reason\n\n        if 400 <= self.status_code < 500:\n            http_error_msg = (\n                f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            http_error_msg = (\n                f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n            )\n\n        if http_error_msg:\n            raise HTTPError(http_error_msg, response=self)\n\n    def close(self) -> None:\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if release_conn is not None:\n            release_conn()\n","sourceCodeStart":1153,"sourceCodeEnd":1185,"githubUrl":"https://github.com/psf/requests/blob/414f0513c33883adf6f2b46901d4f0b38a455851/src/requests/models.py#L1153-L1185","documentation":"Raised by Response.raise_for_status() in src/requests/models.py when the response status code is in the 4xx range (400 <= status_code < 500). Requests wraps the status, the server-supplied reason phrase (decoded utf-8, falling back to iso-8859-1), and the final URL into a requests.exceptions.HTTPError so callers can turn HTTP-level failures into Python exceptions instead of silently inspecting status codes.","triggerScenarios":"Calling response.raise_for_status() after any requests.get/post/etc. that returned 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests, or any other 4xx. It is never raised automatically — only when raise_for_status() (or code that calls it, e.g. many API client wrappers) is invoked.","commonSituations":"Missing or expired API keys/tokens (401/403), wrong endpoint paths or IDs (404), malformed JSON bodies or missing required parameters (400/422), rate limiting (429), and redirects landing on auth walls. The URL in the message reflects the final URL after redirects, which often reveals the real problem.","solutions":["Inspect the failing response before raising: check response.status_code and response.text/response.json() for the server's error detail.","Fix the request per status: refresh/attach credentials for 401/403, correct the URL or resource ID for 404, validate the payload for 400/422.","For 429, honor the Retry-After header or add backoff (e.g. urllib3 Retry with status_forcelist).","Wrap the call in try/except requests.exceptions.HTTPError and use err.response for structured handling."],"exampleFix":"# before\nresp = requests.get(url)\nresp.raise_for_status()\ndata = resp.json()\n\n# after\nresp = requests.get(url, headers={\"Authorization\": f\"Bearer {token}\"})\ntry:\n    resp.raise_for_status()\nexcept requests.HTTPError as err:\n    print(err.response.status_code, err.response.text)\n    raise\ndata = resp.json()","handlingStrategy":"try-catch","validationCode":null,"typeGuard":"def is_client_error(resp):\n    return 400 <= resp.status_code < 500","tryCatchPattern":"try:\n    resp = requests.get(url)\n    resp.raise_for_status()\nexcept requests.exceptions.HTTPError as e:\n    if e.response is not None and 400 <= e.response.status_code < 500:\n        handle_client_error(e.response)","preventionTips":["Only call raise_for_status() when you want exceptions; otherwise branch on resp.status_code or resp.ok","Check resp.ok before consuming the body","Handle 401/403/404 explicitly since they indicate caller-side problems (auth, permissions, wrong URL) that retries won't fix","Access e.response inside the handler to log status and body for diagnosis"],"tags":["http","client-error","raise-for-status","network"],"analyzedSha":"414f0513c33883adf6f2b46901d4f0b38a455851","analyzedAt":"2026-07-31T19:24:57.696Z","schemaVersion":2}