Skip to content

Commit aff1d1f

Browse files
committed
Add an iterate method to iterate over all records of a table.
1 parent fac3bea commit aff1d1f

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

airtable/airtable.py

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
import os, json, requests
1+
import json
2+
import os
3+
import requests
24
from collections import OrderedDict
35

46
API_URL = 'https://api.airtable.com/v%s/'
@@ -35,7 +37,7 @@ def create_payload(data):
3537
return {'fields': data}
3638

3739

38-
class Airtable:
40+
class Airtable(object):
3941
def __init__(self, base_id, api_key):
4042
self.airtable_url = API_URL % API_VERSION
4143
self.base_url = os.path.join(self.airtable_url, base_id)
@@ -68,11 +70,34 @@ def get(self, table_name, record_id=None, limit=0, offset=None):
6870
else:
6971
url = table_name
7072
if limit and check_integer(limit):
71-
params.update({'limit': limit})
73+
params.update({'pageSize': limit})
7274
if offset and check_string(offset):
7375
params.update({'offset': offset})
7476
return self.__request('GET', url, params)
7577

78+
def iterate(self, table_name, batch_size=0):
79+
"""Iterate over all records of a table.
80+
81+
Args:
82+
table_name: the name of the table to list.
83+
batch_size: the number of records to fetch per request. The default
84+
(0) is using the default of the API which is (as of 2016-09)
85+
100. Note that the API does not allow more than that (but
86+
allow for less).
87+
Yields:
88+
A dict for each record containing at least three fields: "id",
89+
"createdTime" and "fields".
90+
"""
91+
offset = None
92+
while True:
93+
response = self.get(table_name, limit=batch_size, offset=offset)
94+
for record in response.pop('records'):
95+
yield record
96+
if 'offset' in response:
97+
offset = response['offset']
98+
else:
99+
break
100+
76101
def create(self, table_name, data):
77102
if check_string(table_name):
78103
payload = create_payload(data)

0 commit comments

Comments
 (0)