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.
Deze oefening maakt deel uit van de cursus
Introduction to APIs in Python
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
# 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}.')