1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonでfor文のループ内でAPIを呼び出す際のエラーハンドリング方法を考えてみた

Posted at

APIを叩く時にエラーとなることがある。
for文でAPIのパラメータをインクリメントして叩いている時にエラーとなった場合にエラーハンドリングをどうしたらいいのか複数考えてみた。
※業務で同じようなことに出会したことがないため、同じようなことを業務でしている方がいらっしゃいましたら、エラーハンドリングの方法をコメントしていただけると勉強になります。

エラーハンドリング案

①try-catch

try-catch.py
import requests

for item in items:
    try:
        response = requests.get(api_url)
        # レスポンスの処理
    except requests.exceptions.HTTPError as errh:
        print('HTTPError:', errh)
    except requests.exceptions.ConnectionError as errc:
        print('ConnectionError:', errc)
    except requests.exceptions.Timeout as errt:
        print('Timeout Error:', errt)
    except requests.exceptions.RequestException as err:
        print('RequestException:', err)

APIを叩いた時にエラーが発生した場合にそれぞれのErrorに応じて処理を行う

②リトライ

retry.py
import requests
import time

MAX_RETRIES = 3
RETRY_INTERVAL = 5

for item in items:
    for retry_count in range(MAX_RETRIES):
        try:
            response = requests.get(api_url)
            break
        except requests.exceptions.RequestException:
            if retry_count == MAX_RETRIES - 1:
                print('APIリトライ失敗')
            else:
                time.sleep(RETRY_INTERVAL)

APIのパラメータをインクリメントしない場合にはなりますが、エラーが起こった時に再試行する。
エラーが起こらなかった場合はbreakでfor文から抜ける。

終わりに

try-catchとリトライを組み合わせたり、ロガーを追加して保守しやすくするなり方法があると記事を書きながら思いました。良さそうな案があれば日々追記してきます。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?