Open In App

Exception Handling Of Python Requests Module

Last Updated : 23 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python request module is a simple and elegant Python HTTP library. It provides methods for accessing Web resources via HTTP. In the following article, we will use the HTTP GET method in the Request module. This method requests data from the server and the Exception handling comes in handy when the response is not successful. Here, we will go through such situations. We will use Python’s try and except functionality to explore the exceptions that arise from the Requests module.

  • url: Returns the URL of the response
  • raise_for_status(): If an error occur, this method returns a HTTPError object
  • request: Returns the request object that requested this response
  • status_code: Returns a number that indicates the status (200 is OK, 404 is Not Found)
     

Successful Connection Request

The first thing to know is that the response code is 200 if the request is successful.

Python3




# code
import requests
  
# The following line makes an https request, and stores the response
# in the variable 'r'
r = requests.get("https://www.google.com")
  
# The following line give us the response code
r.status_code


Output:

200

Exception Handling for HTTP Errors

Here, we tried the following URL sequence and then passed this variable to the Python requests module using raised_for_status(). If the try part is successful, we will get the response code 200, if the page that we requested doesn’t exist. This is an HTTP error, which was handled by the Request module’s exception HTTPError and you probably got the error 404.

Python3




# code
import requests
  
  
try:
    r = requests.get(url, timeout=1)
    r.raise_for_status()
except requests.exceptions.HTTPError as errh:
    print("HTTP Error")
    print(errh.args[0])
# Prints the response code
print(r)


Output:

HTTP Error
404 Client Error: Not Found for url: https://www.amazon.com/nothing_here
<Response [404]>

General Exception Handling

You could also use a general exception from the Request module. That is requests.exceptions.RequestException.

Python3




# code
try:
    r = requests.get(url, timeout=1)
    r.raise_for_status()
except requests.exceptions.RequestException as errex:
    print("Exception request")


Output:

Exception request 

Now, you may have noticed that there is an argument ‘timeout’ passed into the Request module. We could prescribe a time limit for the requested connection to respond. If this has not happened, we could catch that using the exception requests.exceptions.ReadTimeout. To demonstrate this let us find a website that responds successfully.

Python3




import requests
  
# code
try:
    r = requests.get(url, timeout=1)
    r.raise_for_status()
except requests.exceptions.ReadTimeout as errrt:
    print("Time out")
  
print(r)


Output:

<Response [200]>

If we change timeout = 0.01, the same code would return, because the request could not possibly be that fast.

Time out
<Response [200]>

Exception Handling for Missing Schema

Another common error is that we might not specify HTTPS or HTTP in the URL. For example, We cause use requests.exceptions.MissingSchema to catch this exception.

Python3




url = "www.google.com"
# code
try:
    r = requests.get(url, timeout=1)
    r.raise_for_status()
except requests.exceptions.MissingSchema as errmiss:
    print("Missing schema: include http or https")
except requests.exceptions.ReadTimeout as errrt:
    print("Time out")


Output:

Missing scheme: include http or https

Exception Handling for Connection Error

Let us say that there is a site that doesn’t exist. Here, the error will occur even when you can’t make a connection because of the lack of an internet connection

Python3




# code
try:
  r = requests.get(url, timeout = 1, verify = True)
  r.raise_for_status()
except requests.exceptions.HTTPError as errh:
  print("HTTP Error")
  print(errh.args[0])
except requests.exceptions.ReadTimeout as errrt:
  print("Time out")
except requests.exceptions.ConnectionError as conerr:
  print("Connection error")


Output:

Connection error

Putting Everything Together

Here, We put together everything we tried so far the idea is that the exceptions are handled according to the specificity. 

For example, url =  “https://www.gle.com”,  When this code is run for this URL will produce an Exception request. Whereas, In the absence of connection requests.exceptions.ConnectionError will print the Connection Error, and when the connection is not made the general exception is handled by requests.exceptions.RequestException.

Python3




  
# code
try:
    r = requests.get(url, timeout=1, verify=True)
    r.raise_for_status()
except requests.exceptions.HTTPError as errh:
    print("HTTP Error")
    print(errh.args[0])
except requests.exceptions.ReadTimeout as errrt:
    print("Time out")
except requests.exceptions.ConnectionError as conerr:
    print("Connection error")
except requests.exceptions.RequestException as errex:
    print("Exception request")


Output:

Note: The output may change according to requests.

 Time out


Previous Article
Next Article

Similar Reads

GET and POST Requests in GraphQL API using Python requests
In this article, we will be understanding how to write GET and POST requests to GRAPHQL APIs using the Python request module. Dealing with GraphQL API is a bit different compared to the simple REST APIs. We have to parse in a query that involves parsing the GraphQL queries in the request body. What are Requests in Python Requests is a python packag
9 min read
Python | Raising an Exception to Another Exception
Let's consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information about both errors. Code #1 : def example(): try: in
2 min read
Create API Tester using Python Requests Module
Prerequisites: Python Requests module, API In this article, we will discuss the work process of the Python Requests module by creating an API tester. API stands for Application Programming Interface (main participant of all the interactivity). It is like a messenger that takes our requests to a system and returns a response back to us via seamless
3 min read
Upgrading Python Requests Module
The Python Requests Module is a simple and standard HTTP library, that is widely used for making HTTP requests extremely easily. It is one of the most downloaded Python packages in the present times. The requests module is frequently used in web scraping and needs to be learned in web scraping or REST APIs to proceed further in these tasks. Hence,
3 min read
Multiple Exception Handling in Python
Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages. If you can handle different exceptions all using a single block of code, they can be grouped together in a tuple as shown in th
3 min read
Handling TypeError Exception in Python
TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise a TypeError. ExamplesThe general causes for TypeError being raised are: 1. Unsupported Operation Betwe
3 min read
Handling NameError Exception in Python
Prerequisites: Python Exception Handling There are several standard exceptions in Python and NameError is one among them. NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are : 1. Misspelled built-in functions: In the below example code, the print statement
2 min read
Handling OSError exception in Python
Let us see how to handle OSError Exceptions in Python. OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as "file not found" or "disk full". Below is an example of OSError: Python Code # Importing
2 min read
Handling a thread's exception in the caller thread in Python
Multithreading in Python can be achieved by using the threading library. For invoking a thread, the caller thread creates a thread object and calls the start method on it. Once the join method is called, that initiates its execution and executes the run method of the class object. For Exception handling, try-except blocks are used that catch the ex
3 min read
Handling EOFError Exception in Python
EOFError is raised when one of the built-in functions input() or raw_input() hits an end-of-file condition (EOF) without reading any data. This error is sometimes experienced while using online IDEs. This occurs when we have asked the user for input but have not provided any input in the input box. We can overcome this issue by using try and except
1 min read
Article Tags :
Practice Tags :