Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python requests: how to check for "200 OK"

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?

like image 247
Monty Avatar asked Jan 08 '19 07:01

Monty


People also ask

How do I check Python response status?

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.

What is a 200 status code?

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.

What is request module in Python?

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).


1 Answers

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.

like image 82
eol Avatar answered Sep 23 '22 02:09

eol