Skip to content

Instantly share code, notes, and snippets.

@dogrunjp
Last active December 14, 2016 07:37
Show Gist options
  • Save dogrunjp/d50e0da5c39593a052f98b064cb0cdbc to your computer and use it in GitHub Desktop.
Save dogrunjp/d50e0da5c39593a052f98b064cb0cdbc to your computer and use it in GitHub Desktop.
[Python] ある条件で全件数が不明で、100件づつしか値を返さないAPIで全件数をリストで取得する再帰的な関数

ある条件で全件数が不明で、100件づつしか値を返さないAPIで全件数をリストで取得する再帰的な関数

タイトルのような処理を書いていたのですが、再帰的な関数に慣れないため、欲しい値を得るまでに時間がかかりました。

APIの仕様は、下記のようにシンプルにして考えてみます。

  • 全件数が不明
  • APIはデータを{item: []}の形式で返す
  • 最大100件までしか値を返さない
  • 取得件数を指定するオプションは"rows="
  • 取得アイテムのオフセットは"start="

この条件で全件を取得する関数を考えてみます。

def get_all_items(acc_list=[], n=0):
    base_url = "http://huga"
    rows_val = 100
    start_val = rows_val * n
    target_url = "{0}?rows={1}&start={2}".format(base_url, rows_val, start_val)
    res = urllib.request.urlopen(target_url)
    res_read = res.read().decode('utf-8')
    res_json = json.loads(res_read)
    item = res_json["item"]
    item_list.extend(item)
    fetched = len(item)
    if fetched >= rows_val:
        item_list.extend(get_all_items(acc_list, n+1))
    return item_list

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment