Handling errors with Requests
When the requests
library is unable to connect to an API server, it will raise an exception. This exception allows you to detect if the API is available and act accordingly. But even when the request is successfully sent, we can still encounter errors. If we send an invalid request, a 4xx Client Error
is returned from the API, if the server encounters an error, a 5xx Server Error
is returned.
The requests
package provides a set of included exceptions that can be used to handle these errors using try/except
statements.
The requests
package has already been imported for your convenience.
This exercise is part of the course
Introduction to APIs in Python
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Import the correct exception class
from ____ import ____
url ="http://wronghost:3000/albums"
try:
r = requests.get(url)
print(r.status_code)
# Use the imported class to intercept the connection error
except ____ as conn_err:
print(f'Connection Error! {conn_err}.')