What is the easiest way to check whether the response received from a requests post was "200 OK" or an error has occurred?
I tried doing something like this:
.... resp = requests.post(my_endpoint_var, headers=header_var, data=post_data_var) print(resp) if resp == "<Response [200]>": print ('OK!') else: print ('Boo!')
The output on the screen is:
Response [200] (including the "<" and ">") Boo!
So even though I am getting a 200, my check in the if statement is somehow not matching?
status_code returns a number that indicates the status (200 is OK, 404 is Not Found). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object.
The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: GET : The resource has been fetched and is transmitted in the message body.
Definition and Usage. The requests module allows you to send HTTP requests using Python. The HTTP request returns a Response Object with all the response data (content, encoding, status, etc).
According to the docs, there's a status_code property on the response-object. So you can do the following:
if resp.status_code == 200: print ('OK!') else: print ('Boo!')
EDIT:
As others have pointed out, a simpler check would be
if resp.ok: print ('OK!') else: print ('Boo!')
if you want to consider all 2xx
response codes and not 200
explicitly. You may also want to check Peter's answer for a more python-like way to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With