Airtable Api¶
Overview¶
This client offers three classes you can use to access the Airtable Api:
Table
- represents an Airtable TableBase
- represents an Airtable BaseApi
- represents an Airtable Api
The interfaces of these are nearly identical, the main difference
is if base_id
and table_id
are provided on initialization or on calls.
For example, the three all()
calls below would return the same result:
from pyairtable import Api, Base, Table
api = Api('auth_token')
api.all('base_id', 'table_name')
base = Base('auth_token', 'base_id')
base.all('table_name')
table = Table('auth_token', 'base_id', 'table_name')
table.all()
Interface¶
The table below shows a comparison of the methods used in the library compared with the official API equivalent.
Type |
pyAirtable |
Airtable Api |
---|---|---|
Retrieve a single Record |
|
|
Iterate over record pages |
|
|
Get all records |
|
|
Get all matches |
|
|
Get first match |
|
|
Create record |
|
|
Update a record |
|
|
Replace a record |
|
|
Delete a record |
|
|
Examples¶
Examples below use the Table
Api for conciseness -
all methods are available for all three interfaces (Api
, Base
, and Table
).
Fetching Records¶
Iterate over a set of records of size page_size
, up until max_records
or end of
table, whichever is shorter.
>>> for records in table.iterate(page_size=100, max_records=1000):
... print(records)
[{'id': 'rec123asa23', 'fields': {'Last Name': 'Alfred', 'Age': 84}, ...}, ...]
[{'id': 'rec123asa23', 'fields': {'Last Name': 'Jameson', 'Age': 42}, ...}, ...]
This method returns a single list with all records in a table. Note that under the
hood it uses iterate()
to fetch records so multiple requests might be made.
>>> table.all(sort=["First Name", "-Age"]):
[{'id': 'rec123asa23', 'fields': {'Last Name': 'Alfred', 'Age': 84}, ...}, ...]
Creating Records¶
Creates a single record from a dictionary representing the table’s fields.
>>> table.create({'First Name': 'John'})
{'id': 'rec123asa23', 'fields': {'First Name': 'John', ...}}
Batch create records from a list of dictionaries representing the table’s fields.
>>> table.batch_create([{'First Name': 'John'}, ...])
[{'id': 'rec123asa23', 'fields': {'First Name': 'John'}}, ...]
Updating Records¶
Updates a single record for the provided record_id
using a
dictionary representing the table’s fields.
>>> table.update('recwPQIfs4wKPyc9D', {"Age": 21})
[{'id': 'recwPQIfs4wKPyc9D', 'fields': {"First Name": "John", "Age": 21}}, ...]
Batch update records from a list of records.
>>> table.batch_update([{"id": "recwPQIfs4wKPyc9D", "fields": {"First Name": "Matt"}}, ...])
[{'id': 'recwPQIfs4wKPyc9D', 'fields': {"First Name": "Matt", ...}}, ...]
New in version 1.5.0.
Batch upsert (create or update) records from a list of records. For details on the behavior of this Airtable API endpoint, see Update multiple records.
>>> table.batch_upsert(
... [{"id": "recwPQIfs4wKPyc9D", "fields": {"First Name": "Matt"}}, ...],
... key_fields=["First Name"]
... )
[{'id': 'recwPQIfs4wKPyc9D', 'fields': {'First Name': 'Matt', 'Age': 21, ...}}, ...]
Deleting Records¶
Deletes a single record using the provided record_id
.
>>> table.delete('recwPQIfs4wKPyc9D')
{'deleted': True, 'id': 'recwPQIfs4wKPyc9D'}
Batch delete records using a list of record ids.
>>> table.batch_delete(['recwPQIfs4wKPyc9D', 'recwAcQdqwe21asdf'])
[{'deleted': True, 'id': 'recwPQIfs4wKPyc9D'},
{'deleted': True, 'id': 'recwAcQdqwe21asdf'}]
Return Values¶
Return Values: when records are returned, will most often be a list of Airtable records (dictionary) in a format as shown below.
>>> table.all()
[
{
"records": [
{
"id": "recwPQIfs4wKPyc9D",
"fields": {
"COLUMN_ID": "1",
},
"createdTime": "2017-03-14T22:04:31.000Z"
},
{
"id": "rechOLltN9SpPHq5o",
"fields": {
"COLUMN_ID": "2",
},
"createdTime": "2017-03-20T15:21:50.000Z"
},
{
"id": "rec5eR7IzKSAOBHCz",
"fields": {
"COLUMN_ID": "3",
},
"createdTime": "2017-08-05T21:47:52.000Z"
}
],
"offset": "rec5eR7IzKSAOBHCz"
},
...
]
The Base
class is similar to Table
, the main difference is that
table_name is not provided during initialization. Instead, it can be
specified on each request.
>>> base = Base('auth_token', 'base_id')
>>> base.all('Contacts')
[{'id': 'rec123asa23', 'fields': {'Last Name': 'Alfred', 'Age': 84}, ...]
Classes¶
Api¶
New in version 1.0.0.
- class pyairtable.api.Api(api_key, *, timeout=None, retry_strategy=None, endpoint_url='https://api.airtable.com')[source]¶
Represents an Airtable Api.
The Api Key or Authorization Token is provided on init and
base_id
andtable_id
can be provided on each method call.If you are only operating on one Table, or one Base, consider using
Base
orTable
.- Usage:
>>> api = Api('auth_token') >>> api.all('base_id', 'table_name')
- __init__(api_key, *, timeout=None, retry_strategy=None, endpoint_url='https://api.airtable.com')[source]¶
- Parameters
api_key (
str
) – An Airtable API Key or An Airtable Authorization Token.- Keyword Arguments
timeout (
Tuple
) – A tuple indicating a connect and read timeout. eg.timeout=(2,5)
would configure a 2 second timeout for the connection to be established and 5 seconds for a server read timeout. Default isNone
(no timeout).retry_strategy (
Retry
) – An instance ofurllib3.util.Retry
.pyairtable.retrying.retry_strategy()
returns one with reasonable defaults, but you may provide your own custom instance ofRetry
. Default isNone
(no retry).endpoint_url (
str
) – The API endpoint to hit. You might want to override it if you are using an API proxy to debug your API calls. Default ishttps://api.airtable.com
.
- all(base_id, table_name, **options)[source]¶
Retrieves all records repetitively and returns a single list.
>>> api.all('base_id', 'table_name', view='MyView', fields=['ColA', '-ColB']) [{'fields': ... }, ...] >>> api.all('base_id', 'table_name', max_records=50) [{'fields': ... }, ...]
- Parameters
base_id (
str
) – An Airtable base id.table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.
- Keyword Arguments
view – The name or ID of a view. If set, only the records in that view will be returned. The records will be sorted according to the order of the view.
page_size – The number of records returned in each request. Must be less than or equal to 100. Default is 100.
max_records – The maximum total number of records that will be returned. If this value is larger than page_size multiple requests will be needed to fetch all records.
fields – Name of field or fields to be retrieved. Default is all fields. Only data for fields whose names are in this list will be included in the records. If you don’t need every field, you can use this parameter to reduce the amount of data transferred.
sort – List of fields to sort by. Default order is ascending. This parameter specifies how the records will be ordered. If you set the view parameter, the returned records in that view will be sorted by these fields. If sorting by multiple columns, column names can be passed as a list. Sorting Direction is ascending by default, but can be reversed by prefixing the column name with a minus sign
-
.formula – An Airtable formula. The formula will be evaluated for each record, and if the result is not 0, false, “”, NaN, [], or #Error! the record will be included in the response. If combined with view, only records in that view which satisfy the formula will be returned. For example, to only include records where
COLUMN_A
isn’t empty, pass in:"NOT({COLUMN_A}='')"
.cell_format – The cell format to request from the Airtable API. Supported options are json (the default) and string. json will return cells as a JSON object. string will return the cell as a string. user_locale and time_zone must be set when using string.
user_locale – The user locale that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/220340268-Supported-locale-modifiers-for-SET-LOCALE for valid values.
time_zone – The time zone that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/216141558-Supported-timezones-for-SET-TIMEZONE for valid values.
return_fields_by_field_id – An optional boolean value that lets you return field objects where the key is the field id. This defaults to false, which returns field objects where the key is the field name.
- Returns
List of Records
- Return type
records (
list
)
>>> records = all(max_records=3, view='All')
- batch_create(base_id, table_name, records, typecast=False, return_fields_by_field_id=False)[source]¶
Breaks records into chunks of 10 and inserts them in batches. Follows the set API rate. To change the rate limit you can change
API_LIMIT = 0.2
(5 per second)>>> records = [{'Name': 'John'}, {'Name': 'Marc'}] >>> api.batch_create('base_id', 'table_name', records)
- Parameters
base_id (
str
) – An Airtable base id.table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.records (
List[dict]
) – List of dictionaries representing records to be created.
- Keyword Arguments
typecast – The Airtable API will perform best-effort automatic data conversion from string values. Default is False.
return_fields_by_field_id – An optional boolean value that lets you return field objects where the key is the field id. This defaults to false, which returns field objects where the key is the field name.
- Returns
list of added records
- Return type
records (
list
)
- batch_delete(base_id, table_name, record_ids)[source]¶
Breaks records into batches of 10 and deletes in batches, following set API Rate Limit (5/sec). To change the rate limit set value of
API_LIMIT
to the time in seconds it should sleep before calling the function again.>>> record_ids = ['recwPQIfs4wKPyc9D', 'recwDxIfs3wDPyc3F'] >>> api.batch_delete('base_id', 'table_name', records_ids)
- Parameters
base_id (
str
) – An Airtable base id.table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.record_ids (
list
) – Record Ids to delete
- Returns
list of records deleted
- Return type
records(
list
)
- batch_update(base_id, table_name, records, replace=False, typecast=False, return_fields_by_field_id=False)[source]¶
Updates a records by their record id’s in batch.
- Parameters
base_id (
str
) – An Airtable base id.table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.records (
list
) – List of dict: [{“id”: record_id, “fields”: fields_to_update_dict}]
- Keyword Arguments
replace (
bool
, optional) – IfTrue
, record is replaced in its entirety by provided fields - eg. if a field is not included its value will bet set to null. If False, only provided fields are updated. Default isFalse
.typecast – The Airtable API will perform best-effort automatic data conversion from string values. Default is False.
return_fields_by_field_id – An optional boolean value that lets you return field objects where the key is the field id. This defaults to false, which returns field objects where the key is the field name.
- Returns
list of updated records
- Return type
records(
list
)
- batch_upsert(base_id, table_name, records, key_fields, replace=False, typecast=False, return_fields_by_field_id=False)[source]¶
Updates or creates records in batches, either using
id
(if given) or using a set of fields (key_fields
) to look for matches. For more information on how this operation behaves, see Airtable’s API documentation for Update multiple records.New in version 1.5.0.
- Parameters
base_id (
str
) – An Airtable base id.table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.records (
list
) – List of dict: [{“id”: record_id, “fields”: fields_to_update_dict}]key_fields (
list
) – List of field names that Airtable should use to match records in the input with existing records on the server.
- Keyword Arguments
replace (
bool
, optional) – IfTrue
, record is replaced in its entirety by provided fields - e.g. if a field is not included its value will bet set to null. If False, only provided fields are updated. Default isFalse
.typecast – The Airtable API will perform best-effort automatic data conversion from string values. Default is False.
return_fields_by_field_id – An optional boolean value that lets you return field objects where the key is the field id. This defaults to false, which returns field objects where the key is the field name.
- Returns
list of updated records
- Return type
records (
list
)
- create(base_id, table_name, fields, typecast=False, return_fields_by_field_id=False)[source]¶
Creates a new record
>>> record = {'Name': 'John'} >>> api.create('base_id', 'table_name', record)
- Parameters
base_id (
str
) – An Airtable base id.table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.fields (
dict
) – Fields to insert. Must be dictionary with Column names as Key.
- Keyword Arguments
typecast – The Airtable API will perform best-effort automatic data conversion from string values. Default is False.
return_fields_by_field_id – An optional boolean value that lets you return field objects where the key is the field id. This defaults to false, which returns field objects where the key is the field name.
- Returns
Inserted record
- Return type
record (
dict
)
- delete(base_id, table_name, record_id)[source]¶
Deletes a record by its id
>>> record = api.match('base_id', 'table_name', 'Employee Id', 'DD13332454') >>> api.delete('base_id', 'table_name', record['id'])
- Parameters
base_id (
str
) – An Airtable base id.table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.record_id (
str
) – An Airtable record id.
- Returns
Deleted Record
- Return type
record (
dict
)
- first(base_id, table_name, **options)[source]¶
Retrieves the first found record or
None
if no records are returned.This is similar to
all()
, except it it setspage_size
andmax_records
to1
.- Parameters
base_id (
str
) – An Airtable base id.table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.
- Keyword Arguments
view – The name or ID of a view. If set, only the records in that view will be returned. The records will be sorted according to the order of the view.
fields – Name of field or fields to be retrieved. Default is all fields. Only data for fields whose names are in this list will be included in the records. If you don’t need every field, you can use this parameter to reduce the amount of data transferred.
sort – List of fields to sort by. Default order is ascending. This parameter specifies how the records will be ordered. If you set the view parameter, the returned records in that view will be sorted by these fields. If sorting by multiple columns, column names can be passed as a list. Sorting Direction is ascending by default, but can be reversed by prefixing the column name with a minus sign
-
.formula – An Airtable formula. The formula will be evaluated for each record, and if the result is not 0, false, “”, NaN, [], or #Error! the record will be included in the response. If combined with view, only records in that view which satisfy the formula will be returned. For example, to only include records where
COLUMN_A
isn’t empty, pass in:"NOT({COLUMN_A}='')"
.cell_format – The cell format to request from the Airtable API. Supported options are json (the default) and string. json will return cells as a JSON object. string will return the cell as a string. user_locale and time_zone must be set when using string.
user_locale – The user locale that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/220340268-Supported-locale-modifiers-for-SET-LOCALE for valid values.
time_zone – The time zone that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/216141558-Supported-timezones-for-SET-TIMEZONE for valid values.
return_fields_by_field_id – An optional boolean value that lets you return field objects where the key is the field id. This defaults to false, which returns field objects where the key is the field name.
- get(base_id, table_name, record_id, **options)[source]¶
Retrieves a record by its id
>>> record = api.get('base_id', 'table_name', 'recwPQIfs4wKPyc9D')
- Parameters
base_id (
str
) – An Airtable base id.table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.record_id (
str
) – An Airtable record id.
- Keyword Arguments
return_fields_by_field_id – An optional boolean value that lets you return field objects where the key is the field id. This defaults to false, which returns field objects where the key is the field name.
- Returns
Record
- Return type
record
- get_base(base_id)[source]¶
Returns a new
Base
instance using all shared attributes fromApi
- Return type
- get_record_url(base_id, table_name, record_id)[source]¶
Returns a url for the provided record
- Parameters
base_id (
str
) – An Airtable base id.table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.
- get_table(base_id, table_name)[source]¶
Returns a new
Table
instance using all shared attributes fromApi
- Return type
- iterate(base_id, table_name, **options)[source]¶
Record Retriever Iterator
Returns iterator with lists in batches according to pageSize. To get all records at once use
all()
>>> for page in api.iterate('base_id', 'table_name'): ... for record in page: ... print(record) {"id": ... } ...
- Parameters
base_id (
str
) – An Airtable base id.table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.
- Keyword Arguments
view – The name or ID of a view. If set, only the records in that view will be returned. The records will be sorted according to the order of the view.
page_size – The number of records returned in each request. Must be less than or equal to 100. Default is 100.
max_records – The maximum total number of records that will be returned. If this value is larger than page_size multiple requests will be needed to fetch all records.
fields – Name of field or fields to be retrieved. Default is all fields. Only data for fields whose names are in this list will be included in the records. If you don’t need every field, you can use this parameter to reduce the amount of data transferred.
sort – List of fields to sort by. Default order is ascending. This parameter specifies how the records will be ordered. If you set the view parameter, the returned records in that view will be sorted by these fields. If sorting by multiple columns, column names can be passed as a list. Sorting Direction is ascending by default, but can be reversed by prefixing the column name with a minus sign
-
.formula – An Airtable formula. The formula will be evaluated for each record, and if the result is not 0, false, “”, NaN, [], or #Error! the record will be included in the response. If combined with view, only records in that view which satisfy the formula will be returned. For example, to only include records where
COLUMN_A
isn’t empty, pass in:"NOT({COLUMN_A}='')"
.cell_format – The cell format to request from the Airtable API. Supported options are json (the default) and string. json will return cells as a JSON object. string will return the cell as a string. user_locale and time_zone must be set when using string.
user_locale – The user locale that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/220340268-Supported-locale-modifiers-for-SET-LOCALE for valid values.
time_zone – The time zone that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/216141558-Supported-timezones-for-SET-TIMEZONE for valid values.
return_fields_by_field_id – An optional boolean value that lets you return field objects where the key is the field id. This defaults to false, which returns field objects where the key is the field name.
- Returns
Record Iterator, grouped by page size
- Return type
iterator
- update(base_id, table_name, record_id, fields, replace=False, typecast=False)[source]¶
Updates a record by its record id. Only Fields passed are updated, the rest are left as is.
>>> table.update('recwPQIfs4wKPyc9D', {"Age": 21}) {id:'recwPQIfs4wKPyc9D', fields': {"First Name": "John", "Age": 21}} >>> table.update('recwPQIfs4wKPyc9D', {"Age": 21}, replace=True) {id:'recwPQIfs4wKPyc9D', fields': {"Age": 21}}
- Parameters
base_id (
str
) – An Airtable base id.table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.record_id (
str
) – An Airtable record id.fields (
dict
) – Fields to update. Must be a dict with column names or IDs as keys
- Keyword Arguments
replace (
bool
, optional) – IfTrue
, record is replaced in its entirety by provided fields - eg. if a field is not included its value will bet set to null. If False, only provided fields are updated. Default isFalse
.typecast – The Airtable API will perform best-effort automatic data conversion from string values. Default is False.
- Returns
Updated record
- Return type
record (
dict
)
Base¶
New in version 1.0.0.
- class pyairtable.api.Base(api_key, base_id, *, timeout=None, retry_strategy=None, endpoint_url='https://api.airtable.com')[source]¶
Represents an Airtable Base. This class is similar to
Api
, exceptbase_id
is provided on init instead of provided on each method call.- Usage:
>>> base = Base('auth_token', 'base_id') >>> base.all()
- __init__(api_key, base_id, *, timeout=None, retry_strategy=None, endpoint_url='https://api.airtable.com')[source]¶
- Parameters
api_key (
str
) – An Airtable API Key or An Airtable Authorization Token.base_id (
str
) – An Airtable base id.
- Keyword Arguments
timeout (
Tuple
) – A tuple indicating a connect and read timeout. eg.timeout=(2,5)
would configure a 2 second timeout for the connection to be established and 5 seconds for a server read timeout. Default isNone
(no timeout).retry_strategy (
Retry
) – An instance ofurllib3.util.Retry
.pyairtable.retrying.retry_strategy()
returns one with reasonable defaults, but you may provide your own custom instance ofRetry
. Default isNone
(no retry).
- batch_create(table_name, records, typecast=False, return_fields_by_field_id=False)[source]¶
Same as
Api.batch_create
but withoutbase_id
arg.
- batch_delete(table_name, record_ids)[source]¶
Same as
Api.batch_delete
but withoutbase_id
arg.
- batch_update(table_name, records, replace=False, typecast=False, return_fields_by_field_id=False)[source]¶
Same as
Api.batch_update
but withoutbase_id
arg.
- batch_upsert(table_name, records, key_fields, replace=False, typecast=False, return_fields_by_field_id=False)[source]¶
Same as
Api.batch_upsert
but withoutbase_id
arg.
- create(table_name, fields, typecast=False, return_fields_by_field_id=False)[source]¶
Same as
Api.create
but withoutbase_id
arg.
- delete(table_name, record_id)[source]¶
Same as
Api.delete
but withoutbase_id
arg.
- get_record_url(table_name, record_id)[source]¶
Same as
Api.get_record_url
but withoutbase_id
arg.
- get_table(table_name)[source]¶
Returns a new
Table
instance using all shared attributes fromBase
- Return type
- iterate(table_name, **options)[source]¶
Same as
Api.iterate
but withoutbase_id
arg.
- update(table_name, record_id, fields, replace=False, typecast=False)[source]¶
Same as
Api.update
but withoutbase_id
arg.
Table¶
New in version 1.0.0.
- class pyairtable.api.Table(api_key, base_id, table_name, *, timeout=None, retry_strategy=None, endpoint_url='https://api.airtable.com')[source]¶
Represents an Airtable Table. This class is similar to
Api
, exceptbase_id
andtable_id
are provided on init instead of provided on each method call.- Usage:
>>> table = Table('apikey/accesstoken', 'base_id', 'table_name') >>> table.all()
- __init__(api_key, base_id, table_name, *, timeout=None, retry_strategy=None, endpoint_url='https://api.airtable.com')[source]¶
- Parameters
api_key (
str
) – An Airtable API Key or An Airtable Authorization Token.base_id (
str
) – An Airtable base id.table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.
- Keyword Arguments
timeout (
Tuple
) – A tuple indicating a connect and read timeout. eg.timeout=(2,5)
would configure a 2 second timeout for the connection to be established and 5 seconds for a server read timeout. Default isNone
(no timeout).retry_strategy (
Retry
) – An instance ofurllib3.util.Retry
.pyairtable.retrying.retry_strategy()
returns one with reasonable defaults, but you may provide your own custom instance ofRetry
. Default isNone
(no retry).
- batch_create(records, typecast=False, return_fields_by_field_id=False)[source]¶
Same as
Api.batch_create
but withoutbase_id
andtable_name
arg.
- batch_delete(record_ids)[source]¶
Same as
Api.batch_delete
but withoutbase_id
andtable_name
arg.
- batch_update(records, replace=False, typecast=False, return_fields_by_field_id=False)[source]¶
Same as
Api.batch_update
but withoutbase_id
andtable_name
arg.
- batch_upsert(records, key_fields, replace=False, typecast=False, return_fields_by_field_id=False)[source]¶
Same as
Api.batch_upsert
but withoutbase_id
andtable_name
arg.
- create(fields, typecast=False, return_fields_by_field_id=False)[source]¶
Same as
Api.create
but withoutbase_id
andtable_name
arg.
- delete(record_id)[source]¶
Same as
Api.delete
but withoutbase_id
andtable_name
arg.
- get_record_url(record_id)[source]¶
Same as
Api.get_record_url
but withoutbase_id
andtable_name
arg.
- iterate(**options)[source]¶
Same as
Api.iterate
but withoutbase_id
andtable_name
arg.
- property table_url¶
Returns the table URL
- update(record_id, fields, replace=False, typecast=False)[source]¶
Same as
Api.update
but withoutbase_id
andtable_name
arg.
Retrying¶
New in version 1.4.0.
You may provide an instance of urllib3.util.Retry
to configure
retrying behaviour.
The library also provides retry_strategy()
to quickly generate a
Retry
instance with reasonable defaults that you can use as-is or with tweaks.
Note
for backwards-compatibility, the default behavior is no retry (retry_strategy=None). This may change in future releases.
Default Retry Strategy
from pyairtable import Api, retry_strategy
api = Api('auth_token', retry_strategy=retry_strategy())
Adjusted Default Strategy
from pyairtable import Api, retry_strategy
api = Api('auth_token', retry_strategy=retry_strategy(total=3))
Custom Retry
from pyairtable import Api, retry_strategy
from urllib3.util import Retry
myRetry = Retry(**kwargs)
api = Api('auth_token', retry_strategy=myRetry)
- pyairtable.api.retrying.retry_strategy(*, status_forcelist=(429, 500, 502, 503, 504), backoff_factor=0.3, total=5, **kwargs)[source]¶
Creates a
Retry
instance with optional default values. See urllib3 Retry docs for more details.New in version 1.4.0.
- Keyword Arguments
status_forcelist (
Tuple[int]
) – list status code which should be retried.backoff_factor (
float
) – backoff factor.total (
int
) – max. number of retries. Note0
means no retries, while``1`` will exececute a total of two requests (1 + 1 retry).**kwargs – All parameters supported by
urllib3.util.Retry
can be used.
- Return type
Retry
Parameters¶
Airtable offers a variety of options to control how you fetch data.
Most options in the Airtable Api (e.g. sort
, fields
, etc.)
have a corresponding kwargs
that can be used with fetching methods like iterate()
.
Keyword Argument |
Airtable Parameter |
Notes |
---|---|---|
|
|
The maximum total number of records that will be returned. If this value is larger than page_size multiple requests will be needed to fetch all records. |
|
|
List of fields to sort by.
Default order is ascending.
This parameter specifies how the records will be ordered. If you set the view
parameter, the returned records in that view will be sorted by these
fields. If sorting by multiple columns, column names can be passed as a list.
Sorting Direction is ascending by default, but can be reversed by
prefixing the column name with a minus sign |
|
|
The name or ID of a view. If set, only the records in that view will be returned. The records will be sorted according to the order of the view. |
|
|
The number of records returned in each request. Must be less than or equal to 100. Default is 100. |
|
|
An Airtable formula. The formula will be evaluated for each record, and if the result
is not 0, false, “”, NaN, [], or #Error! the record will be included
in the response. If combined with view, only records in that view which satisfy the
formula will be returned. For example, to only include records where
|
|
|
Name of field or fields to be retrieved. Default is all fields. Only data for fields whose names are in this list will be included in the records. If you don’t need every field, you can use this parameter to reduce the amount of data transferred. |
|
|
The cell format to request from the Airtable API. Supported options are json (the default) and string. json will return cells as a JSON object. string will return the cell as a string. user_locale and time_zone must be set when using string. |
|
|
The user locale that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/220340268-Supported-locale-modifiers-for-SET-LOCALE for valid values. |
|
|
The time zone that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/216141558-Supported-timezones-for-SET-TIMEZONE for valid values. |
|
|
An optional boolean value that lets you return field objects where the key is the field id. This defaults to false, which returns field objects where the key is the field name. |
Formulas¶
New in version 1.0.0.
The formula module provides functionality to help you compose Airtable formulas. For more information see Airtable Formula Reference
Match¶
match()
helps you build a formula to check for equality
against a Python dictionary:
>>> from pyairtable import Table
>>> from pyairtable.formulas import match
>>> table = Table("auth_token", "base_id", "Contact")
>>> formula = match({"First Name": "John", "Age": 21})
>>> table.first(formula=formula)
{"id": "recUwKa6lbNSMsetH", "fields": {"First Name": "John", "Age": 21}}
>>> formula
"AND({First Name}='John',{Age}=21)"
- pyairtable.formulas.match(dict_values, *, match_any=False)[source]¶
Creates one or more
EQUAL()
expressions for each provided dict value. If more than one assetions is included, the expressions are groupped together into usingAND()
(all values must match).If
match_any=True
, expressions are grouped withOR()
, record is return if any of the values match.This function also handles escaping field names and casting python values to the appropriate airtable types using
to_airtable_value()
on all provided values to help generate the expected formula syntax.If you need more advanced matching you can build similar expressions using lower level forumula primitives.
- Parameters
dict_values – dictionary containing column names and values
- Keyword Arguments
match_any – matches if any of the provided values match. Default is
False
(all values must match)
- Usage:
>>> match({"First Name": "John", "Age": 21}) "AND({First Name}='John',{Age}=21)" >>> match({"First Name": "John", "Age": 21}, match_any=True) "OR({First Name}='John',{Age}=21)" >>> match({"First Name": "John"}) "{First Name}='John'" >>> match({"Registered": True}) "{Registered}=1" >>> match({"Owner's Name": "Mike"}) "{Owner\'s Name}='Mike'"
Formula Helpers¶
- pyairtable.formulas.to_airtable_value(value)[source]¶
Cast value to appropriate airtable types and format. For example, to check
bool
values in formulas, you actually to compare to 0 and 1.Input
Output
bool
int
str
str
; text is wrapped in ‘single quotes’; existing quotes are escaped.all others
unchanged
- Arg:
value: value to be cast.
Raw Formulas¶
New in version 1.0.0.
This module also includes many lower level functions you can use if you want to compose formulas:
- pyairtable.formulas.EQUAL(left, right)[source]¶
Creates an equality assertion
>>> EQUAL(2,2) '2=2'
- Return type
str
- pyairtable.formulas.FIELD(name)[source]¶
Creates a reference to a field. Quotes are escaped.
- Parameters
name (
str
) – field name
- Usage:
>>> FIELD("First Name") '{First Name}' >>> FIELD("Guest's Name") '{Guest\' Names}'
- Return type
str
- pyairtable.formulas.AND(*args)[source]¶
Creates an AND Statement
>>> AND(1, 2, 3) 'AND(1, 2, 3)'
- Return type
str
- pyairtable.formulas.OR(*args)[source]¶
New in version 1.2.0.
Creates an OR Statement
>>> OR(1, 2, 3) 'OR(1, 2, 3)'
- Return type
str
- pyairtable.formulas.FIND(what, where, start_position=0)[source]¶
Creates an FIND statement
>>> FIND(STR(2021), FIELD('DatetimeCol')) 'FIND('2021', {DatetimeCol})'
- Parameters
what (
str
) – String to search forwhere (
str
) – Where to search. Could be a string, or a field reference.start_position – Index of where to start search. Default is 0.
- Return type
str
- pyairtable.formulas.IF(logical, value1, value2)[source]¶
Creates an IF statement
>>> IF(1=1, 0, 1) 'IF(1=1, 0, 1)'
- Return type
str
- pyairtable.formulas.STR_VALUE(value)[source]¶
Wraps string in quotes. This is needed when referencing a string inside a formula. Quotes are escaped.
>>> STR_VALUE("John") "'John'" >>> STR_VALUE("Guest's Name") "'Guest\'s Name'" >>> EQUAL(STR_VALUE("John"), FIELD("First Name")) "'John'={First Name}"
- Return type
str