Just checking the response attribute resp.ok is True
is sufficient for all 2xx responses (while it will be False
for 4xx and 5xx)
However, a potentially more Pythonic way to check for success would be to test and optionally raise an exception with Response.raise_for_status()
(which will raise requests.HTTPError
if the request was unsuccessful, or continue without interruption for a successful request)
This can be directly handled or raised to the calling function (which might, for example, try the request again after a few seconds if it believes the error was transient)
try:
resp = requests.post(url, headers=headers, data=data, timeout=timeout)
resp.raise_for_status()
except requests.HTTPError as ex:
# possibly check response for a message
raise ex # let the caller handle it
except requests.Timeout:
# request took too long
EAFP: It’s Easier to Ask for Forgiveness than Permission
It's frequently clearer to just do what you expect to work and if an exception is raised from the operation, except and handle it.
Finally, note that some APIs will return a valid response (200) for errors with information about why the request was bad, while others may respond with a 400-level with additional information that might be useful (such as a link to documentation or a specific message about what to do), which can be worth checking for.