BaşlayınÜcretsiz Başlayın

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.

Bu egzersiz

Introduction to APIs in Python

kursunun bir parçasıdır
Kursu Görüntüle

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

# 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}.')
Kodu Düzenle ve Çalıştır