How to Get the Status Code of a Response Object in Python Using the Requests Module 


               


How to Get the Status Code of a Response Object in Python Using the Requests Module



Python


In this article, we show how to get the status code of a response object in Python using the requests module.

Using the module requests, we can get the contents of any URL that we want.

Checking the status code of the request we made can be useful to see if the GET request was successful or not.

If the GET request of the URL that we specified was good, then this produces a status of 200, meaning the GET request was successful (the page exists and the retrieval of it was successful). If unsuccessful, it may produce a status code such as 404 for a 'Page Not Found' error.

So how can we check the status code of a response object when we have sent a request?

There is an attribute of the response object called status_code.

Below in the code, we show how to get the status code of a request that we have made.



So first we have to import the requests module.

Then we create a variable named getpage and set it equal to requests.get('http://www.learningaboutelectronics.com')

This is the URL that we want to retrieve (via the HTTP GET method).

We then check the status code of the request that we've made.

And since the page exists and the retrieval was successful, a status code of 200 is returned.

Thus, we know the request was good.

Now let's do an example with a page we know does not exist.

So we make a request to a page that we know does not exist and see what status code we get.



Thus, since the page does not exist and, thus, cannot be retrieved, a 404 status code is returned.

A 404 error, again, means 'Page is not Found'.

So this is how status codes work and can be retrieved in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...