Handle API failures with Python Requests by separating HTTP and JSON errors, bounding retries, honoring rate-limit delays, and preserving failure details.
Use Python's `requests` library to call API endpoints and handle failures. Show how your client would handle HTTP 4xx and 5xx responses, retry a 429 response, and handle a response body that cannot be parsed as JSON.
You may consult API documentation, and you do not need to run the calls. State any assumptions about the HTTP method and expected success response. Endpoint URLs and payload schemas are not prescribed; keep them configurable rather than inventing service-specific fields.
### What a Strong Answer Covers
- Separate handling for transport failures, unsuccessful HTTP responses, and JSON decoding failures.
- A bounded retry policy that distinguishes 429 from other 4xx responses and considers whether repeating the operation is safe.
- Appropriate handling of retry timing, exhausted attempts, and an unsuccessful response with a non-JSON body.
- A clear return/error contract that callers can use without mistaking a failure for an empty successful result.
### Follow-up Questions
- What changes if the endpoint creates a resource and a timeout leaves its outcome uncertain?
- How would your retry policy behave when the server requests a longer wait than the client is willing to make?
Overview: Handle API failures with Python Requests by separating HTTP and JSON errors, bounding retries, honoring rate-limit delays, and preserving failure details.
Use Python's requests library to call API endpoints and handle failures. Show how your client would handle HTTP 4xx and 5xx responses, retry a 429 response, and handle a response body that cannot be parsed as JSON.
You may consult API documentation, and you do not need to run the calls. State any assumptions about the HTTP method and expected success response. Endpoint URLs and payload schemas are not prescribed; keep them configurable rather than inventing service-specific fields.
What a Strong Answer Covers Guidance
Separate handling for transport failures, unsuccessful HTTP responses, and JSON decoding failures.
A bounded retry policy that distinguishes 429 from other 4xx responses and considers whether repeating the operation is safe.
Appropriate handling of retry timing, exhausted attempts, and an unsuccessful response with a non-JSON body.
A clear return/error contract that callers can use without mistaking a failure for an empty successful result.
Follow-up Questions Guidance
What changes if the endpoint creates a resource and a timeout leaves its outcome uncertain?
How would your retry policy behave when the server requests a longer wait than the client is willing to make?