IniziaInizia gratis

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.

Questo esercizio fa parte del corso

Introduction to APIs in Python

Visualizza il corso

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

# 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}.')
Modifica ed esegui il codice