Find internet connectivity using python – requests

Let us imagine ourself creating a desktop application, where we want to check whether our system is connected to the internet, before proceeding to other tasks. In that situation, this little code snippet comes in handy.

The requests library in python can be used to solve this task.

Requests

Requests is a Python HTTP library, released under the Apache License 2.0. The goal of the project is to make HTTP requests simpler and more human-friendly. 

Most of the python applications uses requests library to send http requests such as GET, POST etc,. In this example we are going to test the connectivity with a simple GET request.

Code

We are using a head() method here.

The head() method sends a HEAD request to the specified url.

HEAD requests are done when you do not need the content of the file, but only the status_code or HTTP headers. We can also use get() for this purpose.

How this works?

  1. We are importing the requests module and calling the head() method with a url and a timeout params. You can also pass the url of your API in the url parameter to test the connectivity.
  2. The requests module has a built in exception called as “ConnectionError”. This exception occurs when the connection cannot be established. We are making use of this exception to test whether our system is connected to the internet or not.
Conclusion

The requests module has various methods available to make the http requests simple and effective. We can even specify the headers and do much more. Check out the documentation here.

Happy coding!