API Reference¶
API: pyairtable¶
- class pyairtable.Api[source]¶
Represents an Airtable API. Implements basic URL construction, session and request management, and retrying logic.
- Usage:
>>> api = Api('auth_token') >>> table = api.table('base_id', 'table_name') >>> records = table.all()
- MAX_RECORDS_PER_REQUEST = 10¶
Airtable-imposed limit on number of records per batch create/update operation.
- MAX_URL_LENGTH = 16000¶
Airtable-imposed limit on the length of a URL (including query parameters).
- property urls¶
URLs associated with
Apican be accessed via.urlsusing the following syntax:>>> api = Api(...) >>> api.urls.whoami Url('https://api.airtable.com/...')
These properties are all instances of
Url.- _urls.whoami = Url('meta/whoami')
- _urls.bases = Url('meta/bases')
- __init__(api_key, *, timeout=None, retry_strategy=True, endpoint_url='https://api.airtable.com', use_field_ids=False)[source]¶
- Parameters
api_key (
str) – An Airtable API key or personal access token.timeout (
Optional[Tuple[int,int]], default:None) – A tuple indicating a connect and read timeout. e.g.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 (
Union[bool,Retry,None], default:True) – An instance of urllib3.util.Retry. IfNoneorFalse, requests will not be retried. IfTrue, the default strategy will be applied (seeretry_strategy()for details).endpoint_url (
str, default:'https://api.airtable.com') – The API endpoint to use. Override this if you are using a debugging or caching proxy.use_field_ids (
bool, default:False) – IfTrue, all API requests will return responses with field IDs instead of field names.
- property api_key: str¶
Airtable API key or access token to use on all connections.
- Return type
str
- whoami()[source]¶
Return the current user ID and (if connected via OAuth) the list of scopes. See Get user ID & scopes for more information.
- Return type
- base(base_id, *, validate=False, force=False)[source]¶
Return a new
Baseinstance that uses this instance ofApi.- Parameters
base_id (
str) – An Airtable base ID.validate (
bool, default:False) – IfFalse, will create an object without validating the ID/name provided. IfTrue, will fetch information from the metadata API and validate the ID/name exists, raisingKeyErrorif it does not.force (
bool, default:False) – By default, this method will only fetch information from the API if it has not been cached. If called withforce=Trueit will always call the API, and will overwrite any cached values.
- Raises
KeyError – if
validate=Trueand the given base ID does not exist.- Return type
- bases(*, force=False)[source]¶
Retrieve the base’s schema and return a list of
Baseinstances.- Parameters
force (
bool, default:False) – By default, this method will only fetch information from the API if it has not been cached. If called withforce=Trueit will always call the API, and will overwrite any cached values.
- Usage:
>>> api.bases() [ <pyairtable.Base base_id='appSW9...'>, <pyairtable.Base base_id='appLkN...'> ]
- Return type
List[Base]
- create_base(workspace_id, name, tables)[source]¶
Create a base in the given workspace.
See https://airtable.com/developers/web/api/create-base
- Parameters
workspace_id (
str) – The ID of the workspace where the new base will live.name (
str) – The name to give to the new base. Does not need to be unique.tables (
Sequence[Dict[str,Any]]) – A list ofdictobjects that conform to Airtable’s Table model.
- Return type
- table(base_id, table_name, *, validate=False, force=False)[source]¶
Build a new
Tableinstance that uses this instance ofApi.- Parameters
base_id (
str) – An Airtable base ID.table_name (
str) – The Airtable table’s ID or name.validate (
bool, default:False) – IfFalse, will create an object without validating the ID/name provided. IfTrue, will fetch information from the metadata API and validate the ID/name exists, raisingKeyErrorif it does not.force (
bool, default:False) – By default, this method will only fetch information from the API if it has not been cached. If called withforce=Trueit will always call the API, and will overwrite any cached values.
- Return type
- build_url(*components)[source]¶
Build a URL to the Airtable API endpoint with the given URL components, including the API version number.
- Return type
- request(method, url, fallback=None, options=None, params=None, json=None)[source]¶
Make a request to the Airtable API, optionally converting a GET to a POST if the URL exceeds the maximum URL length.
- Parameters
method (
str) – HTTP method to use.url (
str) – The URL we’re attempting to call.fallback (
Optional[Tuple[str,str]], default:None) – The method and URL to use if we have to convert a GET to a POST.options (
Optional[Dict[str,Any]], default:None) – Airtable-specific query params to use while fetching records. See Parameters for valid options.params (
Optional[Dict[str,Any]], default:None) – Additional query params to append to the URL as-is.json (
Optional[Dict[str,Any]], default:None) – The JSON payload for a POST/PUT/PATCH/DELETE request.
- Return type
Any
- get(url, **kwargs)[source]¶
Make a GET request to the Airtable API. See
request()for keyword arguments.- Return type
Any
- post(url, **kwargs)[source]¶
Make a POST request to the Airtable API. See
request()for keyword arguments.- Return type
Any
- patch(url, **kwargs)[source]¶
Make a PATCH request to the Airtable API. See
request()for keyword arguments.- Return type
Any
- delete(url, **kwargs)[source]¶
Make a DELETE request to the Airtable API. See
request()for keyword arguments.- Return type
Any
- iterate_requests(method, url, fallback=None, options=None, params=None, offset_field='offset')[source]¶
Make one or more requests and iterates through each result.
If the response payload contains an ‘offset’ value, this method will perform another request with that offset value as a parameter (query params for GET, body payload for POST/PATCH/etc).
If the response payload is not a ‘dict’, it will be yielded as normal and the method will return.
- Parameters
method (
str) – HTTP method to use.url (
str) – The URL we’re attempting to call.fallback (
Optional[Tuple[str,str]], default:None) – The method and URL to use if we have to convert a GET to a POST.options (
Optional[Dict[str,Any]], default:None) – Airtable-specific query params to use while fetching records. See Parameters for valid options.params (
Optional[Dict[str,Any]], default:None) – Additional query params to append to the URL as-is.offset_field (
str, default:'offset') – The key to use in the API response to determine whether there are additional pages to retrieve.
- Return type
Iterator[Any]
- chunked(iterable)[source]¶
Iterate through chunks of the given sequence that are equal in size to the maximum number of records per request allowed by the API.
- Return type
Iterator[Sequence[TypeVar(T)]]
- class pyairtable.Base[source]¶
Represents an Airtable base.
- Usage:
>>> base = api.base("appNxslc6jG0XedVM") >>> table = base.table("Table Name") >>> records = table.all()
- property urls¶
URLs associated with
Basecan be accessed via.urlsusing the following syntax:>>> base = Base(...) >>> base.urls.meta Url('https://api.airtable.com/...')
These properties are all instances of
Url.- _urls.meta = Url('meta/bases/{id}')
URL for retrieving the base’s metadata and collaborators.
- _urls.interfaces = Url('meta/bases/{id}/interfaces')
URL for retrieving information about the base’s interfaces.
- _urls.shares = Url('meta/bases/{id}/shares')
URL for retrieving the base’s shares.
- _urls.tables = Url('meta/bases/{id}/tables')
URL for retrieving the base’s schema.
- _urls.collaborators = Url('meta/bases/{id}/collaborators')
URL for POST requests that modify collaborations on the base.
- _urls.webhooks = Url('bases/{id}/webhooks')
URL for retrieving or modifying the base’s webhooks.
- __init__(api, base_id, *, name=None, permission_level=None)[source]¶
Old style constructor takes
strarguments, and will create its own instance ofApi.This approach is deprecated, and will likely be removed in the future.
>>> Base("access_token", "base_id")
New style constructor takes an instance of
Api:>>> Base(api, "table_name")
- Parameters
api (
Union[Api,str]) – An instance ofApior an Airtable access token.base_id (
str) – An Airtable base ID.name (
Optional[str], default:None) – The name of the Airtable base, if known.permission_level (
Optional[str], default:None) – The permission level the current authenticated user has upon the Airtable base, if known.
- api: pyairtable.api.api.Api¶
The connection to the Airtable API.
- id: str¶
The base ID, in the format
appXXXXXXXXXXXXXX
- permission_level: Optional[str]¶
The permission level the current user has on the base
- property name: Optional[str]¶
The name of the base, if provided to the constructor or available in cached base information.
- Return type
Optional[str]
- table(id_or_name, *, validate=False, force=False)[source]¶
Build a new
Tableinstance using this instance ofBase.- Parameters
id_or_name (
str) – An Airtable table ID or name. Table name should be unencoded, as shown on browser.validate (
bool, default:False) – IfFalse, will create an object without validating the ID/name provided. IfTrue, will fetch information from the metadata API and validate the ID/name exists, raisingKeyErrorif it does not.force (
bool, default:False) – By default, this method will only fetch information from the API if it has not been cached. If called withforce=Trueit will always call the API, and will overwrite any cached values.
- Usage:
>>> base.table('Apartments') <Table base='appLkNDICXNqxSDhG' name='Apartments'>
- Return type
- tables(*, force=False)[source]¶
Retrieve the base’s schema and returns a list of
Tableinstances.- Parameters
force (
bool, default:False) – By default, this method will only fetch information from the API if it has not been cached. If called withforce=Trueit will always call the API, and will overwrite any cached values.
- Usage:
>>> base.tables() [ <Table base='appLkN...' id='tbltp8DGLhqbUmjK1' name='Apartments'>, <Table base='appLkN...' id='tblK6MZHez0ZvBChZ' name='Districts'> ]
- Return type
List[Table]
- create_table(name, fields, description=None)[source]¶
Create a table in the given base.
- Parameters
name (
str) – The unique table name.fields (
Sequence[Dict[str,Any]]) – A list ofdictobjects that conform to the Airtable field model.description (
Optional[str], default:None) – The table description. Must be no longer than 20k characters.
- Return type
- schema()[source]¶
Retrieve the schema of all tables in the base and caches it.
- Usage:
>>> base.schema().tables [TableSchema(...), TableSchema(...), ...] >>> base.schema().table("tblXXXXXXXXXXXXXX") TableSchema(id="tblXXXXXXXXXXXXXX", ...) >>> base.schema().table("My Table") TableSchema(id="...", name="My Table", ...)
- Parameters
force (
bool) – By default, this method will only fetch information from the API if it has not been cached. If called withforce=Trueit will always call the API, and will overwrite any cached values.- Return type
- webhooks()[source]¶
Retrieve all the base’s webhooks (see: List webhooks).
- Usage:
>>> base.webhooks() [ Webhook( id='ach00000000000001', are_notifications_enabled=True, cursor_for_next_payload=1, is_hook_enabled=True, last_successful_notification_time=None, notification_url="https://example.com", last_notification_result=None, expiration_time=datetime.datetime(...), specification: WebhookSpecification(...) ) ]
- Return type
List[Webhook]
- webhook(webhook_id)[source]¶
Build a single webhook or raises
MissingRecordErrorif the given ID is invalid.Airtable’s API does not permit retrieving a single webhook, so this function will call
webhooks()and simply return one item from the list.- Return type
- add_webhook(notify_url, spec)[source]¶
Create a webhook on the base with the given webhooks specification.
The return value will contain a unique secret that must be saved in order to validate payloads as they are sent to your notification endpoint. If you do not save this, you will have no way of confirming that payloads you receive did, in fact, come from Airtable.
For more on how to validate notifications to your webhook, see
WebhookNotification.from_request().- Usage:
>>> base.add_webhook( ... "https://example.com", ... { ... "options": { ... "filters": { ... "dataTypes": ["tableData"], ... } ... } ... } ... ) CreateWebhookResponse( id='ach00000000000001', mac_secret_base64='c3VwZXIgZHVwZXIgc2VjcmV0', expiration_time=datetime.datetime(...) )
- Raises
pydantic.ValidationError – If the dict provided is invalid.
- Parameters
notify_url (
str) – The URL where Airtable will POST all event notifications.spec (
Union[WebhookSpecification,Dict[Any,Any]]) – The configuration for the webhook. It is easiest to pass a dict that conforms to the webhooks specification but you can also provideWebhookSpecification.
- Return type
- collaborators()[source]¶
⚠ This feature is only available on Enterprise billing plans.
Retrieve base collaborators.
- Parameters
force (
bool) – By default, this method will only fetch information from the API if it has not been cached. If called withforce=Trueit will always call the API, and will overwrite any cached values.- Return type
⚠ This feature is only available on Enterprise billing plans.
Retrieve base shares.
- Parameters
force (
bool) – By default, this method will only fetch information from the API if it has not been cached. If called withforce=Trueit will always call the API, and will overwrite any cached values.- Return type
List[Info]
- class pyairtable.Table[source]¶
Represents an Airtable table.
- Usage:
>>> api = Api(access_token) >>> table = api.table("base_id", "table_name") >>> records = table.all()
- property urls¶
URLs associated with
Tablecan be accessed via.urlsusing the following syntax:>>> table = Table(...) >>> table.urls.records Url('https://api.airtable.com/...')
These properties are all instances of
Url.- _urls.records = Url('{base.id}/{self.id_or_name}')
URL for retrieving all records in the table
- _urls.records_post = Url('{base.id}/{self.id_or_name}/listRecords')
URL for retrieving all records in the table via POST, when the request is too large to fit into GET parameters.
- _urls.fields = Url('meta/bases/{base.id}/tables/{self.id_or_name}/fields')
- _urls.record_comments(record_id)[source]
URL for comments on a specific record in the table.
- Return type
- __init__(api_key: str, base_id: str, table_name: str, *, timeout: Optional[Tuple[int, int]] = 'None', retry_strategy: Optional[urllib3.util.retry.Retry] = 'None', endpoint_url: str = "'https://api.airtable.com'")[source]¶
- __init__(api_key: None, base_id: pyairtable.api.base.Base, table_name: str)
- __init__(api_key: None, base_id: pyairtable.api.base.Base, table_name: pyairtable.models.schema.TableSchema)
Old style constructor takes
strarguments, and will create its own instance ofApi. This constructor can also be provided with keyword arguments to theApiclass.This approach is deprecated, and will likely be removed in the future.
>>> Table("api_key", "base_id", "table_name", timeout=(1, 1))
New style constructor has an odd signature to preserve backwards-compatibility with the old style (above), requiring
Noneas the first argument, followed by an instance ofBase, followed by the table name.>>> Table(None, base, "table_name")
These signatures may change in the future. Developers using this library are encouraged to not construct Table instances directly, and instead fetch tables via
Api.table().
- base: pyairtable.api.base.Base¶
The base that this table belongs to.
- name: str¶
Can be either the table name or the table ID (
tblXXXXXXXXXXXXXX).
- property id: str¶
Get the table’s Airtable ID.
If the instance was created with a name rather than an ID, this property will perform an API request to retrieve the base’s schema. For example:
# This will not create any network traffic >>> table = base.table('tbl00000000000123') >>> table.id 'tbl00000000000123' # This will fetch schema for the base when `table.id` is called >>> table = base.table('Table Name') >>> table.id 'tbl00000000000123'
- Return type
str
- property id_or_name: str¶
Return the table ID if it is known, otherwise the table name used for the constructor. This is the URL component used to identify the table in Airtable’s API.
- Parameters
quoted (
bool, default:True) – Whether to return a URL-encoded value.
Usage:
>>> table = base.table("Apartments") >>> table.id_or_name 'Apartments' >>> table.schema() >>> table.id_or_name 'tblXXXXXXXXXXXXXX'
- Return type
str
- property api: pyairtable.api.api.Api¶
The API connection used by the table’s
Base.- Return type
- get(record_id, **options)[source]¶
Retrieve a record by its ID.
>>> table.get('recwPQIfs4wKPyc9D') {'id': 'recwPQIfs4wKPyc9D', 'fields': {'First Name': 'John', 'Age': 21}}
- Parameters
record_id (
str) – An Airtable record ID.- Keyword Arguments
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.
time_zone – The time zone that should be used to format dates when using string as the cell_format. See Supported SET_TIMEZONE timezones for valid values.
user_locale – The user locale that should be used to format dates when using string as the cell_format. See Supported SET_LOCALE modifiers for valid values.
use_field_ids – 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. This behavior can be overridden by passinguse_field_ids=TruetoApi.
- Return type
- iterate(**options)[source]¶
Iterate through each page of results from List records. To get all records at once, use
all().>>> it = table.iterate() >>> next(it) [{"id": ...}, {"id": ...}, {"id": ...}, ...] >>> next(it) [{"id": ...}, {"id": ...}, {"id": ...}, ...] >>> next(it) [{"id": ...}] >>> next(it) Traceback (most recent call last): StopIteration
- 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. If no value given, Airtable’s 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 none of
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. Read more at Building Formulas.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 Supported SET_LOCALE modifiers for valid values.
time_zone – The time zone that should be used to format dates when using string as the cell_format. See Supported SET_TIMEZONE timezones for valid values.
use_field_ids – 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. This behavior can be overridden by passinguse_field_ids=TruetoApi.count_comments – If
True, the API will include acommentCountfield for each record. This allows you to see which records have comments without fetching each record individually. Defaults toFalse.
- Return type
Iterator[List[RecordDict]]
- all(**options)[source]¶
Retrieve all matching records in a single list.
>>> table = api.table('base_id', 'table_name') >>> table.all(view='MyView', fields=['ColA', '-ColB']) [{'fields': ...}, ...] >>> table.all(max_records=50) [{'fields': ...}, ...]
- 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. If no value given, Airtable’s 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 none of
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. Read more at Building Formulas.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 Supported SET_LOCALE modifiers for valid values.
time_zone – The time zone that should be used to format dates when using string as the cell_format. See Supported SET_TIMEZONE timezones for valid values.
use_field_ids – 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. This behavior can be overridden by passinguse_field_ids=TruetoApi.count_comments – If
True, the API will include acommentCountfield for each record. This allows you to see which records have comments without fetching each record individually. Defaults toFalse.
- Return type
List[RecordDict]
- first(**options)[source]¶
Retrieve the first matching record. Returns
Noneif no records are returned.This is similar to
all(), except it setspage_sizeandmax_recordsto1.- 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 none of
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. Read more at Building Formulas.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 Supported SET_LOCALE modifiers for valid values.
time_zone – The time zone that should be used to format dates when using string as the cell_format. See Supported SET_TIMEZONE timezones for valid values.
use_field_ids – 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. This behavior can be overridden by passinguse_field_ids=TruetoApi.count_comments – If
True, the API will include acommentCountfield for each record. This allows you to see which records have comments without fetching each record individually. Defaults toFalse.
- Return type
Optional[RecordDict]
- create(fields, typecast=False, use_field_ids=None)[source]¶
Create a new record
>>> record = {'Name': 'John'} >>> table = api.table('base_id', 'table_name') >>> table.create(record)
- Parameters
fields (
Dict[str,WritableFieldValue]) – Fields to insert. Must be a dict with field names or IDs as keys.typecast (
bool, default:False) – The Airtable API will perform best-effort automatic data conversion from string values.use_field_ids (
Optional[bool], default:None) – An optional boolean value that lets you return field objects where the key is the field id. This defaults toFalse, which returns field objects where the key is the field name. This behavior can be overridden by passinguse_field_ids=TruetoApi.
- Return type
- batch_create(records, typecast=False, use_field_ids=None)[source]¶
Create a number of new records in batches.
>>> table.batch_create([{'Name': 'John'}, {'Name': 'Marc'}]) [ { 'id': 'recW9e0c9w0er9gug', 'createdTime': '2017-03-14T22:04:31.000Z', 'fields': {'Name': 'John'} }, { 'id': 'recW9e0c9w0er9guh', 'createdTime': '2017-03-14T22:04:31.000Z', 'fields': {'Name': 'Marc'} } ]
- Parameters
records (
Iterable[Dict[str,WritableFieldValue]]) – Iterable of dicts representing records to be created.typecast (
bool, default:False) – The Airtable API will perform best-effort automatic data conversion from string values.use_field_ids (
Optional[bool], default:None) – An optional boolean value that lets you return field objects where the key is the field id. This defaults toFalse, which returns field objects where the key is the field name. This behavior can be overridden by passinguse_field_ids=TruetoApi.
- Return type
List[RecordDict]
- update(record_id, fields, replace=False, typecast=False, use_field_ids=None)[source]¶
Update a particular record ID with the given fields.
>>> table.update('recwPQIfs4wKPyc9D', {"Age": 21}) {'id': 'recwPQIfs4wKPyc9D', 'fields': {'First Name': 'John', 'Age': 21}} >>> table.update('recwPQIfs4wKPyc9D', {"Age": 22}, replace=True) {'id': 'recwPQIfs4wKPyc9D', 'fields': {'Age': 22}}
- Parameters
record_id (
str) – An Airtable record ID.fields (
Dict[str,WritableFieldValue]) – Fields to update. Must be a dict with column names or IDs as keys.replace (
bool, default:False) – IfTrue, record is replaced in its entirety by provided fields; if a field is not included its value will be set to null. IfFalse, only provided fields are updated.typecast (
bool, default:False) – The Airtable API will perform best-effort automatic data conversion from string values.use_field_ids (
Optional[bool], default:None) – An optional boolean value that lets you return field objects where the key is the field id. This defaults toFalse, which returns field objects where the key is the field name. This behavior can be overridden by passinguse_field_ids=TruetoApi.
- Return type
- batch_update(records, replace=False, typecast=False, use_field_ids=None)[source]¶
Update several records in batches.
- Parameters
records (
Iterable[UpdateRecordDict]) – Records to update.replace (
bool, default:False) – IfTrue, record is replaced in its entirety by provided fields; if a field is not included its value will be set to null. IfFalse, only provided fields are updated.typecast (
bool, default:False) – The Airtable API will perform best-effort automatic data conversion from string values.use_field_ids (
Optional[bool], default:None) – An optional boolean value that lets you return field objects where the key is the field id. This defaults toFalse, which returns field objects where the key is the field name. This behavior can be overridden by passinguse_field_ids=TruetoApi.
- Return type
List[RecordDict]- Returns
The list of updated records.
- batch_upsert(records, key_fields, replace=False, typecast=False, use_field_ids=None)[source]¶
Update or create 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
records (
Iterable[Dict[str,Any]]) – Records to update.key_fields (
List[str]) – List of field names that Airtable should use to match records in the input with existing records on the server.replace (
bool, default:False) – IfTrue, record is replaced in its entirety by provided fields; if a field is not included its value will be set to null. IfFalse, only provided fields are updated.typecast (
bool, default:False) – The Airtable API will perform best-effort automatic data conversion from string values.use_field_ids (
Optional[bool], default:None) – An optional boolean value that lets you return field objects where the key is the field id. This defaults toFalse, which returns field objects where the key is the field name. This behavior can be overridden by passinguse_field_ids=TruetoApi.
- Return type
- Returns
Lists of created/updated record IDs, along with the list of all records affected.
- delete(record_id)[source]¶
Delete the given record.
>>> table.delete('recwPQIfs4wKPyc9D') {'id': 'recwPQIfs4wKPyc9D', 'deleted': True}
- Parameters
record_id (
str) – An Airtable record ID.- Return type
- Returns
Confirmation that the record was deleted.
- batch_delete(record_ids)[source]¶
Delete the given records, operating in batches.
>>> table.batch_delete(['recwPQIfs4wKPyc9D', 'recwDxIfs3wDPyc3F']) [ {'id': 'recwPQIfs4wKPyc9D', 'deleted': True}, {'id': 'recwDxIfs3wDPyc3F', 'deleted': True} ]
- Parameters
record_ids (
Iterable[str]) – Record IDs to delete- Return type
List[RecordDeletedDict]- Returns
Confirmation that the records were deleted.
- comments(record_id)[source]¶
Retrieve all comments on the given record.
- Usage:
>>> table = Api.table("appNxslc6jG0XedVM", "tblslc6jG0XedVMNx") >>> table.comments("recMNxslc6jG0XedV") [ Comment( id='comdVMNxslc6jG0Xe', text='Hello, @[usrVMNxslc6jG0Xed]!', created_time=datetime.datetime(...), last_updated_time=None, mentioned={ 'usrVMNxslc6jG0Xed': Mentioned( display_name='Alice', email='alice@example.com', id='usrVMNxslc6jG0Xed', type='user' ) }, author=Collaborator( id='usr0000pyairtable', email='pyairtable@example.com', name='Your pyairtable access token' ) ) ]
- Parameters
record_id (
str) – An Airtable record ID.- Return type
List[Comment]
- add_comment(record_id, text)[source]¶
Create a comment on a record. See Create comment for details.
- Usage:
>>> table = Api.table("appNxslc6jG0XedVM", "tblslc6jG0XedVMNx") >>> comment = table.add_comment("recMNxslc6jG0XedV", "Hello, @[usrVMNxslc6jG0Xed]!") >>> comment.text = "Never mind!" >>> comment.save() >>> comment.delete()
- Parameters
record_id (
str) – An Airtable record ID.text (
str) – The text of the comment. Use@[usrIdentifier]to mention users.
- Return type
- schema(*, force=False)[source]¶
Retrieve the schema of the current table.
- Usage:
>>> table.schema() TableSchema( id='tblslc6jG0XedVMNx', name='My Table', primary_field_id='fld6jG0XedVMNxFQW', fields=[...], views=[...] )
- Parameters
force (
bool, default:False) – By default, this method will only fetch information from the API if it has not been cached. If called withforce=Trueit will always call the API, and will overwrite any cached values.- Return type
- create_field(name, field_type, description=None, options=None)[source]¶
Create a field on the table.
- Usage:
>>> table.create_field("Attachments", "multipleAttachment") FieldSchema( id='fldslc6jG0XedVMNx', name='Attachments', type='multipleAttachment', description=None, options=MultipleAttachmentsFieldOptions(is_reversed=False) )
- Parameters
name (
str) – The unique name of the field.field_type (
str) – One of the Airtable field types.description (
Optional[str], default:None) – A long form description of the table.options (
Optional[Dict[str,Any]], default:None) – Only available for some field types. For more information, read about the Airtable field model.
- Return type
Union[AITextFieldSchema,AutoNumberFieldSchema,BarcodeFieldSchema,ButtonFieldSchema,CheckboxFieldSchema,CountFieldSchema,CreatedByFieldSchema,CreatedTimeFieldSchema,CurrencyFieldSchema,DateFieldSchema,DateTimeFieldSchema,DurationFieldSchema,EmailFieldSchema,ExternalSyncSourceFieldSchema,FormulaFieldSchema,LastModifiedByFieldSchema,LastModifiedTimeFieldSchema,ManualSortFieldSchema,MultilineTextFieldSchema,MultipleAttachmentsFieldSchema,MultipleCollaboratorsFieldSchema,MultipleLookupValuesFieldSchema,MultipleRecordLinksFieldSchema,MultipleSelectsFieldSchema,NumberFieldSchema,PercentFieldSchema,PhoneNumberFieldSchema,RatingFieldSchema,RichTextFieldSchema,RollupFieldSchema,SingleCollaboratorFieldSchema,SingleLineTextFieldSchema,SingleSelectFieldSchema,UrlFieldSchema,UnknownFieldSchema]
- upload_attachment(record_id, field, filename, content=None, content_type=None)[source]¶
Upload an attachment to the Airtable API, either by supplying the path to the file or by providing the content directly as a variable.
See Upload attachment.
- Usage:
>>> table.upload_attachment("recAdw9EjV90xbZ", "Attachments", "/tmp/example.jpg") { 'id': 'recAdw9EjV90xbZ', 'createdTime': '2023-05-22T21:24:15.333134Z', 'fields': { 'Attachments': [ { 'id': 'attW8eG2x0ew1Af', 'url': 'https://content.airtable.com/...', 'filename': 'example.jpg' } ] } }
- Parameters
record_id (
str) – An Airtable record ID.field (
str) – The ID or name of themultipleAttachmentstype field.filename (
Union[str,Path]) – The path to the file to upload. Ifcontentis provided, this argument is still used to tell Airtable what name to give the file.content (
Union[str,bytes,None], default:None) – The content of the file as a string or bytes object. If no value is provided, pyAirtable will attempt to read the contents offilename.content_type (
Optional[str], default:None) – The MIME type of the file. If not provided, the library will attempt to guess the content type based onfilename.
- Return type
- Returns
A full list of attachments in the given field, including the new attachment.
- class pyairtable.Workspace[source]¶
Represents an Airtable workspace, which contains a number of bases and its own set of collaborators.
>>> ws = api.workspace("wspmhESAta6clCCwF") >>> ws.collaborators().name 'my first workspace' >>> ws.create_base("Base Name", tables=[...]) <pyairtable.Base base_id="appMhESAta6clCCwF">
Most workspace functionality is limited to users on Enterprise billing plans.
- property urls¶
URLs associated with
Workspacecan be accessed via.urlsusing the following syntax:>>> workspace = Workspace(...) >>> workspace.urls.meta Url('https://api.airtable.com/...')
These properties are all instances of
Url.- _urls.meta = Url('meta/workspaces/{id}')
URL for retrieving the workspace’s metadata and collaborators.
- _urls.move_base = Url('meta/workspaces/{id}/moveBase')
URL for moving a base to a new workspace.
- _urls.collaborators = Url('meta/workspaces/{id}/collaborators')
URL for POST requests that modify collaborations on the workspace.
- create_base(name, tables)[source]¶
Create a base in the given workspace.
See https://airtable.com/developers/web/api/create-base
- Parameters
name (
str) – The name to give to the new base. Does not need to be unique.tables (
Sequence[Dict[str,Any]]) – A list ofdictobjects that conform to Airtable’s Table model.
- Return type
- collaborators()[source]¶
⚠ This feature is only available on Enterprise billing plans.
Retrieve basic information, collaborators, and invite links for the given workspace, caching the result.
See https://airtable.com/developers/web/api/get-workspace-collaborators
- Parameters
force (
bool) – By default, this method will only fetch information from the API if it has not been cached. If called withforce=Trueit will always call the API, and will overwrite any cached values.- Return type
- bases()[source]¶
⚠ This feature is only available on Enterprise billing plans.
Retrieve all bases within the workspace.
- Return type
List[Base]
- property name: str¶
⚠ This feature is only available on Enterprise billing plans.
The name of the workspace.
- Return type
str
- delete()[source]¶
⚠ This feature is only available on Enterprise billing plans.
Delete the workspace.
See https://airtable.com/developers/web/api/delete-workspace
- Usage:
>>> ws = api.workspace("wspmhESAta6clCCwF") >>> ws.delete()
- Return type
None
- move_base(base, target, index=None)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Move the given base to a new workspace.
See https://airtable.com/developers/web/api/move-base
- Usage:
>>> base = api.base("appCwFmhESAta6clC") >>> ws = api.workspace("wspmhESAta6clCCwF") >>> ws.move_base(base, "wspSomeOtherPlace", index=0)
- Return type
None
- class pyairtable.Enterprise[source]¶
⚠ This feature is only available on Enterprise billing plans.
Represents an Airtable enterprise account.
>>> enterprise = api.enterprise("entUBq2RGdihxl3vU") >>> enterprise.info().workspace_ids ['wspmhESAta6clCCwF', ...]
- property urls¶
URLs associated with
Enterprisecan be accessed via.urlsusing the following syntax:>>> enterprise = Enterprise(...) >>> enterprise.urls.meta Url('https://api.airtable.com/...')
These properties are all instances of
Url.- _urls.meta = Url('meta/enterpriseAccounts/{id}')
URL for retrieving basic information about the enterprise.
- _urls.users = Url('meta/enterpriseAccounts/{id}/users')
URL for retrieving information about all users.
- _urls.groups = Url('meta/groups')
URL for retrieving information about all user groups.
- _urls.claim_users = Url('meta/enterpriseAccounts/{id}/claim/users')
URL for claiming a user into an enterprise.
- _urls.audit_log = Url('meta/enterpriseAccounts/{id}/auditLogEvents')
URL for retrieving audit log events.
- _urls.descendants = Url('meta/enterpriseAccounts/{id}/descendants')
URL for managing descendant enterprise accounts.
- _urls.move_groups = Url('meta/enterpriseAccounts/{id}/moveGroups')
URL for moving user groups between enterprise accounts.
- _urls.move_workspaces = Url('meta/enterpriseAccounts/{id}/moveWorkspaces')
URL for moving workspaces between enterprise accounts.
- _urls.create_workspace = Url('meta/workspaces')
URL for creating a new workspace.
- _urls.packages = Url('meta/enterpriseAccounts/{id}/packages')
URL for listing enterprise packages.
- _urls.package_install(package_id)[source]
URL for installing a package (creating a base from a package).
- Return type
- _urls.group(group_id)[source]
URL for retrieving information about a single user group.
- Return type
- _urls.admin_access(action)[source]
URL for granting or revoking admin access to one or more users.
- Return type
- info(*, aggregated=False, descendants=False)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Retrieve basic information about the enterprise, caching the result. Calls Get enterprise.
- Parameters
aggregated (
bool, default:False) – ifTrue, include aggregated values across the enterprise.descendants (
bool, default:False) – ifTrue, include information about the enterprise’s descendant orgs.force (
bool) – By default, this method will only fetch information from the API if it has not been cached. If called withforce=Trueit will always call the API, and will overwrite any cached values.
- Return type
- group(group_id, collaborations=True)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Retrieve information on a single user group with the given ID.
- Parameters
group_id (
str) – A user group ID (grpQBq2RGdihxl3vU).collaborations (
bool, default:True) – IfFalse, no collaboration data will be requested from Airtable. This may result in faster responses.
- Return type
- user(id_or_email, *, collaborations=True, aggregated=False, descendants=False)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Retrieve information on a single user with the given ID or email.
- Parameters
id_or_email (
str) – A user ID (usrQBq2RGdihxl3vU) or email address.collaborations (
bool, default:True) – IfFalse, no collaboration data will be requested from Airtable. This may result in faster responses.aggregated (
bool, default:False) – IfTrue, includes the user’s aggregated values across this enterprise account and its descendants.descendants (
bool, default:False) – IfTrue, includes information about the user in adictkeyed per descendant enterprise account.
- Return type
- users(ids_or_emails, *, collaborations=True, aggregated=False, descendants=False)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Retrieve information on the users with the given IDs or emails.
Read more at Get users by ID or email.
- Parameters
ids_or_emails (
Iterable[str]) – A sequence of user IDs (usrQBq2RGdihxl3vU) or email addresses (or both).collaborations (
bool, default:True) – IfFalse, no collaboration data will be requested from Airtable. This may result in faster responses.aggregated (
bool, default:False) – IfTrue, includes the user’s aggregated values across this enterprise account and its descendants.descendants (
bool, default:False) – IfTrue, includes information about the user in adictkeyed per descendant enterprise account.
- Return type
List[UserInfo]
- audit_log(*, page_size=None, page_limit=None, sort_asc=False, previous=None, next=None, start_time=None, end_time=None, user_id=None, event_type=None, model_id=None, category=None)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Retrieve and yield results from the Audit Log, one page of results at a time. Each result is an instance of
AuditLogResponseand contains the pagination IDs returned from the API, as described in the linked documentation.By default, the Airtable API will return up to 180 days of audit log events, going backwards from most recent. Retrieving all records may take some time, but is as straightforward as:
>>> enterprise = Enterprise("entYourEnterpriseId") >>> events = [ ... event ... for page in enterprise.audit_log() ... for event in page.events ... ]
If you are creating a record of all audit log events, you probably want to start with the earliest events in the retention window and iterate chronologically. You’ll likely have a job running periodically in the background, so you’ll need some way to persist the pagination IDs retrieved from the API in case that job is interrupted and needs to be restarted.
The sample code below will use a local file to remember the next page’s ID, so that if the job is interrupted, it will resume where it left off (potentially processing some entries twice).
import os import shelve import pyairtable def handle_event(event): print(event) api = pyairtable.Api(os.environ["AIRTABLE_API_KEY"]) enterprise = api.enterprise(os.environ["AIRTABLE_ENTERPRISE_ID"]) persistence = shelve.open("audit_log.db") first_page = persistence.get("next", None) for page in enterprise.audit_log(sort_asc=True, next=first_page): for event in page.events: handle_event(event) persistence["next"] = page.pagination.next
For more information on any of the keyword parameters below, refer to the audit log events API documentation.
- Parameters
page_size (
Optional[int], default:None) – How many events per page to return (maximum 100).page_limit (
Optional[int], default:None) – How many pages to return before stopping.sort_asc (
Optional[bool], default:False) – Whether to sort in ascending order (earliest to latest) rather than descending order (latest to earliest).previous (
Optional[str], default:None) – Requests the previous page of results from the given ID. See the audit log integration guide for more information on pagination parameters.next (
Optional[str], default:None) – Requests the next page of results according to the given ID. See the audit log integration guide for more information on pagination parameters.start_time (
Union[str,date,datetime,None], default:None) – Earliest timestamp to retrieve (inclusive).end_time (
Union[str,date,datetime,None], default:None) – Latest timestamp to retrieve (inclusive).originating_user_id – Retrieve audit log events originating from the provided user ID or IDs (maximum 100).
event_type (
Union[str,Iterable[str],None], default:None) – Retrieve audit log events falling under the provided audit log event type or types (maximum 100).model_id (
Union[str,Iterable[str],None], default:None) – Retrieve audit log events taking action on, or involving, the provided model ID or IDs (maximum 100).category (
Union[str,Iterable[str],None], default:None) – Retrieve audit log events belonging to the provided audit log event category or categories.
- Return type
Iterator[AuditLogResponse]- Returns
An object representing a single page of audit log results.
- remove_user(user_id, replacement=None, *, descendants=False)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Unshare a user from all enterprise workspaces, bases, and interfaces. If applicable, the user will also be removed from as an enterprise admin.
See Remove user from enterprise for more information.
- Parameters
user_id (
str) – The user ID.replacement (
Optional[str], default:None) – If the user is the sole owner of any workspaces, you must specify a replacement user ID to be added as the new owner of such workspaces. If the user is not the sole owner of any workspaces, this is optional and will be ignored if provided.descendants (
bool, default:False) – IfTrue, removes the user from descendant enterprise accounts.
- Return type
- claim_users(users)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Batch manage organizations enterprise account users. This endpoint allows you to change a user’s membership status from being unmanaged to being an organization member, and vice versa.
See Manage user membership for more information.
- Parameters
users (
Dict[str,Literal[‘managed’, ‘unmanaged’]]) – Adictmapping user IDs or emails to the desired state, either"managed"or"unmanaged".- Return type
- delete_users(emails)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Delete multiple users by email.
- Parameters
emails (
Iterable[str]) – A list or other iterable of email addresses.- Return type
- grant_admin(*users)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Grant admin access to one or more users.
- revoke_admin(*users)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Revoke admin access to one or more users.
- create_descendant(name)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Creates a descendant enterprise account of the enterprise account. Descendant enterprise accounts can only be created for root enterprise accounts with the Enterprise Hub feature enabled.
See Create descendant enterprise.
- Parameters
name (
str) – The name to give the new account.- Return type
Self
- move_groups(group_ids, target)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Move one or more user groups from the current enterprise account into a different enterprise account within the same organization.
See Move user groups.
- Parameters
group_ids (
Iterable[str]) – User group IDs.target (
Union[str,Self]) – The ID of the target enterprise, or an instance ofEnterprise.
- Return type
- move_workspaces(workspace_ids, target)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Move one or more workspaces from the current enterprise account into a different enterprise account within the same organization.
See Move workspaces.
- Parameters
workspace_ids (
Iterable[str]) – The list of workspace IDs.target (
Union[str,Self]) – The ID of the target enterprise, or an instance ofEnterprise.
- Return type
- create_workspace(name)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Creates a new workspace with the provided name within the enterprise account and returns the workspace ID. The requesting user must be an active effective admin of the enterprise account; the created workspace’s owner will be the user who makes the request.
See Create workspace.
- Parameters
name (
str) – The name of the workspace to be created.- Return type
- Returns
The ID of the newly created workspace.
- packages(*, all_enterprises=False)[source]¶
⚠ This feature is only available on Enterprise billing plans.
List all packages for the enterprise account.
See List packages.
- Parameters
all_enterprises (
bool, default:False) – If True and the enterprise account is the root enterprise account, returns all packages across the entire enterprise grid. Defaults to False.force (
bool) – By default, this method will only fetch information from the API if it has not been cached. If called withforce=Trueit will always call the API, and will overwrite any cached values.
- Return type
List[Package]- Returns
A list of Package objects representing the enterprise packages.
- package(package_id, *, force=False)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Retrieve information about a single package by ID.
- Parameters
package_id (
str) – The ID of the package to retrieve.force (
bool, default:False) – IfTrue, forces a refresh of the cached package list.
- Return type
- Returns
A Package object representing the enterprise package.
- create_base(workspace, name, tables)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Create a base in the given workspace.
See https://airtable.com/developers/web/api/create-base
- Parameters
workspace (
Union[str,Workspace]) – The ID of the workspace or aWorkspaceobject.name (
str) – The name to give to the new base. Does not need to be unique.tables (
Sequence[Dict[str,Any]]) – A list ofdictobjects that conform to Airtable’s Table model.
- Return type
- create_base_from_package(workspace, name, package_or_release, *, description=None)[source]¶
⚠ This feature is only available on Enterprise billing plans.
Create a base from an enterprise package template in the specified workspace.
See https://airtable.com/developers/web/api/create-base-from-package-enterprise
- Parameters
workspace (
Union[str,Workspace]) – The ID of the workspace or aWorkspaceobject.name (
str) – The name for the new base.package_or_release (
Union[str,Package]) – APackageobject, a package ID (pkg...), or a package release ID. When a package or package ID is given, the package’s latest release is installed. Any other string is forwarded to the API as the release ID.description (
Optional[str], default:None) – Optional description for the base.
- Return type
- Returns
The newly created Base object.
- Raises
MissingRecordError – If the given package ID is not found.
InvalidParameterError – If the resolved package has no latest release.
- pyairtable.retry_strategy(*, status_forcelist=(429,), backoff_factor=0.1, total=5, allowed_methods=None, **kwargs)[source]¶
Create a Retry instance with adjustable default values.
Apiaccepts this via theretry_strategy=parameter.For example, to increase the total number of retries:
>>> from pyairtable import Api, retry_strategy >>> api = Api('auth_token', retry_strategy=retry_strategy(total=10))
Or to retry certain types of server errors in addition to rate limiting errors:
>>> from pyairtable import Api, retry_strategy >>> retry = retry_strategy(status_forcelist=(429, 500, 502, 503, 504)) >>> api = Api('auth_token', retry_strategy=retry)
You can also disable retries entirely:
>>> from pyairtable import Api >>> api = Api('auth_token', retry_strategy=None)
New in version 1.4.0.
- Parameters
status_forcelist (
Tuple[int,...], default:(429,)) – Status codes which should be retried.allowed_methods (
Optional[Collection[str]], default:None) – HTTP methods which can be retried. IfNone, then all HTTP methods will be retried.backoff_factor (
Union[int,float], default:0.1) – A backoff factor to apply between attempts after the second try. Sleep time between each request will be calculated asbackoff_factor * (2 ** (retry_count - 1))total (
int, default:5) – Maximum number of retries. Note that0means no retries, whereas1will execute a total of two requests (original + 1 retry).**kwargs – Accepts any valid parameter to Retry.
- Return type
Retry
API: pyairtable.api.enterprise¶
- pydantic model pyairtable.api.enterprise.UserRemoved[source]¶
Returned from the Remove user from enterprise endpoint.
- field was_user_removed_as_admin: bool¶
- pydantic model pyairtable.api.enterprise.DeleteUsersResponse[source]¶
Returned from the Delete users by email endpoint.
- field deleted_users: List[DeleteUsersResponse.UserInfo]¶
- field errors: List[DeleteUsersResponse.Error]¶
- pydantic model pyairtable.api.enterprise.ManageUsersResponse[source]¶
Returned from the Manage user membership, Grant admin access, and Revoke admin access endpoints.
- field errors: List[ManageUsersResponse.Error] [Optional]¶
- pydantic model pyairtable.api.enterprise.MoveError[source]¶
- field id: str¶
- field type: str¶
- field message: str¶
- pydantic model pyairtable.api.enterprise.MoveGroupsResponse[source]¶
Returned by Move user groups.
- field moved_groups: List[pyairtable.models.schema.NestedId] [Optional]¶
- field errors: List[pyairtable.api.enterprise.MoveError] [Optional]¶
- pydantic model pyairtable.api.enterprise.MoveWorkspacesResponse[source]¶
Returned by Move workspaces.
- field moved_workspaces: List[pyairtable.models.schema.NestedId] [Optional]¶
- field errors: List[pyairtable.api.enterprise.MoveError] [Optional]¶
API: pyairtable.api.types¶
pyAirtable provides a number of type aliases and TypedDicts which are used as inputs and return values to various pyAirtable methods.
- pyairtable.api.types.RecordId¶
An alias for
strused internally for disambiguation. Record IDs for Airtable look like"recAdw9EjV90xbZ".
- pyairtable.api.types.Timestamp¶
An alias for
strused internally for disambiguation. Airtable returns timestamps as ISO 8601 UTC strings, e.g."2023-05-22T21:24:15.333134Z"
- pyairtable.api.types.FieldName¶
An alias for
strused internally for disambiguation. Field names can be any valid string.
- class pyairtable.api.types.AITextDict[source]¶
A
dictrepresenting text generated by AI.>>> record = table.get('recW8eG2x0ew1Af') >>> record['fields']['Generated Text'] { 'state': 'generated', 'isStale': False, 'value': '...' }
- class pyairtable.api.types.AttachmentDict[source]¶
A
dictrepresenting an attachment stored in an Attachments field.>>> record = table.get('recW8eG2x0ew1Af') >>> record['fields']['Attachments'] [ { 'id': 'attW8eG2x0ew1Af', 'url': 'https://example.com/hello.jpg', 'filename': 'hello.jpg' } ]
See https://airtable.com/developers/web/api/field-model#multipleattachment
- class pyairtable.api.types.CreateAttachmentById[source]¶
A
dictrepresenting a new attachment to be written to the Airtable API.>>> new_attachment = {"id": "attW8eG2x0ew1Af"} >>> existing = record["fields"].setdefault("Attachments", []) >>> existing.append(new_attachment) >>> table.update(existing["id"], existing["fields"])
- class pyairtable.api.types.CreateAttachmentByUrl[source]¶
A
dictrepresenting a new attachment to be written to the Airtable API.>>> new_attachment = { ... "url": "https://example.com/image.jpg", ... "filename": "something_else.jpg", ... } >>> existing = record["fields"].setdefault("Attachments", []) >>> existing.append(new_attachment) >>> table.update(existing["id"], existing["fields"])
- class pyairtable.api.types.BarcodeDict[source]¶
A
dictrepresenting the value stored in a Barcode field.>>> record = table.get('recW8eG2x0ew1Af') >>> record['fields']['Barcode'] {'type': 'upce', 'text': '01234567'}
See https://airtable.com/developers/web/api/field-model#barcode
- class pyairtable.api.types.ButtonDict[source]¶
A
dictrepresenting the value stored in a Button field.>>> record = table.get('recW8eG2x0ew1Af') >>> record['fields']['Click Me'] {'label': 'Click Me', 'url': 'http://example.com'}
See https://airtable.com/developers/web/api/field-model#button
- class pyairtable.api.types.CollaboratorDict[source]¶
A dict representing the value stored in a User field returned from the API.
>>> record = table.get('recW8eG2x0ew1Af') >>> record['fields']['Created By'] { 'id': 'usrAdw9EjV90xbW', 'email': 'alice@example.com', 'name': 'Alice Arnold' } >>> record['fields']['Collaborators'] [ { 'id': 'usrAdw9EjV90xbW', 'email': 'alice@example.com', 'name': 'Alice Arnold' }, { 'id': 'usrAdw9EjV90xbX', 'email': 'bob@example.com', 'name': 'Bob Barker' } ]
See https://airtable.com/developers/web/api/field-model#collaborator
- class pyairtable.api.types.CollaboratorEmailDict[source]¶
A dict representing a collaborator identified by email, not by ID. Often used when writing to the API, because the email of a collaborator may be more easily accessible than their Airtable user ID.
>>> table = Table("access_token", "base_id", "api_key") >>> record = table.update("recW8eG2x0ew1Af", { ... "Collaborator": {"email": "alice@example.com"} ... }) >>> record { 'id': 'recW8eG2x0ew1Af', 'createdTime': 2023-06-07T17:35:17Z', 'fields': { 'Collaborator': { 'id': 'usrAdw9EjV90xbW', 'email': 'alice@example.com', 'name': 'Alice Arnold' } } }
- class pyairtable.api.types.AddUserCollaboratorDict[source]¶
Used to add a user as a collaborator to a base, workspace, or interface.
- class pyairtable.api.types.AddGroupCollaboratorDict[source]¶
Used to add a group as a collaborator to a base, workspace, or interface.
- pyairtable.api.types.FieldValue: TypeAlias = typing.Any¶
Represents the types of values that we might receive from the API. At present, is an alias for
Anybecause we don’t want to lose forward compatibility with any changes Airtable makes in the future.
- pyairtable.api.types.Fields¶
A mapping of field names to values that we might receive from the API.
alias of
Dict[str,Any]
- pyairtable.api.types.WritableFieldValue¶
Represents the types of values that can be written to the Airtable API.
alias of
Union[None,str,int,float,bool,pyairtable.api.types.CollaboratorDict,pyairtable.api.types.CollaboratorEmailDict,pyairtable.api.types.BarcodeDict,List[str],List[pyairtable.api.types.AttachmentDict],List[Union[pyairtable.api.types.CreateAttachmentById,pyairtable.api.types.CreateAttachmentByUrl]],List[pyairtable.api.types.CollaboratorDict],List[pyairtable.api.types.CollaboratorEmailDict]]
- pyairtable.api.types.WritableFields¶
A mapping of field names to values which can be sent to the API.
alias of
Dict[str,Union[None,str,int,float,bool,pyairtable.api.types.CollaboratorDict,pyairtable.api.types.CollaboratorEmailDict,pyairtable.api.types.BarcodeDict,List[str],List[pyairtable.api.types.AttachmentDict],List[Union[pyairtable.api.types.CreateAttachmentById,pyairtable.api.types.CreateAttachmentByUrl]],List[pyairtable.api.types.CollaboratorDict],List[pyairtable.api.types.CollaboratorEmailDict]]]
- class pyairtable.api.types.RecordDict[source]¶
A
dictrepresenting a record returned from the Airtable API. See List records.- Usage:
>>> table.first(formula="Name = 'Alice'") { 'id': 'recAdw9EjV90xbW', 'createdTime': '2023-05-22T21:24:15.333134Z', 'fields': {'Name': 'Alice', 'Department': 'Engineering'} }
>>> table.first(count_comments=True) { 'id': 'recAdw9EjV90xbW', 'createdTime': '2023-05-22T21:24:15.333134Z', 'fields': {'Name': 'Alice'}, 'commentCount': 5 }
- class pyairtable.api.types.CreateRecordDict[source]¶
A
dictrepresenting the payload passed to the Airtable API to create a record.Field values must each be a
WritableFieldValue.- Usage:
>>> table.create({ ... "fields": { ... "Field Name": "Field Value", ... "Other Field": ["Value 1", "Value 2"] ... } ... })
- class pyairtable.api.types.UpdateRecordDict[source]¶
A
dictrepresenting the payload passed to the Airtable API to update a record.Field values must each be a
WritableFieldValue.- Usage:
>>> table.batch_update([ ... { ... "id": "recAdw9EjV90xbW", ... "fields": { ... "Email": "alice@example.com" ... } ... }, ... { ... "id": "recAdw9EjV90xbX", ... "fields": { ... "Email": "bob@example.com" ... } ... } ... ])
- class pyairtable.api.types.RecordDeletedDict[source]¶
A
dictrepresenting the payload returned by the Airtable API to confirm a deletion.- Usage:
>>> table.delete("recAdw9EjV90xbZ") {'id': 'recAdw9EjV90xbZ', 'deleted': True}
- class pyairtable.api.types.UpsertResultDict[source]¶
A
dictrepresenting the payload returned by the Airtable API after an upsert. For more details on this data structure, see the Update multiple records API documentation.- Usage:
>>> table.batch_upsert(records, key_fields=["Name"]) { 'createdRecords': [...], 'updatedRecords': [...], 'records': [...] }
- class pyairtable.api.types.UserAndScopesDict[source]¶
A
dictrepresenting the Get user ID & scopes endpoint.- Usage:
>>> api.whoami() {'id': 'usrX9e810wHn3mMLz'}
- class pyairtable.api.types.UploadAttachmentResultDict[source]¶
A
dictrepresenting the payload returned by Upload attachment.- Usage:
>>> table.upload_attachment("recAdw9EjV90xbZ", "Attachments", "/tmp/example.jpg") { 'id': 'recAdw9EjV90xbZ', 'createdTime': '2023-05-22T21:24:15.333134Z', 'fields': { 'Attachments': [ { 'id': 'attW8eG2x0ew1Af', 'url': 'https://content.airtable.com/...', 'filename': 'example.jpg' } ] } }
- pyairtable.api.types.assert_typed_dict(cls, obj)[source]¶
Raises a TypeError if the given object is not a dict, or raises pydantic.ValidationError if the given object does not conform to the interface declared by the given TypedDict.
- Parameters
cls (
Type[TypeVar(T)]) – The TypedDict class.obj (
Any) – The object that should be a TypedDict.
- Usage:
>>> assert_typed_dict( ... RecordDict, ... { ... "id": "recAdw9EjV90xbZ", ... "createdTime": "2023-05-22T21:24:15.333134Z", ... "fields": {}, ... } ... ) { 'id': 'recAdw9EjV90xbZ', 'createdTime': '2023-05-22T21:24:15.333134Z', 'fields': {} }
>>> assert_typed_dict(RecordDict, {"foo": "bar"}) Traceback (most recent call last): pydantic.error_wrappers.ValidationError: 3 validation errors for RecordDict id field required (type=value_error.missing) createdTime field required (type=value_error.missing) fields field required (type=value_error.missing)
- Return type
TypeVar(T)
- pyairtable.api.types.assert_typed_dicts(cls, objects)[source]¶
Like
assert_typed_dict()but for a list of dicts.- Parameters
cls (
Type[TypeVar(T)]) – The TypedDict class.objects (
Any) – The object that should be a list of TypedDicts.
- Return type
List[TypeVar(T)]
API: pyairtable.exceptions¶
- exception pyairtable.exceptions.PyAirtableError[source]¶
Base class for all exceptions raised by PyAirtable.
- exception pyairtable.exceptions.CircularFormulaError[source]¶
A circular dependency was encountered when flattening nested conditions.
- exception pyairtable.exceptions.InvalidParameterError[source]¶
Raised when invalid parameters are passed to
all(),first(), etc.
- exception pyairtable.exceptions.MissingRecordError[source]¶
A requested record was not found in Airtable.
- exception pyairtable.exceptions.MissingValueError[source]¶
A required field received an empty value, either from Airtable or other code.
- exception pyairtable.exceptions.MultipleValuesError[source]¶
SingleLinkField received more than one value from either Airtable or calling code.
API: pyairtable.formulas¶
This module exports building blocks for constructing Airtable formulas, including function call proxies for all formula functions as of Dec ‘23.
See Building Formulas for more information.
- class pyairtable.formulas.Formula[source]¶
Represents an Airtable formula that can be combined with other formulas or converted to a string. On its own, this class simply wraps a
strso that it will be not be modified or escaped as if it were a value.>>> Formula("{Column} = 1") Formula('{Column} = 1') >>> str(_) '{Column} = 1'
- class pyairtable.formulas.Comparison[source]¶
Represents a logical condition that compares two expressions.
- class pyairtable.formulas.Compound[source]¶
Represents a boolean logical operator (AND, OR, etc.) wrapping around one or more component formulas.
- pyairtable.formulas.AND(*components, **fields)[source]¶
Join one or more logical conditions into an AND compound condition. Keyword arguments will be treated as field names.
>>> AND(EQ("foo", 1), EQ(Field("bar"), 2), baz=3) AND(EQ('foo', 1), EQ(Field('bar'), 2), EQ(Field('baz'), 3))
- Return type
- pyairtable.formulas.OR(*components, **fields)[source]¶
Join one or more logical conditions into an OR compound condition. Keyword arguments will be treated as field names.
>>> OR(EQ("foo", 1), EQ(Field("bar"), 2), baz=3) OR(EQ('foo', 1), EQ(Field('bar'), 2), EQ(Field('baz'), 3))
- Return type
- pyairtable.formulas.NOT(component=None, /, **fields)[source]¶
Wrap one logical condition in a negation compound. Keyword arguments will be treated as field names.
Can be called with either a formula or with a single kewyord argument, but not both.
>>> NOT(EQ("foo", 1)) NOT(EQ('foo', 1))
>>> NOT(foo=1) NOT(EQ(Field('foo'), 1))
If not called with exactly one condition, will throw an exception:
>>> NOT(EQ("foo", 1), EQ("bar", 2)) Traceback (most recent call last): TypeError: NOT() takes from 0 to 1 positional arguments but 2 were given
>>> NOT(EQ("foo", 1), bar=2) Traceback (most recent call last): ValueError: NOT() requires exactly one condition; got 2
>>> NOT(foo=1, bar=2) Traceback (most recent call last): ValueError: NOT() requires exactly one condition; got 2
>>> NOT() Traceback (most recent call last): ValueError: NOT() requires exactly one condition; got 0
- Return type
- pyairtable.formulas.match(field_values, *, match_any=False)[source]¶
Create one or more equality expressions for each provided value, treating keys as field names and values as values (not formula expressions).
If more than one assertion is included, the expressions are grouped together into using
AND()(all values must match). Ifmatch_any=True, expressions are grouped withOR().>>> match({"First Name": "John", "Age": 21}) AND(EQ(Field('First Name'), 'John'), EQ(Field('Age'), 21))
>>> match({"First Name": "John", "Age": 21}, match_any=True) OR(EQ(Field('First Name'), 'John'), EQ(Field('Age'), 21))
To use comparisons other than equality, use a 2-tuple of
(operator, value)as the value for a particular field. For example:>>> match({"First Name": "John", "Age": (">=", 21)}) AND(EQ(Field('First Name'), 'John'), GTE(Field('Age'), 21))
If you need more advanced matching you can build formula expressions using lower level primitives.
- Parameters
field_values (
Dict[str,Any]) – mapping of column names to values (or to 2-tuples of the format(operator, value)).match_any (
bool, default:False) – IfTrue, matches if any of the provided values match. Otherwise, all values must match.
- Return type
- pyairtable.formulas.to_formula(value)[source]¶
Converts the given value into a Formula object.
When given a Formula object, it returns the object as-is:
>>> to_formula(EQ(F.Formula("a"), "b")) EQ(Formula('a'), 'b')
When given a scalar value, it simply wraps that value’s string representation in a Formula object:
>>> to_formula(1) Formula('1') >>> to_formula('foo') Formula("'foo'")
Boolean and date values receive custom function calls:
>>> to_formula(True) TRUE() >>> to_formula(False) FALSE() >>> to_formula(datetime.date(2023, 12, 1)) DATETIME_PARSE('2023-12-01') >>> to_formula(datetime.datetime(2023, 12, 1, 12, 34, 56)) DATETIME_PARSE('2023-12-01T12:34:56.000Z')
- Return type
- pyairtable.formulas.to_formula_str(value)[source]¶
Converts the given value into a string representation that can be used in an Airtable formula expression.
>>> to_formula_str(EQ(F.Formula("a"), "b")) "a='b'" >>> to_formula_str(True) 'TRUE()' >>> to_formula_str(False) 'FALSE()' >>> to_formula_str(3) '3' >>> to_formula_str(3.5) '3.5' >>> to_formula_str(Decimal("3.14159265")) '3.14159265' >>> to_formula_str(Fraction("4/19")) '4/19' >>> to_formula_str("asdf") "'asdf'" >>> to_formula_str("Jane's") "'Jane\'s'" >>> to_formula_str(datetime.date(2023, 12, 1)) "DATETIME_PARSE('2023-12-01')" >>> to_formula_str(datetime.datetime(2023, 12, 1, 12, 34, 56)) "DATETIME_PARSE('2023-12-01T12:34:56.000Z')"
- Return type
str
- pyairtable.formulas.quoted(value)[source]¶
Wrap string in quotes. This is needed when referencing a string inside a formula. Quotes are escaped.
>>> quoted("John") "'John'" >>> quoted("Guest's Name") "'Guest\\'s Name'"
- Return type
str
- pyairtable.formulas.escape_quotes(value)[source]¶
Ensure any quotes are escaped. Already escaped quotes are ignored.
This function has been deprecated. Use
quoted()instead.- Parameters
value (
str) – text to be escaped
- Usage:
>>> escape_quotes(r"Player's Name") "Player\\'s Name" >>> escape_quotes(r"Player\'s Name") "Player\\'s Name"
- Return type
str
- pyairtable.formulas.field_name(name)[source]¶
Create a reference to a field. Quotes are escaped.
- Parameters
name (
str) – field name
- Usage:
>>> field_name("First Name") '{First Name}' >>> field_name("Guest's Name") "{Guest's Name}"
- Return type
str
- class pyairtable.formulas.FunctionCall[source]¶
Represents a function call in an Airtable formula, and converts all arguments to that function into Airtable formula expressions.
>>> FunctionCall("WEEKDAY", datetime.date(2024, 1, 1)) WEEKDAY(datetime.date(2024, 1, 1)) >>> str(_) "WEEKDAY(DATETIME_PARSE('2024-01-01'))"
pyAirtable exports shortcuts like
WEEKDAY()for all formula functions known at time of publishing.
- pyairtable.formulas.AVERAGE(number, /, *numbers)[source]¶
Returns the average of the numbers.
- Return type
- pyairtable.formulas.CEILING(value, significance=None, /)[source]¶
Returns the nearest integer multiple of significance that is greater than or equal to the value. If no significance is provided, a significance of 1 is assumed.
- Return type
- pyairtable.formulas.CONCATENATE(text, /, *texts)[source]¶
Joins together the text arguments into a single text value.
- Return type
- pyairtable.formulas.COUNT(number, /, *numbers)[source]¶
Count the number of numeric items.
- Return type
- pyairtable.formulas.COUNTA(value, /, *values)[source]¶
Count the number of non-empty values. This function counts both numeric and text values.
- Return type
- pyairtable.formulas.COUNTALL(value, /, *values)[source]¶
Count the number of all elements including text and blanks.
- Return type
- pyairtable.formulas.CREATED_TIME()[source]¶
Returns the date and time a given record was created.
- Return type
- pyairtable.formulas.DATEADD(date, number, units, /)[source]¶
Adds specified “count” units to a datetime. (See list of shared unit specifiers. For this function we recommend using the full unit specifier for your desired unit.)
- Return type
- pyairtable.formulas.DATESTR(date, /)[source]¶
Formats a datetime into a string (YYYY-MM-DD).
- Return type
- pyairtable.formulas.DATETIME_DIFF(date1, date2, units, /)[source]¶
Returns the difference between datetimes in specified units. The difference between datetimes is determined by subtracting [date2] from [date1]. This means that if [date2] is later than [date1], the resulting value will be negative.
- Return type
- pyairtable.formulas.DATETIME_FORMAT(date, output_format=None, /)[source]¶
Formats a datetime into a specified string. See an explanation of how to use this function with date fields or a list of supported format specifiers.
- Return type
- pyairtable.formulas.DATETIME_PARSE(date, input_format=None, locale=None, /)[source]¶
Interprets a text string as a structured date, with optional input format and locale parameters. The output format will always be formatted ‘M/D/YYYY h:mm a’.
- Return type
- pyairtable.formulas.DAY(date, /)[source]¶
Returns the day of the month of a datetime in the form of a number between 1-31.
- Return type
- pyairtable.formulas.ENCODE_URL_COMPONENT(component_string, /)[source]¶
Replaces certain characters with encoded equivalents for use in constructing URLs or URIs. Does not encode the following characters:
-_.~- Return type
- pyairtable.formulas.EVEN(value, /)[source]¶
Returns the smallest even integer that is greater than or equal to the specified value.
- Return type
- pyairtable.formulas.EXP(power, /)[source]¶
Computes Euler’s number (e) to the specified power.
- Return type
- pyairtable.formulas.FALSE()[source]¶
Logical value false. False is represented numerically by a 0.
- Return type
- pyairtable.formulas.FIND(string_to_find, where_to_search, start_from_position=None, /)[source]¶
Finds an occurrence of stringToFind in whereToSearch string starting from an optional startFromPosition.(startFromPosition is 0 by default.) If no occurrence of stringToFind is found, the result will be 0.
- Return type
- pyairtable.formulas.FLOOR(value, significance=None, /)[source]¶
Returns the nearest integer multiple of significance that is less than or equal to the value. If no significance is provided, a significance of 1 is assumed.
- Return type
- pyairtable.formulas.FROMNOW(date, /)[source]¶
Calculates the number of days between the current date and another date.
- Return type
- pyairtable.formulas.HOUR(datetime, /)[source]¶
Returns the hour of a datetime as a number between 0 (12:00am) and 23 (11:00pm).
- Return type
- pyairtable.formulas.IF(expression, if_true, if_false, /)[source]¶
Returns value1 if the logical argument is true, otherwise it returns value2. Can also be used to make nested IF statements.
- Return type
- pyairtable.formulas.INT(value, /)[source]¶
Returns the greatest integer that is less than or equal to the specified value.
- Return type
- pyairtable.formulas.ISERROR(expr, /)[source]¶
Returns true if the expression causes an error.
- Return type
- pyairtable.formulas.IS_AFTER(date1, date2, /)[source]¶
Determines if [date1] is later than [date2]. Returns 1 if yes, 0 if no.
- Return type
- pyairtable.formulas.IS_BEFORE(date1, date2, /)[source]¶
Determines if [date1] is earlier than [date2]. Returns 1 if yes, 0 if no.
- Return type
- pyairtable.formulas.IS_SAME(date1, date2, unit, /)[source]¶
Compares two dates up to a unit and determines whether they are identical. Returns 1 if yes, 0 if no.
- Return type
- pyairtable.formulas.LAST_MODIFIED_TIME(*fields)[source]¶
Returns the date and time of the most recent modification made by a user in a non-computed field in the table.
- Return type
- pyairtable.formulas.LEFT(string, how_many, /)[source]¶
Extract how many characters from the beginning of the string.
- Return type
- pyairtable.formulas.LOG(number, base=None, /)[source]¶
Computes the logarithm of the value in provided base. The base defaults to 10 if not specified.
- Return type
- pyairtable.formulas.MAX(number, /, *numbers)[source]¶
Returns the largest of the given numbers.
- Return type
- pyairtable.formulas.MID(string, where_to_start, count, /)[source]¶
Extract a substring of count characters starting at whereToStart.
- Return type
- pyairtable.formulas.MIN(number, /, *numbers)[source]¶
Returns the smallest of the given numbers.
- Return type
- pyairtable.formulas.MINUTE(datetime, /)[source]¶
Returns the minute of a datetime as an integer between 0 and 59.
- Return type
- pyairtable.formulas.MOD(value, divisor, /)[source]¶
Returns the remainder after dividing the first argument by the second.
- Return type
- pyairtable.formulas.MONTH(date, /)[source]¶
Returns the month of a datetime as a number between 1 (January) and 12 (December).
- Return type
- pyairtable.formulas.NOW()[source]¶
While similar to the TODAY() function, NOW() returns the current date AND time.
- Return type
- pyairtable.formulas.ODD(value, /)[source]¶
Rounds positive value up the the nearest odd number and negative value down to the nearest odd number.
- Return type
- pyairtable.formulas.POWER(base, power, /)[source]¶
Computes the specified base to the specified power.
- Return type
- pyairtable.formulas.REGEX_EXTRACT(string, regex, /)[source]¶
Returns the first substring that matches a regular expression.
- Return type
- pyairtable.formulas.REGEX_MATCH(string, regex, /)[source]¶
Returns whether the input text matches a regular expression.
- Return type
- pyairtable.formulas.REGEX_REPLACE(string, regex, replacement, /)[source]¶
Substitutes all matching substrings with a replacement string value.
- Return type
- pyairtable.formulas.REPLACE(string, start_character, number_of_characters, replacement, /)[source]¶
Replaces the number of characters beginning with the start character with the replacement text.
- Return type
- pyairtable.formulas.REPT(string, number, /)[source]¶
Repeats string by the specified number of times.
- Return type
- pyairtable.formulas.RIGHT(string, how_many, /)[source]¶
Extract howMany characters from the end of the string.
- Return type
- pyairtable.formulas.ROUND(value, precision, /)[source]¶
Rounds the value to the number of decimal places given by “precision.” (Specifically, ROUND will round to the nearest integer at the specified precision, with ties broken by rounding half up toward positive infinity.)
- Return type
- pyairtable.formulas.ROUNDDOWN(value, precision, /)[source]¶
Rounds the value to the number of decimal places given by “precision,” always rounding down.
- Return type
- pyairtable.formulas.ROUNDUP(value, precision, /)[source]¶
Rounds the value to the number of decimal places given by “precision,” always rounding up.
- Return type
- pyairtable.formulas.SEARCH(string_to_find, where_to_search, start_from_position=None, /)[source]¶
Searches for an occurrence of stringToFind in whereToSearch string starting from an optional startFromPosition. (startFromPosition is 0 by default.) If no occurrence of stringToFind is found, the result will be empty.
- Return type
- pyairtable.formulas.SECOND(datetime, /)[source]¶
Returns the second of a datetime as an integer between 0 and 59.
- Return type
- pyairtable.formulas.SET_LOCALE(date, locale_modifier, /)[source]¶
Sets a specific locale for a datetime. Must be used in conjunction with DATETIME_FORMAT. A list of supported locale modifiers can be found here.
- Return type
- pyairtable.formulas.SET_TIMEZONE(date, tz_identifier, /)[source]¶
Sets a specific timezone for a datetime. Must be used in conjunction with DATETIME_FORMAT. A list of supported timezone identifiers can be found here.
- Return type
- pyairtable.formulas.SQRT(value, /)[source]¶
Returns the square root of a nonnegative number.
- Return type
- pyairtable.formulas.SUBSTITUTE(string, old_text, new_text, index=None, /)[source]¶
Replaces occurrences of old_text in string with new_text.
- Return type
- pyairtable.formulas.SUM(number, /, *numbers)[source]¶
Sum together the numbers. Equivalent to number1 + number2 + …
- Return type
- pyairtable.formulas.SWITCH(expression, pattern, result, /, *pattern_results)[source]¶
Takes an expression, a list of possible values for that expression, and for each one, a value that the expression should take in that case. It can also take a default value if the expression input doesn’t match any of the defined patterns. In many cases, SWITCH() can be used instead of a nested IF() formula.
- Return type
- pyairtable.formulas.T(value, /)[source]¶
Returns the argument if it is text and blank otherwise.
- Return type
- pyairtable.formulas.TIMESTR(timestamp, /)[source]¶
Formats a datetime into a time-only string (HH:mm:ss).
- Return type
- pyairtable.formulas.TODAY()[source]¶
While similar to the NOW() function: TODAY() returns the current date (not the current time, if formatted, time will return 12:00am).
- Return type
- pyairtable.formulas.TONOW(date, /)[source]¶
Calculates the number of days between the current date and another date.
- Return type
- pyairtable.formulas.TRIM(string, /)[source]¶
Removes whitespace at the beginning and end of string.
- Return type
- pyairtable.formulas.TRUE()[source]¶
Logical value true. The value of true is represented numerically by a 1.
- Return type
- pyairtable.formulas.VALUE(text, /)[source]¶
Converts the text string to a number. Some exceptions apply—if the string contains certain mathematical operators(-,%) the result may not return as expected. In these scenarios we recommend using a combination of VALUE and REGEX_REPLACE to remove non-digit values from the string:
- Return type
- pyairtable.formulas.WEEKDAY(date, start_day_of_week=None, /)[source]¶
Returns the day of the week as an integer between 0 (Sunday) and 6 (Saturday). You may optionally provide a second argument (either
"Sunday"or"Monday") to start weeks on that day. If omitted, weeks start on Sunday by default.- Return type
- pyairtable.formulas.WEEKNUM(date, start_day_of_week=None, /)[source]¶
Returns the week number in a year. You may optionally provide a second argument (either
"Sunday"or"Monday") to start weeks on that day. If omitted, weeks start on Sunday by default.- Return type
- pyairtable.formulas.WORKDAY(start_date, num_days, holidays=None, /)[source]¶
Returns a date that is numDays working days after startDate. Working days exclude weekends and an optional list of holidays, formatted as a comma-separated string of ISO-formatted dates.
- Return type
- pyairtable.formulas.WORKDAY_DIFF(start_date, end_date, holidays=None, /)[source]¶
Counts the number of working days between startDate and endDate. Working days exclude weekends and an optional list of holidays, formatted as a comma-separated string of ISO-formatted dates.
- Return type
- pyairtable.formulas.XOR(expression, /, *expressions)[source]¶
Returns true if an odd number of arguments are true.
- Return type
API: pyairtable.models¶
pyAirtable will wrap certain API responses in type-annotated models, some of which will be deeply nested within each other. Models which implementers can interact with directly are documented below. Nested or internal models are documented in each submodule.
Due to its complexity, the pyairtable.models.schema module is
documented separately, and none of its classes are exposed here.
- pydantic model pyairtable.models.AuditLogResponse[source]¶
Represents a page of audit log events.
See Audit log events for more information on how to interpret this data structure.
- field events: List[AuditLogEvent]¶
- field pagination: Optional[AuditLogResponse.Pagination]¶
- pydantic model pyairtable.models.AuditLogEvent[source]¶
Represents a single audit log event.
See Audit log events for more information on how to interpret this data structure.
To avoid namespace conflicts with the Pydantic library, the
modelIdandmodelTypefields from the Airtable API are represented as fields namedobject_idandobject_type.- field id: str¶
- field timestamp: datetime.datetime¶
- field action: str¶
- field actor: AuditLogActor¶
- field object_id: str¶
- field object_type: str¶
- field payload: AuditLogPayload¶
- field payload_version: str¶
- field context: AuditLogEvent.Context¶
- field origin: AuditLogEvent.Origin¶
- pydantic model pyairtable.models.Collaborator[source]¶
Represents an Airtable user being passed from the API.
This is only used in contexts involving other models (e.g.
Comment). In contexts where API values are returned asdict, we will return collaborator information as adictas well.- field id: str¶
Airtable’s unique ID for the user, in the format
usrXXXXXXXXXXXXXX.
- field email: Optional[str]¶
The email address of the user.
- field name: Optional[str]¶
The display name of the user.
- pydantic model pyairtable.models.Comment[source]¶
A record comment that has been retrieved from the Airtable API.
>>> comment = table.add_comment("recMNxslc6jG0XedV", "Hello, @[usrVMNxslc6jG0Xed]!") >>> table.comments("recMNxslc6jG0XedV") [ Comment( id='comdVMNxslc6jG0Xe', text='Hello, @[usrVMNxslc6jG0Xed]!', created_time=datetime.datetime(...), last_updated_time=None, mentioned={ 'usrVMNxslc6jG0Xed': Mentioned( display_name='Alice', email='alice@example.com', id='usrVMNxslc6jG0Xed', type='user' ) }, author=Collaborator( id='usr0000pyairtable', email='pyairtable@example.com', name='Your pyairtable access token' ) ) ] >>> comment.text = "Never mind!" >>> comment.save() >>> comment.delete()
The following fields can be modified and saved:
text- field id: str¶
The unique ID of the comment.
- field text: str¶
The text of the comment.
- field created_time: datetime.datetime¶
The ISO 8601 timestamp of when the comment was created.
- field last_updated_time: Optional[datetime.datetime]¶
The ISO 8601 timestamp of when the comment was last edited.
- field author: pyairtable.models.collaborator.Collaborator¶
The account which created the comment.
- field parent_comment_id: Optional[str]¶
The comment ID of the parent comment, if this comment is a threaded reply.
- field attachments: List[Attachment] [Optional]¶
List of attachments on this comment.
- delete()¶
Delete the record on the server and mark this instance as deleted.
- Return type
None
- property deleted: bool¶
Indicates whether the record has been deleted since being returned from the API.
- Return type
bool
- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- pydantic model pyairtable.models.Webhook[source]¶
A webhook that has been retrieved from the Airtable API.
>>> spec = { ... "options": { ... "filters": { ... "dataTypes": ["tableData"], ... } ... } ... } >>> base.add_webhook("https://example.com", spec) CreateWebhookResponse( id='ach00000000000001', mac_secret_base64='c3VwZXIgZHVwZXIgc2VjcmV0', expiration_time=datetime.datetime(...) ) >>> webhooks = base.webhooks() >>> webhooks[0] Webhook( id='ach00000000000001', are_notifications_enabled=True, cursor_for_next_payload=1, is_hook_enabled=True, last_successful_notification_time=None, notification_url="https://example.com", last_notification_result=None, expiration_time=datetime.datetime(...), specification: WebhookSpecification(...) ) >>> webhooks[0].disable_notifications() >>> webhooks[0].enable_notifications() >>> webhooks[0].extend_expiration() >>> webhooks[0].delete()
- field id: str¶
- field are_notifications_enabled: bool¶
- field cursor_for_next_payload: int¶
- field is_hook_enabled: bool¶
- field last_successful_notification_time: Optional[datetime.datetime]¶
- field notification_url: Optional[str]¶
- field last_notification_result: Optional[WebhookNotificationResult]¶
- field expiration_time: Optional[datetime.datetime]¶
- field specification: WebhookSpecification¶
- enable_notifications()[source]¶
Turn on notifications for this webhook. See Enable/disable webhook notifications.
- Return type
None
- disable_notifications()[source]¶
Turn off notifications for this webhook. See Enable/disable webhook notifications.
- Return type
None
- extend_expiration()[source]¶
Extend the life of a webhook by seven days. See Refresh a webhook.
- Return type
None
- payloads(cursor=1, *, limit=None)[source]¶
Iterate through all payloads on or after the given cursor. See
WebhookPayload. Each payload will contain an extra attribute,cursor, which you will need to store if you want to later resume retrieving payloads after that point.For more details on the mechanisms of retrieving webhook payloads, or to find more information about the data structures you’ll get back, see List webhook payloads.
- Parameters
cursor (
int, default:1) – The cursor of the first webhook payload to retrieve.limit (
Optional[int], default:None) – The number of payloads to yield before stopping. If not provided, will retrieve all remaining payloads.
- Usage:
>>> webhook = Base.webhook("ach00000000000001") >>> iter_payloads = webhook.payloads() >>> next(iter_payloads) WebhookPayload( timestamp=datetime.datetime(...), base_transaction_number=4, payload_format="v0", action_metadata=ActionMetadata( source="client", source_metadata={ "user": { "id": "usr00000000000000", "email": "foo@bar.com", "permissionLevel": "create" } } ), changed_tables_by_id={}, created_tables_by_id={}, destroyed_table_ids=["tbl20000000000000", "tbl20000000000001"], error=None, error_code=None, cursor=1 )
- Return type
Iterator[WebhookPayload]
- delete()¶
Delete the record on the server and mark this instance as deleted.
- Return type
None
- property deleted: bool¶
Indicates whether the record has been deleted since being returned from the API.
- Return type
bool
- pydantic model pyairtable.models.WebhookNotification[source]¶
Represents the value that Airtable will POST to the webhook’s notification URL.
This will not contain the full webhook payload; it will only contain the IDs of the base and the webhook which triggered the notification. You will need to use
Webhook.payloadsto retrieve the actual payloads describing the change(s) which triggered the webhook.See Webhook notification delivery for more information on how these payloads are structured.
- field base: pyairtable.models.webhook._NestedId¶
- field webhook: pyairtable.models.webhook._NestedId¶
- field timestamp: datetime.datetime¶
- classmethod from_request(body, header, secret)[source]¶
Validate a request body and X-Airtable-Content-MAC header using the secret returned when the webhook was created.
- Parameters
body (
str) – The full request body sent over the wire.header (
str) – The request’s X-Airtable-Content-MAC header.secret (
Union[bytes,str]) – The MAC secret provided when the webhook was created. Ifstr, it’s assumed this is still base64-encoded; ifbytes, it’s assumed that this has been decoded.
- Returns
An instance parsed from the provided request body.
- Return type
- Raises
ValueError – if the header and body do not match the secret.
- pydantic model pyairtable.models.WebhookPayload[source]¶
Payload returned by
Webhook.payloads(). See API docs: Webhooks payload.- field timestamp: datetime.datetime¶
- field base_transaction_number: int¶
- field payload_format: str¶
- field action_metadata: Optional[WebhookPayload.ActionMetadata]¶
- field changed_tables_by_id: Dict[str, WebhookPayload.TableChanged] [Optional]¶
- field created_tables_by_id: Dict[str, WebhookPayload.TableCreated] [Optional]¶
- field destroyed_table_ids: List[str] [Optional]¶
- field error: Optional[bool]¶
- field error_code: Optional[str]¶
- field cursor: Optional[int]¶
The payload transaction number, as described in List webhook payloads - Response format. If passed to
Webhook.payloads()it will return the same payload again, along with any more payloads recorded after it.This field is specific to pyAirtable, and is not part of Airtable’s webhook payload specification.
- pydantic model ActionMetadata[source]¶
- field source: str¶
- field source_metadata: Dict[Any, Any] [Optional]¶
- pydantic model FieldChanged[source]¶
- field current: WebhookPayload.FieldInfo¶
- field previous: Optional[WebhookPayload.FieldInfo]¶
- pydantic model TableChanged[source]¶
- field changed_views_by_id: Dict[str, WebhookPayload.ViewChanged] [Optional]¶
- field changed_fields_by_id: Dict[str, WebhookPayload.FieldChanged] [Optional]¶
- field changed_records_by_id: Dict[str, WebhookPayload.RecordChanged] [Optional]¶
- field created_fields_by_id: Dict[str, WebhookPayload.FieldInfo] [Optional]¶
- field created_records_by_id: Dict[str, WebhookPayload.RecordCreated] [Optional]¶
- field changed_metadata: Optional[WebhookPayload.TableChanged.ChangedMetadata]¶
- field destroyed_field_ids: List[str] [Optional]¶
- field destroyed_record_ids: List[str] [Optional]¶
- pydantic model ChangedMetadata[source]¶
- field current: WebhookPayload.TableInfo¶
- field previous: WebhookPayload.TableInfo¶
- pydantic model ViewChanged[source]¶
- field changed_records_by_id: Dict[str, WebhookPayload.RecordChanged] [Optional]¶
- field created_records_by_id: Dict[str, WebhookPayload.RecordCreated] [Optional]¶
- field destroyed_record_ids: List[str] [Optional]¶
- pydantic model TableCreated[source]¶
- field metadata: Optional[WebhookPayload.TableInfo]¶
- field fields_by_id: Dict[str, WebhookPayload.FieldInfo] [Optional]¶
- field records_by_id: Dict[str, WebhookPayload.RecordCreated] [Optional]¶
- pydantic model RecordChanged[source]¶
- field current: WebhookPayload.CellValuesByFieldId¶
- field previous: Optional[WebhookPayload.CellValuesByFieldId]¶
- field unchanged: Optional[WebhookPayload.CellValuesByFieldId]¶
API: pyairtable.models.comment¶
- pydantic model pyairtable.models.comment.Mentioned[source]¶
A user or group that was mentioned within a comment. Stored as a
dictthat is keyed by ID.>>> comment = table.add_comment(record_id, "Hello, @[usrVMNxslc6jG0Xed]!") >>> comment.mentioned { "usrVMNxslc6jG0Xed": Mentioned( display_name='Alice', email='alice@example.com', id='usrVMNxslc6jG0Xed', type='user' ) }
See User mentioned for more details.
- field id: str¶
- field type: str¶
- field display_name: str¶
- field email: Optional[str]¶
- pydantic model pyairtable.models.comment.Reaction[source]¶
A reaction to a comment.
- pydantic model ReactingUser[source]¶
- field user_id: str¶
- field email: Optional[str]¶
- field name: Optional[str]¶
- field emoji_info: pyairtable.models.comment.Reaction.EmojiInfo¶
- field reacting_user: pyairtable.models.comment.Reaction.ReactingUser¶
- property emoji: str¶
The emoji character used for the reaction.
- Return type
str
- pydantic model pyairtable.models.comment.Attachment[source]¶
An attachment on a comment. URLs returned will expire 2 hours after being returned from the API.
See List comments.
- pydantic model Thumbnails[source]¶
- pydantic model Thumbnail[source]¶
- field url: str¶
- field height: Optional[int]¶
- field width: Optional[int]¶
- field full: Optional[pyairtable.models.comment.Attachment.Thumbnails.Thumbnail]¶
- field large: Optional[pyairtable.models.comment.Attachment.Thumbnails.Thumbnail]¶
- field small: Optional[pyairtable.models.comment.Attachment.Thumbnails.Thumbnail]¶
- field id: str¶
- field url: str¶
- field filename: str¶
- field type: Optional[str]¶
- field size: Optional[int]¶
- field height: Optional[int]¶
- field width: Optional[int]¶
- field thumbnails: Optional[pyairtable.models.comment.Attachment.Thumbnails]¶
API: pyairtable.models.schema¶
- class pyairtable.models.schema.FieldType[source]¶
Enumeration of all field types supported by Airtable.
- Usage:
>>> from pyairtable.models.schema import FieldType >>> FieldType.SINGLE_LINE_TEXT FieldType('singleLineText')
- pydantic model pyairtable.models.schema.Bases[source]¶
The list of bases visible to the API token.
See https://airtable.com/developers/web/api/list-bases
- field bases: List[Bases.Info] [Optional]¶
- pydantic model pyairtable.models.schema.BaseCollaborators[source]¶
Detailed information about who can access a base.
See https://airtable.com/developers/web/api/get-base-collaborators
- field id: str¶
- field name: str¶
- field created_time: datetime.datetime¶
- field permission_level: str¶
- field workspace_id: str¶
- field interfaces: Dict[str, BaseCollaborators.InterfaceCollaborators] [Optional]¶
- field group_collaborators: BaseCollaborators.GroupCollaborators [Optional]¶
- field individual_collaborators: BaseCollaborators.IndividualCollaborators [Optional]¶
- field invite_links: BaseCollaborators.InviteLinks [Optional]¶
- field sensitivity_label: Optional[BaseCollaborators.SensitivityLabel]¶
- field package_installations: List[BaseCollaborators.PackageInstallation] [Optional]¶
- pydantic model InterfaceCollaborators[source]¶
- field id: str¶
- field name: str¶
- field created_time: datetime.datetime¶
- field first_publish_time: Optional[datetime.datetime]¶
- field group_collaborators: List[GroupCollaborator] [Optional]¶
- field individual_collaborators: List[IndividualCollaborator] [Optional]¶
- field invite_links: List[InterfaceInviteLink] [Optional]¶
- add(collaborator_type, collaborator_id, permission_level)¶
Add a user or group as a collaborator to this Airtable object.
- Parameters
collaborator_type (
str) – Either'user'or'group'.collaborator_id (
str) – The user or group ID.permission_level (
str) – See application permission levels.
- Return type
None
- add_collaborators(collaborators)¶
Add multiple collaborators to this Airtable object.
- Parameters
collaborators (
Iterable[Union[AddUserCollaboratorDict,AddGroupCollaboratorDict]]) – A list ofdictthat conform to the specification laid out in the Add base collaborator API documentation.- Return type
None
- add_group(group_id, permission_level)¶
Add a group as a collaborator to this Airtable object.
- Parameters
group_id (
str) – The group ID.permission_level (
str) – See application permission levels.
- Return type
None
- add_user(user_id, permission_level)¶
Add a user as a collaborator to this Airtable object.
- Parameters
user_id (
str) – The user ID.permission_level (
str) – See application permission levels.
- Return type
None
- remove(collaborator_id)¶
Remove a user or group as a collaborator.
- Parameters
collaborator_id (
str) – The user or group ID.- Return type
None
- update(collaborator_id, permission_level)¶
Change the permission level granted to a user or group.
- Parameters
collaborator_id (
str) – The user or group ID.permission_level (
str) – See application permission levels.
- Return type
None
- pydantic model GroupCollaborators[source]¶
- field via_base: List[GroupCollaborator] [Optional]¶
- field via_workspace: List[GroupCollaborator] [Optional]¶
- pydantic model IndividualCollaborators[source]¶
- field via_base: List[IndividualCollaborator] [Optional]¶
- field via_workspace: List[IndividualCollaborator] [Optional]¶
- pydantic model InviteLinks[source]¶
- field via_base: List[InviteLink] [Optional]¶
- field via_workspace: List[WorkspaceInviteLink] [Optional]¶
- pydantic model PackageInstallation[source]¶
- field id: str¶
- field package_id: str¶
- field package_release_id: Optional[str]¶
- field installation_type: str¶
- add(collaborator_type, collaborator_id, permission_level)¶
Add a user or group as a collaborator to this Airtable object.
- Parameters
collaborator_type (
str) – Either'user'or'group'.collaborator_id (
str) – The user or group ID.permission_level (
str) – See application permission levels.
- Return type
None
- add_collaborators(collaborators)¶
Add multiple collaborators to this Airtable object.
- Parameters
collaborators (
Iterable[Union[AddUserCollaboratorDict,AddGroupCollaboratorDict]]) – A list ofdictthat conform to the specification laid out in the Add base collaborator API documentation.- Return type
None
- add_group(group_id, permission_level)¶
Add a group as a collaborator to this Airtable object.
- Parameters
group_id (
str) – The group ID.permission_level (
str) – See application permission levels.
- Return type
None
- add_user(user_id, permission_level)¶
Add a user as a collaborator to this Airtable object.
- Parameters
user_id (
str) – The user ID.permission_level (
str) – See application permission levels.
- Return type
None
- remove(collaborator_id)¶
Remove a user or group as a collaborator.
- Parameters
collaborator_id (
str) – The user or group ID.- Return type
None
- update(collaborator_id, permission_level)¶
Change the permission level granted to a user or group.
- Parameters
collaborator_id (
str) – The user or group ID.permission_level (
str) – See application permission levels.
- Return type
None
Collection of shared views in a base.
See https://airtable.com/developers/web/api/list-shares
Enable the base share.
- Return type
None
Disable the base share.
- Return type
None
Delete the record on the server and mark this instance as deleted.
- Return type
None
Indicates whether the record has been deleted since being returned from the API.
- Return type
bool
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- pydantic model pyairtable.models.schema.BaseSchema[source]¶
Schema of all tables within the base.
See https://airtable.com/developers/web/api/get-base-schema
- Usage:
>>> schema = api.base(base_id).schema() >>> schema.tables [TableSchema(...), ...] >>> schema.table("Table Name") TableSchema( id='tbl6jG0XedVMNxFQW', name='Table Name', primary_field_id='fld0XedVMNxFQW6jG', description=None, fields=[...], views=[...] )
- field tables: List[TableSchema]¶
- pydantic model pyairtable.models.schema.TableSchema[source]¶
Metadata for a table.
See https://airtable.com/developers/web/api/get-base-schema
The following fields can be modified and saved:
name,description,date_dependency- Usage:
>>> schema = base.table("Table Name").schema() >>> schema.id 'tbl6clmhESAtaCCwF' >>> schema.name 'Table Name'
>>> schema.fields [FieldSchema(...), ...] >>> schema().field("fld6jG0XedVMNxFQW") SingleLineTextFieldSchema( id='fld6jG0XedVMNxFQW', name='Name', type='singleLineText' )
>>> schema.views [ViewSchema(...), ...] >>> schema().view("View Name") ViewSchema( id='viw6jG0XedVMNxFQW', name='My Grid View', type='grid' )
- field id: str¶
- field name: str¶
- field primary_field_id: str¶
- field description: Optional[str]¶
- field fields: List[FieldSchema]¶
- field views: List[ViewSchema]¶
- field date_dependency: Optional[DateDependency]¶
- field(id_or_name)[source]¶
Get the schema for the field with the given ID or name.
- Return type
Union[AITextFieldSchema,AutoNumberFieldSchema,BarcodeFieldSchema,ButtonFieldSchema,CheckboxFieldSchema,CountFieldSchema,CreatedByFieldSchema,CreatedTimeFieldSchema,CurrencyFieldSchema,DateFieldSchema,DateTimeFieldSchema,DurationFieldSchema,EmailFieldSchema,ExternalSyncSourceFieldSchema,FormulaFieldSchema,LastModifiedByFieldSchema,LastModifiedTimeFieldSchema,ManualSortFieldSchema,MultilineTextFieldSchema,MultipleAttachmentsFieldSchema,MultipleCollaboratorsFieldSchema,MultipleLookupValuesFieldSchema,MultipleRecordLinksFieldSchema,MultipleSelectsFieldSchema,NumberFieldSchema,PercentFieldSchema,PhoneNumberFieldSchema,RatingFieldSchema,RichTextFieldSchema,RollupFieldSchema,SingleCollaboratorFieldSchema,SingleLineTextFieldSchema,SingleSelectFieldSchema,UrlFieldSchema,UnknownFieldSchema]
- set_date_dependency(start_date_field, end_date_field, duration_field, rescheduling_mode, predecessor_field=None, skip_weekends_and_holidays=False, holidays=None)[source]¶
Create or replace the date dependency settings for the table. You still need to call
save()to persist the changes.- Usage:
>>> table_schema = base.table("Table Name").schema() >>> table_schema.set_date_dependency( ... start_date_field="Start Date", ... end_date_field="End Date", ... duration_field="Duration", ... rescheduling_mode="flexible", ... skip_weekends_and_holidays=True, ... holidays=["2026-01-01", "2026-12-25"], ... predecessor_field="Depends On", ... ) >>> table_schema.save()
This method also accepts ORM model fields as shorthand for those fields’ IDs:
>>> table_schema = SomeModel.meta.table.schema() >>> table_schema.set_date_dependency( ... start_date_field=SomeModel.start_date, ... end_date_field=SomeModel.end_date, ... duration_field=SomeModel.duration, ... rescheduling_mode="flexible", ... ) >>> table_schema.save()
- Parameters
start_date_field (
Union[str,Field[Any,Any,Any]]) – The field ID or name for the start date.end_date_field (
Union[str,Field[Any,Any,Any]]) – The field ID or name for the end date.duration_field (
Union[str,Field[Any,Any,Any]]) – The field ID or name for the duration.rescheduling_mode (
str) – Either “flexible”, “fixed”, or “none”.skip_weekends_and_holidays (
bool, default:False) – Whether to skip weekends and holidays.holidays (
Optional[List[str]], default:None) – A list of holiday dates in ISO format (YYYY-MM-DD).predecessor_field (
Union[str,Field[Any,Any,Any],None], default:None) – Optional; the field ID or name for predecessor tasks.
- Return type
None
- pydantic model DateDependency[source]¶
Settings for date dependencies in the table.
See https://airtable.com/developers/web/api/model/date-dependency-settings
- field is_enabled: bool¶
- field duration_field_id: str¶
- field start_date_field_id: str¶
- field end_date_field_id: str¶
- field predecessor_field_id: Optional[str]¶
- field rescheduling_mode: str¶
- field should_skip_weekends_and_holidays: bool¶
- field holidays: List[str] [Optional]¶
- field is_forward_only: Optional[bool]¶
- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- pydantic model pyairtable.models.schema.ViewSchema[source]¶
Metadata for a view.
See https://airtable.com/developers/web/api/get-view-metadata
- Usage:
>>> vw = table.schema().view("View name") >>> vw.name 'View name' >>> vw.type 'grid' >>> vw.delete()
- field id: str¶
- field type: str¶
- field name: str¶
- field personal_for_user_id: Optional[str]¶
- field visible_field_ids: Optional[List[str]]¶
- delete()¶
Delete the record on the server and mark this instance as deleted.
- Return type
None
- property deleted: bool¶
Indicates whether the record has been deleted since being returned from the API.
- Return type
bool
- pydantic model pyairtable.models.schema.GroupCollaborator[source]¶
- field created_time: datetime.datetime¶
- field granted_by_user_id: str¶
- field group_id: str¶
- field name: str¶
- field permission_level: str¶
- pydantic model pyairtable.models.schema.IndividualCollaborator[source]¶
- field created_time: datetime.datetime¶
- field granted_by_user_id: str¶
- field user_id: str¶
- field email: str¶
- field permission_level: str¶
- pydantic model pyairtable.models.schema.BaseIndividualCollaborator[source]¶
- field base_id: str¶
- field created_time: datetime¶
- field granted_by_user_id: str¶
- field user_id: str¶
- field email: str¶
- field permission_level: str¶
- pydantic model pyairtable.models.schema.BaseGroupCollaborator[source]¶
- field base_id: str¶
- field created_time: datetime¶
- field granted_by_user_id: str¶
- field group_id: str¶
- field name: str¶
- field permission_level: str¶
- pydantic model pyairtable.models.schema.InviteLink[source]¶
Represents an invite link.
- field id: str¶
- field type: str¶
- field created_time: datetime.datetime¶
- field invited_email: Optional[str]¶
- field referred_by_user_id: str¶
- field permission_level: str¶
- field restricted_to_email_domains: List[str] [Optional]¶
- delete()¶
Delete the record on the server and mark this instance as deleted.
- Return type
None
- property deleted: bool¶
Indicates whether the record has been deleted since being returned from the API.
- Return type
bool
- pydantic model pyairtable.models.schema.BaseInviteLink[source]¶
Represents a base invite link.
- field base_id: str¶
- delete()¶
Delete the record on the server and mark this instance as deleted.
- Return type
None
- property deleted: bool¶
Indicates whether the record has been deleted since being returned from the API.
- Return type
bool
- field id: str¶
- field type: str¶
- field created_time: datetime¶
- field invited_email: Optional[str]¶
- field referred_by_user_id: str¶
- field permission_level: str¶
- field restricted_to_email_domains: List[str] [Optional]¶
- pydantic model pyairtable.models.schema.WorkspaceInviteLink[source]¶
Represents an invite link to a workspace that was returned within a base schema.
- delete()¶
Delete the record on the server and mark this instance as deleted.
- Return type
None
- property deleted: bool¶
Indicates whether the record has been deleted since being returned from the API.
- Return type
bool
- field id: str¶
- field type: str¶
- field created_time: datetime¶
- field invited_email: Optional[str]¶
- field referred_by_user_id: str¶
- field permission_level: str¶
- field restricted_to_email_domains: List[str] [Optional]¶
- pydantic model pyairtable.models.schema.InterfaceInviteLink[source]¶
Represents an invite link to an interface that was returned within a base schema.
- delete()¶
Delete the record on the server and mark this instance as deleted.
- Return type
None
- property deleted: bool¶
Indicates whether the record has been deleted since being returned from the API.
- Return type
bool
- field id: str¶
- field type: str¶
- field created_time: datetime¶
- field invited_email: Optional[str]¶
- field referred_by_user_id: str¶
- field permission_level: str¶
- field restricted_to_email_domains: List[str] [Optional]¶
- pydantic model pyairtable.models.schema.EnterpriseInfo[source]¶
Information about groups, users, workspaces, and email domains associated with an enterprise account.
See https://airtable.com/developers/web/api/get-enterprise
- field id: str¶
- field created_time: datetime.datetime¶
- field group_ids: List[str]¶
- field user_ids: List[str]¶
- field workspace_ids: List[str]¶
- field email_domains: List[EnterpriseInfo.EmailDomain]¶
- field root_enterprise_id: str¶
- field descendant_enterprise_ids: List[str] [Optional]¶
- field aggregated: Optional[EnterpriseInfo.AggregatedIds]¶
- field descendants: Dict[str, EnterpriseInfo.AggregatedIds] [Optional]¶
- pydantic model pyairtable.models.schema.Package[source]¶
Represents an enterprise package.
Returned from the List packages endpoint.
- field id: str¶
- field type: str¶
- field created_by_user_id: str¶
- field created_time: datetime.datetime¶
- field description: Optional[str]¶
- field enterprise_account_id: Optional[str]¶
- field install_count: int¶
- field last_updated_by_user_id: str¶
- field last_updated_time: datetime.datetime¶
- field latest_release_id: Optional[str]¶
- field name: str¶
- field source_application_id: str¶
- field tagline: Optional[str]¶
- pydantic model pyairtable.models.schema.WorkspaceCollaborators[source]¶
Detailed information about who can access a workspace.
See https://airtable.com/developers/web/api/get-workspace-collaborators
- field id: str¶
- field name: str¶
- field created_time: datetime.datetime¶
- field base_ids: List[str]¶
- field restrictions: WorkspaceCollaborators.Restrictions¶
- field group_collaborators: WorkspaceCollaborators.GroupCollaborators [Optional]¶
- field individual_collaborators: WorkspaceCollaborators.IndividualCollaborators [Optional]¶
- field invite_links: WorkspaceCollaborators.InviteLinks [Optional]¶
- pydantic model Restrictions[source]¶
- field invite_creation: str¶
- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- pydantic model GroupCollaborators[source]¶
- field via_base: List[BaseGroupCollaborator] [Optional]¶
- field via_workspace: List[GroupCollaborator] [Optional]¶
- pydantic model IndividualCollaborators[source]¶
- field via_base: List[BaseIndividualCollaborator] [Optional]¶
- field via_workspace: List[IndividualCollaborator] [Optional]¶
- pydantic model InviteLinks[source]¶
- field via_base: List[BaseInviteLink] [Optional]¶
- field via_workspace: List[InviteLink] [Optional]¶
- add(collaborator_type, collaborator_id, permission_level)¶
Add a user or group as a collaborator to this Airtable object.
- Parameters
collaborator_type (
str) – Either'user'or'group'.collaborator_id (
str) – The user or group ID.permission_level (
str) – See application permission levels.
- Return type
None
- add_collaborators(collaborators)¶
Add multiple collaborators to this Airtable object.
- Parameters
collaborators (
Iterable[Union[AddUserCollaboratorDict,AddGroupCollaboratorDict]]) – A list ofdictthat conform to the specification laid out in the Add base collaborator API documentation.- Return type
None
- add_group(group_id, permission_level)¶
Add a group as a collaborator to this Airtable object.
- Parameters
group_id (
str) – The group ID.permission_level (
str) – See application permission levels.
- Return type
None
- add_user(user_id, permission_level)¶
Add a user as a collaborator to this Airtable object.
- Parameters
user_id (
str) – The user ID.permission_level (
str) – See application permission levels.
- Return type
None
- remove(collaborator_id)¶
Remove a user or group as a collaborator.
- Parameters
collaborator_id (
str) – The user or group ID.- Return type
None
- update(collaborator_id, permission_level)¶
Change the permission level granted to a user or group.
- Parameters
collaborator_id (
str) – The user or group ID.permission_level (
str) – See application permission levels.
- Return type
None
- pydantic model pyairtable.models.schema.Collaborations[source]¶
The full set of collaborations granted to a user or user group.
See https://airtable.com/developers/web/api/model/collaborations
- field base_collaborations: List[Collaborations.BaseCollaboration] [Optional]¶
- field interface_collaborations: List[Collaborations.InterfaceCollaboration] [Optional]¶
- field workspace_collaborations: List[Collaborations.WorkspaceCollaboration] [Optional]¶
- property bases: Dict[str, pyairtable.models.schema.Collaborations.BaseCollaboration]¶
Mapping of base IDs to collaborations, to make lookups easier.
- Return type
Dict[str,BaseCollaboration]
- property interfaces: Dict[str, pyairtable.models.schema.Collaborations.InterfaceCollaboration]¶
Mapping of interface IDs to collaborations, to make lookups easier.
- Return type
Dict[str,InterfaceCollaboration]
- property workspaces: Dict[str, pyairtable.models.schema.Collaborations.WorkspaceCollaboration]¶
Mapping of workspace IDs to collaborations, to make lookups easier.
- Return type
Dict[str,WorkspaceCollaboration]
- pydantic model BaseCollaboration[source]¶
- field base_id: str¶
- field created_time: datetime.datetime¶
- field granted_by_user_id: str¶
- field permission_level: str¶
- pydantic model pyairtable.models.schema.UserInfo[source]¶
Detailed information about a user.
See https://airtable.com/developers/web/api/get-user-by-id
The following fields can be modified and saved:
state,email,first_name,last_name- field id: str¶
- field name: str¶
- field email: str¶
- field state: str¶
- field is_service_account: bool¶
- field is_sso_required: bool¶
- field is_two_factor_auth_enabled: bool¶
- field last_activity_time: Optional[datetime.datetime]¶
- field created_time: Optional[datetime.datetime]¶
- field license_type: Optional[str]¶
- field enterprise_user_type: Optional[str]¶
- field invited_to_airtable_by_user_id: Optional[str]¶
- field is_managed: bool¶
- field is_admin: bool¶
- field is_super_admin: bool¶
- field groups: List[pyairtable.models.schema.NestedId] [Optional]¶
- field collaborations: Collaborations [Optional]¶
- field descendants: Dict[str, UserInfo.DescendantIds] [Optional]¶
- field aggregated: Optional[UserInfo.AggregatedIds]¶
- pydantic model DescendantIds[source]¶
- field license_type: Optional[str]¶
- field last_activity_time: Optional[datetime.datetime]¶
- field collaborations: Optional[Collaborations]¶
- field is_admin: bool¶
- field is_managed: bool¶
- field groups: List[pyairtable.models.schema.NestedId] [Optional]¶
- pydantic model AggregatedIds[source]¶
- field license_type: Optional[str]¶
- field last_activity_time: Optional[datetime.datetime]¶
- field collaborations: Optional[Collaborations]¶
- field is_admin: bool¶
- field groups: List[pyairtable.models.schema.NestedId] [Optional]¶
- delete()¶
Delete the record on the server and mark this instance as deleted.
- Return type
None
- property deleted: bool¶
Indicates whether the record has been deleted since being returned from the API.
- Return type
bool
- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- pydantic model pyairtable.models.schema.UserGroup[source]¶
Detailed information about a user group and its members.
See https://airtable.com/developers/web/api/get-user-group
- field id: str¶
- field name: str¶
- field enterprise_account_id: str¶
- field created_time: datetime.datetime¶
- field updated_time: datetime.datetime¶
- field members: List[UserGroup.Member]¶
- field collaborations: Collaborations [Optional]¶
- field mapped_user_license_type: Optional[str]¶
- pydantic model pyairtable.models.schema.AITextFieldConfig[source]¶
Field configuration for AI text.
- field type: Literal[FieldType('aiText')]¶
- field options: AITextFieldOptions¶
- pydantic model pyairtable.models.schema.AITextFieldOptions[source]¶
- field prompt: List[Union[str, AITextFieldOptions.PromptField]] [Optional]¶
- field referenced_field_ids: List[str] [Optional]¶
- pydantic model PromptField[source]¶
- field field: pyairtable.models.schema.NestedFieldId¶
- pydantic model pyairtable.models.schema.AutoNumberFieldConfig[source]¶
Field configuration for Auto number.
- field type: Literal[FieldType('autoNumber')]¶
- pydantic model pyairtable.models.schema.BarcodeFieldConfig[source]¶
Field configuration for Barcode.
- field type: Literal[FieldType('barcode')]¶
- pydantic model pyairtable.models.schema.ButtonFieldConfig[source]¶
Field configuration for Button.
- field type: Literal[FieldType('button')]¶
- pydantic model pyairtable.models.schema.CheckboxFieldConfig[source]¶
Field configuration for Checkbox.
- field type: Literal[FieldType('checkbox')]¶
- field options: CheckboxFieldOptions¶
- pydantic model pyairtable.models.schema.CheckboxFieldOptions[source]¶
- field color: str¶
- field icon: str¶
- pydantic model pyairtable.models.schema.CountFieldConfig[source]¶
Field configuration for Count.
- field type: Literal[FieldType('count')]¶
- field options: CountFieldOptions¶
- pydantic model pyairtable.models.schema.CountFieldOptions[source]¶
- field is_valid: bool¶
- field record_link_field_id: Optional[str]¶
- pydantic model pyairtable.models.schema.CreatedByFieldConfig[source]¶
Field configuration for Created by.
- field type: Literal[FieldType('createdBy')]¶
- pydantic model pyairtable.models.schema.CreatedTimeFieldConfig[source]¶
Field configuration for Created time.
- field type: Literal[FieldType('createdTime')]¶
- pydantic model pyairtable.models.schema.CurrencyFieldConfig[source]¶
Field configuration for Currency.
- field type: Literal[FieldType('currency')]¶
- field options: CurrencyFieldOptions¶
- pydantic model pyairtable.models.schema.CurrencyFieldOptions[source]¶
- field precision: int¶
- field symbol: str¶
- pydantic model pyairtable.models.schema.DateFieldConfig[source]¶
Field configuration for Date.
- field type: Literal[FieldType('date')]¶
- field options: DateFieldOptions¶
- pydantic model pyairtable.models.schema.DateFieldOptions[source]¶
- field date_format: DateTimeFieldOptions.DateFormat¶
- pydantic model pyairtable.models.schema.DateTimeFieldConfig[source]¶
Field configuration for Date and time.
- field type: Literal[FieldType('dateTime')]¶
- field options: DateTimeFieldOptions¶
- pydantic model pyairtable.models.schema.DateTimeFieldOptions[source]¶
- field time_zone: str¶
- field date_format: DateTimeFieldOptions.DateFormat¶
- field time_format: DateTimeFieldOptions.TimeFormat¶
- pydantic model pyairtable.models.schema.DurationFieldConfig[source]¶
Field configuration for Duration.
- field type: Literal[FieldType('duration')]¶
- field options: DurationFieldOptions¶
- pydantic model pyairtable.models.schema.EmailFieldConfig[source]¶
Field configuration for Email.
- field type: Literal[FieldType('email')]¶
- pydantic model pyairtable.models.schema.ExternalSyncSourceFieldConfig[source]¶
Field configuration for Sync source.
- field type: Literal[FieldType('externalSyncSource')]¶
- field options: SingleSelectFieldOptions¶
- pydantic model pyairtable.models.schema.FormulaFieldConfig[source]¶
Field configuration for Formula.
- field type: Literal[FieldType('formula')]¶
- field options: FormulaFieldOptions¶
- pydantic model pyairtable.models.schema.FormulaFieldOptions[source]¶
- field formula: str¶
- field is_valid: bool¶
- field referenced_field_ids: Optional[List[str]]¶
- field result: Optional[FieldConfig]¶
- pydantic model pyairtable.models.schema.LastModifiedByFieldConfig[source]¶
Field configuration for Last modified by.
- field type: Literal[FieldType('lastModifiedBy')]¶
- pydantic model pyairtable.models.schema.LastModifiedTimeFieldConfig[source]¶
Field configuration for Last modified time.
- field type: Literal[FieldType('lastModifiedTime')]¶
- field options: LastModifiedTimeFieldOptions¶
- pydantic model pyairtable.models.schema.LastModifiedTimeFieldOptions[source]¶
- field is_valid: bool¶
- field referenced_field_ids: Optional[List[str]]¶
- field result: Optional[Union[DateFieldConfig, DateTimeFieldConfig]]¶
- pydantic model pyairtable.models.schema.ManualSortFieldConfig[source]¶
Field configuration for
manualSortfield type (not documented).- field type: Literal[FieldType('manualSort')]¶
- pydantic model pyairtable.models.schema.MultilineTextFieldConfig[source]¶
Field configuration for Long text.
- field type: Literal[FieldType('multilineText')]¶
- pydantic model pyairtable.models.schema.MultipleAttachmentsFieldConfig[source]¶
Field configuration for Attachments.
- field type: Literal[FieldType('multipleAttachments')]¶
- field options: MultipleAttachmentsFieldOptions¶
- pydantic model pyairtable.models.schema.MultipleAttachmentsFieldOptions[source]¶
Field configuration for Attachments.
- field is_reversed: bool¶
- pydantic model pyairtable.models.schema.MultipleCollaboratorsFieldConfig[source]¶
Field configuration for Multiple Collaborators.
- field type: Literal[FieldType('multipleCollaborators')]¶
- pydantic model pyairtable.models.schema.MultipleLookupValuesFieldConfig[source]¶
Field configuration for Lookup <https://airtable.com/developers/web/api/field-model#lookup>__.
- field type: Literal[FieldType('multipleLookupValues')]¶
- field options: MultipleLookupValuesFieldOptions¶
- pydantic model pyairtable.models.schema.MultipleLookupValuesFieldOptions[source]¶
- field is_valid: bool¶
- field field_id_in_linked_table: Optional[str]¶
- field record_link_field_id: Optional[str]¶
- field result: Optional[FieldConfig]¶
- pydantic model pyairtable.models.schema.MultipleRecordLinksFieldConfig[source]¶
Field configuration for Link to another record <https://airtable.com/developers/web/api/field-model#foreignkey>__.
- field type: Literal[FieldType('multipleRecordLinks')]¶
- field options: MultipleRecordLinksFieldOptions¶
- pydantic model pyairtable.models.schema.MultipleRecordLinksFieldOptions[source]¶
- field is_reversed: bool¶
- field linked_table_id: str¶
- field prefers_single_record_link: bool¶
- field inverse_link_field_id: Optional[str]¶
- field view_id_for_record_selection: Optional[str]¶
- pydantic model pyairtable.models.schema.MultipleSelectsFieldConfig[source]¶
Field configuration for Multiple select.
- field type: Literal[FieldType('multipleSelects')]¶
- field options: SingleSelectFieldOptions¶
- pydantic model pyairtable.models.schema.NumberFieldConfig[source]¶
Field configuration for Number.
- field type: Literal[FieldType('number')]¶
- field options: NumberFieldOptions¶
- pydantic model pyairtable.models.schema.PercentFieldConfig[source]¶
Field configuration for Percent.
- field type: Literal[FieldType('percent')]¶
- field options: NumberFieldOptions¶
- pydantic model pyairtable.models.schema.PhoneNumberFieldConfig[source]¶
Field configuration for Phone.
- field type: Literal[FieldType('phoneNumber')]¶
- pydantic model pyairtable.models.schema.RatingFieldConfig[source]¶
Field configuration for Rating.
- field type: Literal[FieldType('rating')]¶
- field options: RatingFieldOptions¶
- pydantic model pyairtable.models.schema.RatingFieldOptions[source]¶
- field color: str¶
- field icon: str¶
- field max: int¶
- pydantic model pyairtable.models.schema.RichTextFieldConfig[source]¶
Field configuration for Rich text.
- field type: Literal[FieldType('richText')]¶
- pydantic model pyairtable.models.schema.RollupFieldConfig[source]¶
Field configuration for Rollup <https://airtable.com/developers/web/api/field-model#rollup>__.
- field type: Literal[FieldType('rollup')]¶
- field options: RollupFieldOptions¶
- pydantic model pyairtable.models.schema.RollupFieldOptions[source]¶
- field field_id_in_linked_table: Optional[str]¶
- field is_valid: bool¶
- field record_link_field_id: Optional[str]¶
- field referenced_field_ids: Optional[List[str]]¶
- field result: Optional[FieldConfig]¶
- pydantic model pyairtable.models.schema.SingleCollaboratorFieldConfig[source]¶
Field configuration for Collaborator.
- field type: Literal[FieldType('singleCollaborator')]¶
- pydantic model pyairtable.models.schema.SingleLineTextFieldConfig[source]¶
Field configuration for Single line text.
- field type: Literal[FieldType('singleLineText')]¶
- pydantic model pyairtable.models.schema.SingleSelectFieldConfig[source]¶
Field configuration for Single select.
- field type: Literal[FieldType('singleSelect')]¶
- field options: SingleSelectFieldOptions¶
- pydantic model pyairtable.models.schema.SingleSelectFieldOptions[source]¶
- field choices: List[SingleSelectFieldOptions.Choice]¶
- pydantic model pyairtable.models.schema.UrlFieldConfig[source]¶
Field configuration for Url.
- field type: Literal[FieldType('url')]¶
- pydantic model pyairtable.models.schema.UnknownFieldConfig[source]¶
Field configuration class used as a fallback for unrecognized types. This ensures we don’t raise pydantic.ValidationError if Airtable adds new types.
- field type: str¶
- field options: Optional[Dict[str, Any]]¶
- pydantic model pyairtable.models.schema.AITextFieldSchema[source]¶
Field schema for AI text.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.AI_TEXT]¶
- field options: AITextFieldOptions¶
- pydantic model pyairtable.models.schema.AutoNumberFieldSchema[source]¶
Field schema for Auto number.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.AUTO_NUMBER]¶
- pydantic model pyairtable.models.schema.BarcodeFieldSchema[source]¶
Field schema for Barcode.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.BARCODE]¶
- pydantic model pyairtable.models.schema.ButtonFieldSchema[source]¶
Field schema for Button.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.BUTTON]¶
- pydantic model pyairtable.models.schema.CheckboxFieldSchema[source]¶
Field schema for Checkbox.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.CHECKBOX]¶
- field options: CheckboxFieldOptions¶
- pydantic model pyairtable.models.schema.CountFieldSchema[source]¶
Field schema for Count.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.COUNT]¶
- field options: CountFieldOptions¶
- pydantic model pyairtable.models.schema.CreatedByFieldSchema[source]¶
Field schema for Created by.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.CREATED_BY]¶
- pydantic model pyairtable.models.schema.CreatedTimeFieldSchema[source]¶
Field schema for Created time.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.CREATED_TIME]¶
- pydantic model pyairtable.models.schema.CurrencyFieldSchema[source]¶
Field schema for Currency.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.CURRENCY]¶
- field options: CurrencyFieldOptions¶
- pydantic model pyairtable.models.schema.DateFieldSchema[source]¶
Field schema for Date.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.DATE]¶
- field options: DateFieldOptions¶
- pydantic model pyairtable.models.schema.DateTimeFieldSchema[source]¶
Field schema for Date and time.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.DATE_TIME]¶
- field options: DateTimeFieldOptions¶
- pydantic model pyairtable.models.schema.DurationFieldSchema[source]¶
Field schema for Duration.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.DURATION]¶
- field options: DurationFieldOptions¶
- pydantic model pyairtable.models.schema.EmailFieldSchema[source]¶
Field schema for Email.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.EMAIL]¶
- pydantic model pyairtable.models.schema.ExternalSyncSourceFieldSchema[source]¶
Field schema for Sync source.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.EXTERNAL_SYNC_SOURCE]¶
- field options: SingleSelectFieldOptions¶
- pydantic model pyairtable.models.schema.FormulaFieldSchema[source]¶
Field schema for Formula.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.FORMULA]¶
- field options: FormulaFieldOptions¶
- pydantic model pyairtable.models.schema.LastModifiedByFieldSchema[source]¶
Field schema for Last modified by.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.LAST_MODIFIED_BY]¶
- pydantic model pyairtable.models.schema.LastModifiedTimeFieldSchema[source]¶
Field schema for Last modified time.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.LAST_MODIFIED_TIME]¶
- field options: LastModifiedTimeFieldOptions¶
- pydantic model pyairtable.models.schema.ManualSortFieldSchema[source]¶
Field schema for
manualSortfield type (not documented).The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.MANUAL_SORT]¶
- pydantic model pyairtable.models.schema.MultilineTextFieldSchema[source]¶
Field schema for Long text.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.MULTILINE_TEXT]¶
- pydantic model pyairtable.models.schema.MultipleAttachmentsFieldSchema[source]¶
Field schema for Attachments.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.MULTIPLE_ATTACHMENTS]¶
- field options: MultipleAttachmentsFieldOptions¶
- pydantic model pyairtable.models.schema.MultipleCollaboratorsFieldSchema[source]¶
Field schema for Multiple Collaborators.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.MULTIPLE_COLLABORATORS]¶
- pydantic model pyairtable.models.schema.MultipleLookupValuesFieldSchema[source]¶
Field schema for Lookup <https://airtable.com/developers/web/api/field-model#lookup>__.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.MULTIPLE_LOOKUP_VALUES]¶
- field options: MultipleLookupValuesFieldOptions¶
- pydantic model pyairtable.models.schema.MultipleRecordLinksFieldSchema[source]¶
Field schema for Link to another record <https://airtable.com/developers/web/api/field-model#foreignkey>__.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.MULTIPLE_RECORD_LINKS]¶
- field options: MultipleRecordLinksFieldOptions¶
- pydantic model pyairtable.models.schema.MultipleSelectsFieldSchema[source]¶
Field schema for Multiple select.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.MULTIPLE_SELECTS]¶
- field options: SingleSelectFieldOptions¶
- pydantic model pyairtable.models.schema.NumberFieldSchema[source]¶
Field schema for Number.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.NUMBER]¶
- field options: NumberFieldOptions¶
- pydantic model pyairtable.models.schema.PercentFieldSchema[source]¶
Field schema for Percent.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.PERCENT]¶
- field options: NumberFieldOptions¶
- pydantic model pyairtable.models.schema.PhoneNumberFieldSchema[source]¶
Field schema for Phone.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.PHONE_NUMBER]¶
- pydantic model pyairtable.models.schema.RatingFieldSchema[source]¶
Field schema for Rating.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.RATING]¶
- field options: RatingFieldOptions¶
- pydantic model pyairtable.models.schema.RichTextFieldSchema[source]¶
Field schema for Rich text.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.RICH_TEXT]¶
- pydantic model pyairtable.models.schema.RollupFieldSchema[source]¶
Field schema for Rollup <https://airtable.com/developers/web/api/field-model#rollup>__.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.ROLLUP]¶
- field options: RollupFieldOptions¶
- pydantic model pyairtable.models.schema.SingleCollaboratorFieldSchema[source]¶
Field schema for Collaborator.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.SINGLE_COLLABORATOR]¶
- pydantic model pyairtable.models.schema.SingleLineTextFieldSchema[source]¶
Field schema for Single line text.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.SINGLE_LINE_TEXT]¶
- pydantic model pyairtable.models.schema.SingleSelectFieldSchema[source]¶
Field schema for Single select.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.SINGLE_SELECT]¶
- field options: SingleSelectFieldOptions¶
- pydantic model pyairtable.models.schema.UrlFieldSchema[source]¶
Field schema for Url.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: Literal[FieldType.URL]¶
- pydantic model pyairtable.models.schema.UnknownFieldSchema[source]¶
Field schema class used as a fallback for unrecognized types. This ensures we don’t raise pydantic.ValidationError if Airtable adds new types.
The following fields can be modified and saved:
name,description- save()¶
Save any changes made to the instance’s writable fields and update the instance with any refreshed values returned from the API.
Will raise
RuntimeErrorif the record has been deleted.- Return type
None
- field id: str¶
- field name: str¶
- field description: Optional[str]¶
- field type: str¶
- field options: Optional[Dict[str, Any]]¶
- pyairtable.models.schema.parse_field_schema(obj)[source]¶
Given a
dictrepresenting a field schema, parse it into the appropriate FieldSchema subclass.- Return type
Union[AITextFieldSchema,AutoNumberFieldSchema,BarcodeFieldSchema,ButtonFieldSchema,CheckboxFieldSchema,CountFieldSchema,CreatedByFieldSchema,CreatedTimeFieldSchema,CurrencyFieldSchema,DateFieldSchema,DateTimeFieldSchema,DurationFieldSchema,EmailFieldSchema,ExternalSyncSourceFieldSchema,FormulaFieldSchema,LastModifiedByFieldSchema,LastModifiedTimeFieldSchema,ManualSortFieldSchema,MultilineTextFieldSchema,MultipleAttachmentsFieldSchema,MultipleCollaboratorsFieldSchema,MultipleLookupValuesFieldSchema,MultipleRecordLinksFieldSchema,MultipleSelectsFieldSchema,NumberFieldSchema,PercentFieldSchema,PhoneNumberFieldSchema,RatingFieldSchema,RichTextFieldSchema,RollupFieldSchema,SingleCollaboratorFieldSchema,SingleLineTextFieldSchema,SingleSelectFieldSchema,UrlFieldSchema,UnknownFieldSchema]
API: pyairtable.models.webhook¶
- pydantic model pyairtable.models.webhook.WebhookNotificationResult[source]¶
- field success: bool¶
- field completion_timestamp: datetime.datetime¶
- field duration_ms: float¶
- field retry_number: int¶
- field will_be_retried: Optional[bool]¶
- field error: Optional[WebhookError]¶
- pydantic model pyairtable.models.webhook.WebhookSpecification[source]¶
- field options: WebhookSpecification.Options¶
- pydantic model Options[source]¶
- field filters: WebhookSpecification.Filters¶
- field includes: Optional[WebhookSpecification.Includes]¶
- pydantic model Filters[source]¶
- field data_types: List[str]¶
- field record_change_scope: Optional[str]¶
- field change_types: List[str] [Optional]¶
- field from_sources: List[str] [Optional]¶
- field source_options: Optional[WebhookSpecification.SourceOptions]¶
- field watch_data_in_field_ids: List[str] [Optional]¶
- field watch_schemas_of_field_ids: List[str] [Optional]¶
- pydantic model SourceOptions[source]¶
- field form_submission: Optional[FormSubmission]¶
- field form_page_submission: Optional[FormPageSubmission]¶
- pydantic model pyairtable.models.webhook.CreateWebhook[source]¶
- field notification_url: Optional[str]¶
- field specification: pyairtable.models.webhook.WebhookSpecification¶
- pydantic model pyairtable.models.webhook.CreateWebhookResponse[source]¶
Payload returned by
Base.add_webhookwhich includes the base64-encoded MAC secret that you’ll need in order to verify the authenticity of future webhook requests.- field id: str¶
The ID of the webhook that was just created.
- field mac_secret_base64: str¶
The base64-encoded MAC secret. This should be saved somewhere upon receipt; there is no way to retrieve it once this object is discarded.
- field expiration_time: Optional[datetime.datetime]¶
The timestamp when the webhook will expire and be deleted.
API: pyairtable.orm¶
- class pyairtable.orm.Model[source]¶
Supports creating ORM-style classes representing Airtable tables. For more details, see ORM.
A nested class or dict called
Metais required and can specify the following attributes:api_key(required) - API key or personal access token.base_id(required) - Base ID (not name).table_name(required) - Table ID or name.timeout- A tuple indicating a connect and read timeout. Defaults to no timeout.typecast- The Airtable API will perform best-effort automatic data conversion from string values. Defaults toTrue.retry- An instance of urllib3.util.Retry. IfNoneorFalse, requests will not be retried. IfTrue, the default strategy will be applied (seeretry_strategy()for details).use_field_ids- Whether fields will be defined by ID, rather than name. Defaults toFalse.memoize- Whether the model should reuse models it creates between requests. See Memoizing linked records for more information.
For example, the following two are equivalent:
from pyairtable.orm import Model, fields class Contact(Model): class Meta: base_id = "appaPqizdsNHDvlEm" table_name = "Contact" api_key = "keyapikey" timeout = (5, 5) typecast = True first_name = fields.TextField("First Name") age = fields.IntegerField("Age")
from pyairtable.orm import Model, fields class Contact(Model): Meta = { "base_id": "appaPqizdsNHDvlEm", "table_name": "Contact", "api_key": "keyapikey", "timeout": (5, 5), "typecast": True, } first_name = fields.TextField("First Name") age = fields.IntegerField("Age")
You can implement meta attributes as callables if certain values need to be dynamically provided or are unavailable at import time:
from pyairtable.orm import Model, fields from your_app.config import get_secret class Contact(Model): class Meta: base_id = "appaPqizdsNHDvlEm" table_name = "Contact" @staticmethod def api_key(): return get_secret("AIRTABLE_API_KEY") first_name = fields.TextField("First Name") age = fields.IntegerField("Age")
- created_time: Optional[datetime.datetime] = None¶
The time when the Airtable record was created. If empty, the instance has never been saved to (or fetched from) the API.
- comment_count: Optional[int] = None¶
The number of comments on this record. Only populated if the record was fetched with
count_comments=True.
- meta: ClassVar[pyairtable.orm.model._Meta]¶
A wrapper allowing type-annotated access to ORM configuration.
- __init__(**fields)[source]¶
Construct a model instance with field values based on the given keyword args.
>>> Contact(name="Alice", birthday=date(1980, 1, 1)) <unsaved Contact>
The keyword argument
id=special-cased and sets the record ID, not a field value.>>> Contact(id="recWPqD9izdsNvlE", name="Bob") <Contact id='recWPqD9izdsNvlE'>
- id: str = ''¶
The Airtable record ID for this instance. If empty, the instance has never been saved to the API.
- save(*, force=False)[source]¶
Save the model to the API.
If the instance does not exist already, it will be created; otherwise, the existing record will be updated, using only the fields which have been modified since it was retrieved.
- Parameters
force (
bool, default:False) – IfTrue, all fields will be saved, even if they have not changed.- Return type
- delete()[source]¶
Delete the record.
- Raises
ValueError – if the record does not exist.
- Return type
bool
- classmethod all(*, memoize=None, **kwargs)[source]¶
Retrieve all records for this model. For all supported keyword arguments, see
Table.all.- Parameters
memoize (
Optional[bool], default:None) – IfTrue, any objects created will be memoized for future reuse. IfFalse, objects created will not be memoized. The default behavior is defined on theModelsubclass.- Return type
List[Self]
- classmethod first(*, memoize=None, **kwargs)[source]¶
Retrieve the first record for this model. For all supported keyword arguments, see
Table.first.- Parameters
memoize (
Optional[bool], default:None) – IfTrue, any objects created will be memoized for future reuse. IfFalse, objects created will not be memoized. The default behavior is defined on theModelsubclass.- Return type
Optional[Self]
- to_record(only_writable=False)[source]¶
Build a
RecordDictto represent this instance.This method converts internal field values into values expected by Airtable. For example, a
datetimevalue fromDatetimeFieldis converted into an ISO 8601 string.- Parameters
only_writable (
bool, default:False) – IfTrue, the result will exclude any values which are associated with readonly fields.- Return type
- classmethod from_record(record, *, memoize=None)[source]¶
Create an instance from a record dict.
- Parameters
record (
RecordDict) – The record data from the Airtable API.memoize (
Optional[bool], default:None) – IfTrue, any objects created will be memoized for future reuse. IfFalse, objects created will not be memoized. The default behavior is defined on theModelsubclass.
- Return type
Self
- classmethod from_id(record_id, *, fetch=True, memoize=None)[source]¶
Create an instance from a record ID.
- Parameters
record_id (
str) – An Airtable record ID.fetch (
bool, default:True) – IfTrue, records will be fetched and field values will be updated. IfFalse, new instances are created with the provided IDs, but field values are unset.memoize (
Optional[bool], default:None) – IfTrue, any objects created will be memoized for future reuse. IfFalse, objects created will not be memoized. The default behavior is defined on theModelsubclass.
- Return type
Self
- classmethod from_ids(record_ids, *, fetch=True, memoize=None)[source]¶
Create a list of instances from record IDs. If any record IDs returned are invalid this will raise a KeyError, but only after retrieving all other valid records from the API.
- Parameters
record_ids (
Iterable[str]) – An Airtable record ID.fetch (
bool, default:True) – IfTrue, records will be fetched and field values will be updated. IfFalse, new instances are created with the provided IDs, but field values are unset.memoize (
Optional[bool], default:None) – IfTrue, any objects created will be memoized for future reuse. IfFalse, objects created will not be memoized. The default behavior is defined on theModelsubclass.
- Return type
List[Self]
- classmethod batch_save(models)[source]¶
Save a list of model instances to the Airtable API with as few network requests as possible. Can accept a mixture of new records (which have not been saved yet) and existing records that have IDs.
- Return type
None
- classmethod batch_delete(models)[source]¶
Delete a list of model instances from Airtable.
- Raises
ValueError – if the model has not been saved to Airtable.
- Return type
None
- comments()[source]¶
Return a list of comments on this record. See
Table.comments.- Return type
List[Comment]
- add_comment(text)[source]¶
Add a comment to this record. See
Table.add_comment.- Return type
- class pyairtable.orm.SaveResult[source]¶
Represents the result of saving a record to the API. The result’s attributes contain more granular information about the save operation:
>>> result = model.save() >>> result.record_id 'recWPqD9izdsNvlE' >>> result.created False >>> result.updated True >>> result.forced False >>> result.field_names {'Name', 'Email'}
If none of the model’s fields have changed, calling
save()will not perform any API requests and will return a SaveResult with no changes.>>> model = YourModel() >>> result = model.save() >>> result.saved True >>> second_result = model.save() >>> second_result.saved False
For backwards compatibility, instances of SaveResult will evaluate as truthy if the record was created, and falsy if the record was not created.
- __init__(record_id, created=False, updated=False, forced=False, field_names=<factory>)¶
API: pyairtable.orm.fields¶
Fields define how you’ll interact with your data when using the ORM.
Internally these are implemented as descriptors, which allows us to define methods and type annotations for getting and setting attribute values.
>>> from pyairtable.orm import Model, fields
>>> class Contact(Model):
... class Meta:
... ...
... name = fields.TextField("Name")
... is_registered = fields.CheckboxField("Registered")
...
>>> contact = Contact(name="George", is_registered=True)
>>> assert contact.name == "George"
>>> reveal_type(contact.name) # -> str
>>> contact.to_record()
{
"id": recS6qSLw0OCA6Xul",
"createdTime": "2021-07-14T06:42:37.000Z",
"fields": {
"Name": "George",
"Registered": True,
}
}
- pyairtable.orm.fields.ALL_FIELDS: Set[Type[pyairtable.orm.fields.Field[Any, Any, Any]]]¶
Set of all Field subclasses exposed by the library.
- pyairtable.orm.fields.READONLY_FIELDS: Set[Type[pyairtable.orm.fields.Field[Any, Any, Any]]]¶
Set of all read-only Field subclasses exposed by the library.
- pyairtable.orm.fields.FIELD_TYPES_TO_CLASSES: Dict[str, Type[pyairtable.orm.fields.Field[Any, Any, Any]]]¶
Mapping of Airtable field type names to their ORM classes. See https://airtable.com/developers/web/api/field-model and Formula, Rollup, and Lookup Fields.
The data type of “formula” and “rollup” fields will depend on the underlying fields they reference, so it is not practical for the ORM to know or detect those fields’ types. These two field type names are mapped to the constant
NotImplemented.Keys are
FieldTypeenum values, which inherit fromstrand can be used in string comparisons.
- pyairtable.orm.fields.FIELD_CLASSES_TO_TYPES: Dict[Type[pyairtable.orm.fields.Field[Any, Any, Any]], Set[str]]¶
Mapping of field classes to the set of supported Airtable field types.
- class pyairtable.orm.fields.AITextField[source]¶
Read-only field that returns a
dict.For more about this field type, see AI Text.
- pyairtable.orm.fields.AnyField¶
An alias for any type of Field.
alias of
pyairtable.orm.fields.Field[Any,Any,Any]
- class pyairtable.orm.fields.AttachmentsField[source]¶
Accepts a list of
AttachmentDictorCreateAttachmentDict.For more about this field type, see Attachments.
- list_class¶
alias of
pyairtable.orm.lists.AttachmentsList
- class pyairtable.orm.fields.AutoNumberField[source]¶
Number field with integer precision. Accepts only
intvalues.If the Airtable API returns
null, this field raisesMissingValueError.For more about this field type, see Auto number.
- class pyairtable.orm.fields.BarcodeField[source]¶
Accepts a list of
BarcodeDict.For more about this field type, see Barcode.
- class pyairtable.orm.fields.ButtonField[source]¶
Read-only field that returns a
ButtonDict.If the Airtable API returns
null, this field raisesMissingValueError.For more about this field type, see Button.
- class pyairtable.orm.fields.CheckboxField[source]¶
Accepts
bool. ReturnsFalseinstead ofNoneif the field is empty.For more about this field type, see Checkbox.
- class pyairtable.orm.fields.CollaboratorField[source]¶
Accepts a
CollaboratorDictorCollaboratorEmailDict.For more about this field type, see Collaborator.
- class pyairtable.orm.fields.CountField[source]¶
Number field with integer precision. Accepts only
intvalues.For more about this field type, see Count.
- class pyairtable.orm.fields.CreatedByField[source]¶
Returns a
CollaboratorDict.If the Airtable API returns
null, this field raisesMissingValueError.For more about this field type, see Created by.
- class pyairtable.orm.fields.CreatedTimeField[source]¶
Read only. Returns datetime values.
If the Airtable API returns
null, this field raisesMissingValueError.For more about this field type, see Created time.
- class pyairtable.orm.fields.CurrencyField[source]¶
Number field with unspecified precision. Accepts either
intorfloat.For more about this field type, see Currency.
- class pyairtable.orm.fields.DateField[source]¶
Accepts only date values.
For more about this field type, see Date.
- class pyairtable.orm.fields.DatetimeField[source]¶
Accepts only datetime values.
For more about this field type, see Date and time.
- class pyairtable.orm.fields.DurationField[source]¶
Duration field. Accepts only timedelta values.
For more about this field type, see Duration.
- class pyairtable.orm.fields.EmailField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Email.
- class pyairtable.orm.fields.ExternalSyncSourceField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Sync source.
- class pyairtable.orm.fields.Field[source]¶
A generic class for an Airtable field descriptor that will be included in an ORM model.
Type-checked subclasses should provide three type parameters:
T_API, indicating the JSON-serializable type returned by the APIT_ORM, indicating the type used to store values internallyT_Missing, indicating the type of value returned if the field is empty
Subclasses should also define
valid_typesas a type or tuple of types, which will be used to validate the type of field values being set via this descriptor.- missing_value: ClassVar[Any] = None¶
The value to return when the field is missing
- __init__(field_name, validate_type=True, readonly=None)[source]¶
- Parameters
field_name (
str) – The name of the field in Airtable.validate_type (
bool, default:True) – Whether to raise a TypeError if anything attempts to write an object of an unsupported type as a field value. IfFalse, you may encounter unpredictable behavior from the Airtable API.readonly (
Optional[bool], default:None) – IfTrue, any attempt to write a value to this field will raise anAttributeError. Each field implements appropriate default values, but you may find it useful to mark fields as readonly if you know that the access token your code uses does not have permission to modify specific fields.
- readonly: bool = False¶
Whether to allow modification of the value in this field.
- to_record_value(value)[source]¶
Calculate the value which should be persisted to the API.
- Return type
Any
- to_internal_value(value)[source]¶
Convert a value from the API into the value’s internal representation.
- Return type
Any
- valid_or_raise(value)[source]¶
Validate the type of the given value and raise TypeError if invalid.
- Return type
None
- class pyairtable.orm.fields.FloatField[source]¶
Number field with decimal precision. Accepts only
floatvalues.For more about this field type, see Number.
- class pyairtable.orm.fields.IntegerField[source]¶
Number field with integer precision. Accepts only
intvalues.For more about this field type, see Number.
- class pyairtable.orm.fields.LastModifiedByField[source]¶
Read-only. Returns a
CollaboratorDict.If the Airtable API returns
null, this field raisesMissingValueError.For more about this field type, see Last modified by.
- class pyairtable.orm.fields.LastModifiedTimeField[source]¶
Read only. Returns datetime values.
For more about this field type, see Last modified time.
- class pyairtable.orm.fields.LinkField[source]¶
Represents a MultipleRecordLinks field. Returns and accepts lists of Models.
Can also be used with a lookup field that pulls from a MultipleRecordLinks field, provided the field is created with
readonly=True.For more about this field type, see Link to another record.
- __init__(field_name, model, validate_type=True, readonly=None, lazy=False)[source]¶
- Parameters
field_name (
str) – Name of the Airtable field.model (
Union[str,LinkSelf,Type[Model]]) –Model class representing the linked table. There are a few options:
You can provide a
strthat is the fully qualified module and class name. For example,"your.module.Model"will importModelfromyour.module.You can provide a
strthat is just the class name, and it will be imported from the same module as the model class.You can provide the sentinel value
LinkSelf, and the link field will point to the same model where the link field is created.
validate_type (
bool, default:True) – Whether to raise a TypeError if attempting to write an object of an unsupported type as a field value. IfFalse, you may encounter unpredictable behavior from the Airtable API.readonly (
Optional[bool], default:None) – IfTrue, any attempt to write a value to this field will raise anAttributeError. This will not, however, prevent any modification of the list object returned by this field.lazy (
bool, default:False) – IfTrue, this field will return empty objects with only IDs; callfetch()to retrieve values.
- property linked_model: Type[pyairtable.orm.fields.T_Linked]¶
Resolve a
Modelclass based on themodel=constructor parameter to this field instance.- Return type
Type[Model]
- populate(instance, *, lazy=None, memoize=None)[source]¶
Populates the field’s value for the given instance. This allows you to control how linked models are loaded, depending on your need, without having to decide at the time of field or model construction.
- Parameters
lazy (
Optional[bool], default:None) – IfTrue, this field will return empty objects with only IDs; callfetch()to retrieve values.memoize (
Optional[bool], default:None) – IfTrue, any objects created will be memoized for future reuse. IfFalse, objects created will not be memoized. The default behavior is defined on theModelsubclass.
Usage:
from pyairtable.orm import Model, fields as F class Book(Model): class Meta: ... class Author(Model): class Meta: ... books = F.LinkField("Books", Book) author = Author.from_id("reculZ6qSLw0OCA61") Author.books.populate(author, lazy=True, memoize=False)
- Return type
None
- to_record_value(value)[source]¶
Build the list of record IDs which should be persisted to the API.
- Return type
List[str]
- valid_or_raise(value)[source]¶
Validate the type of the given value and raise TypeError if invalid.
- Return type
None
- list_class¶
alias of
pyairtable.orm.lists.ChangeTrackingList
- pyairtable.orm.fields.LinkSelf = _LinkFieldOptions.LinkSelf¶
Sentinel option for the model= param to
LinkField
- class pyairtable.orm.fields.LookupField[source]¶
Generic field class for a lookup, which returns a list of values.
pyAirtable does not inspect field configuration at runtime or during type checking. If you use mypy, you can declare which type(s) the lookup returns:
>>> from pyairtable.orm import fields as F >>> class MyTable(Model): ... Meta = fake_meta() ... lookup = F.LookupField[str]("My Lookup") ... >>> rec = MyTable.first() >>> rec.lookup ["First value", "Second value", ...]
For more about this field type, see Lookup.
- list_class¶
alias of
pyairtable.orm.lists.ChangeTrackingList
- class pyairtable.orm.fields.ManualSortField[source]¶
Read-only. Returns
""instead ofNoneif the field is empty.The
manualSortfield type is used to define a manual sort order for a list view. Its use or behavior via the API is not documented.
- class pyairtable.orm.fields.MultilineTextField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Long text.
- class pyairtable.orm.fields.MultipleCollaboratorsField[source]¶
Accepts a list of
CollaboratorDictorCollaboratorEmailDict.For more about this field type, see Multiple collaborators.
- list_class¶
alias of
pyairtable.orm.lists.ChangeTrackingList
- class pyairtable.orm.fields.MultipleSelectField[source]¶
Accepts a list of
str.For more about this field type, see Multiple select.
- list_class¶
alias of
pyairtable.orm.lists.ChangeTrackingList
- class pyairtable.orm.fields.NumberField[source]¶
Number field with unspecified precision. Accepts either
intorfloat.For more about this field type, see Number.
- class pyairtable.orm.fields.PercentField[source]¶
Number field with unspecified precision. Accepts either
intorfloat.For more about this field type, see Percent.
- class pyairtable.orm.fields.PhoneNumberField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Phone.
- class pyairtable.orm.fields.RatingField[source]¶
Accepts
intvalues that are greater than zero.For more about this field type, see Rating.
- class pyairtable.orm.fields.RequiredAITextField[source]¶
Read-only field that returns a
dict.For more about this field type, see AI Text.
If the Airtable API returns
null, this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredBarcodeField[source]¶
Accepts a list of
BarcodeDict.For more about this field type, see Barcode.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredCollaboratorField[source]¶
Accepts a
CollaboratorDictorCollaboratorEmailDict.For more about this field type, see Collaborator.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredCountField[source]¶
Number field with integer precision. Accepts only
intvalues.For more about this field type, see Count.
If the Airtable API returns
null, this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredCurrencyField[source]¶
Number field with unspecified precision. Accepts either
intorfloat.For more about this field type, see Currency.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredDateField[source]¶
Accepts only date values.
For more about this field type, see Date.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredDatetimeField[source]¶
Accepts only datetime values.
For more about this field type, see Date and time.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredDurationField[source]¶
Duration field. Accepts only timedelta values.
For more about this field type, see Duration.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredEmailField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Email.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredFloatField[source]¶
Number field with decimal precision. Accepts only
floatvalues.For more about this field type, see Number.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredIntegerField[source]¶
Number field with integer precision. Accepts only
intvalues.For more about this field type, see Number.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredMultilineTextField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Long text.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredNumberField[source]¶
Number field with unspecified precision. Accepts either
intorfloat.For more about this field type, see Number.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredPercentField[source]¶
Number field with unspecified precision. Accepts either
intorfloat.For more about this field type, see Percent.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredPhoneNumberField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Phone.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredRatingField[source]¶
Accepts
intvalues that are greater than zero.For more about this field type, see Rating.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredRichTextField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Rich text.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredSelectField[source]¶
Represents a single select dropdown field. Accepts
strorNone.This will return
Noneif no value is set, and will only return""if an empty dropdown option is available and selected.For more about this field type, see Single select.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredSingleLineTextField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Single line text.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredTextField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Single line text and Long text.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RequiredUrlField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Url.
If the Airtable API returns
null, or if a caller sets this field toNoneor'', this field raisesMissingValueError.
- class pyairtable.orm.fields.RichTextField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Rich text.
- class pyairtable.orm.fields.SelectField[source]¶
Represents a single select dropdown field. Accepts
strorNone.This will return
Noneif no value is set, and will only return""if an empty dropdown option is available and selected.For more about this field type, see Single select.
- class pyairtable.orm.fields.SingleLineTextField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Single line text.
- class pyairtable.orm.fields.SingleLinkField[source]¶
Represents a MultipleRecordLinks field which we assume will only ever contain one link. Returns and accepts a single instance of the linked model, which will be converted to/from a list of IDs when communicating with the Airtable API.
Warning
If Airtable returns multiple IDs for a SingleLinkField and you modify the field value, only the first ID will be saved to the API once you call
.save(). The other IDs will be lost.By default, a SingleLinkField will ignore the 2nd…Nth IDs if it receives multiple IDs from the API. This behavior can be overridden by passing
raise_if_many=Trueto the constructor.from pyairtable.orm import Model, fields as F class Book(Model): class Meta: ... author = F.SingleLinkField("Author", Person) editor = F.SingleLinkField("Editor", Person, raise_if_many=True)
Given the model configuration above and the data below, one field will silently return a single value, while the other field will throw an exception.
>>> book = Book.from_record({ ... "id": "recZ6qSLw0OCA61ul", ... "createdTime": ..., ... "fields": { ... "Author": ["reculZ6qSLw0OCA61", "rec61ulZ6qSLw0OCA"], ... "Editor": ["recLw0OCA61ulZ6qS", "recOCA61ulZ6qSLw0"], ... } ... }) >>> book.author <Person id='reculZ6qSLw0OCA61'> >>> book.editor Traceback (most recent call last): ... MultipleValues: Book.editor got more than one linked record
- __init__(field_name, model, validate_type=True, readonly=None, lazy=False, raise_if_many=False)[source]¶
- Parameters
field_name (
str) – Name of the Airtable field.model (
Union[str,LinkSelf,Type[Model]]) –Model class representing the linked table. There are a few options:
You can provide a
strthat is the fully qualified module and class name. For example,"your.module.Model"will importModelfromyour.module.You can provide a
strthat is just the class name, and it will be imported from the same module as the model class.You can provide the sentinel value
LinkSelf, and the link field will point to the same model where the link field is created.
validate_type (
bool, default:True) – Whether to raise a TypeError if attempting to write an object of an unsupported type as a field value. IfFalse, you may encounter unpredictable behavior from the Airtable API.readonly (
Optional[bool], default:None) – IfTrue, any attempt to write a value to this field will raise anAttributeError. This will not, however, prevent any modification of the list object returned by this field.lazy (
bool, default:False) – IfTrue, this field will return empty objects with only IDs; callfetch()to retrieve values.raise_if_many (
bool, default:False) – IfTrue, this field will raise aMultipleValuesexception upon being accessed if the underlying field contains multiple values.
- to_record_value(value)[source]¶
Calculate the value which should be persisted to the API.
- Return type
List[str]
- populate(instance, *, lazy=None, memoize=None)[source]¶
Populates the field’s value for the given instance. This allows you to control how linked models are loaded, depending on your need, without having to decide at the time of field or model construction.
- Parameters
lazy (
Optional[bool], default:None) – IfTrue, this field will return empty objects with only IDs; callfetch()to retrieve values.memoize (
Optional[bool], default:None) – IfTrue, any objects created will be memoized for future reuse. IfFalse, objects created will not be memoized. The default behavior is defined on theModelsubclass.
Usage:
from pyairtable.orm import Model, fields as F class Book(Model): class Meta: ... class Author(Model): class Meta: ... books = F.LinkField("Books", Book) author = Author.from_id("reculZ6qSLw0OCA61") Author.books.populate(author, lazy=True, memoize=False)
- Return type
None
- class pyairtable.orm.fields.TextField[source]¶
Accepts
str. Returns""instead ofNoneif the field is empty.For more about this field type, see Single line text and Long text.
API: pyairtable.testing¶
pyAirtable provides a number of helper functions for testing code that uses
the Airtable API. These functions are designed to be used with the standard
Python unittest.mock library, and can be used to create fake records,
users, and attachments, as well as to mock the Airtable API itself.
- pyairtable.testing.fake_id(type='rec', value=None)[source]¶
Generate a fake Airtable-style ID.
- Parameters
type (
str, default:'rec') – the object type prefix, defaults to “rec”value (
Optional[Any], default:None) – any value to use as the ID, defaults to random letters and digits
>>> fake_id() 'rec...' >>> fake_id('tbl') 'tbl...' >>> fake_id(value='12345') 'rec00000000012345'
- Return type
str
- pyairtable.testing.fake_meta(base_id='', table_name='', api_key='patFakePersonalAccessToken', timeout=None, retry=None, typecast=True, use_field_ids=False, memoize=False)[source]¶
Generate a
Metaclass for inclusion in aModelsubclass.- Return type
type
- pyairtable.testing.fake_record(fields=None, id=None, **other_fields)[source]¶
Generate a fake record dict with the given field values.
>>> fake_record({"Name": "Alice"}) { 'id': '...', 'createdTime': '...', 'fields': {'name': 'Alice'} }
>>> fake_record(name="Alice", id="123") { 'id': 'rec00000000000123', 'createdTime': '...', 'fields': {'name': 'Alice'} }
>>> fake_record(name="Alice", id="recABC00000000123") { 'id': 'recABC00000000123', 'createdTime': '...', 'fields': {'name': 'Alice'} }
- Return type
- pyairtable.testing.fake_user(value=None)[source]¶
Generate a fake user dict with the given value for an email prefix.
>>> fake_user("Alice") { 'id': 'usr000000000Alice', 'email': 'alice@example.com' 'name': 'Alice' }
- Return type
- pyairtable.testing.fake_attachment(url='', filename='')[source]¶
Generate a fake attachment dict.
>>> fake_attachment() { 'id': 'att...', 'url': 'https://example.com/', 'filename': 'foo.txt', 'size': 100, 'type': 'text/plain', }
>>> fake_attachment('https://example.com/image.png', 'foo.png') { 'id': 'att...', 'url': 'https://example.com/image.png', 'filename': 'foo.png', 'size': 100, 'type': 'text/plain', }
- Return type
- class pyairtable.testing.MockAirtable[source]¶
This class acts as a context manager which mocks several pyAirtable APIs, so that your tests can operate against tables without making network requests.
from pyairtable import Api from pyairtable.testing import MockAirtable table = Api.base("baseId").table("tableName") with MockAirtable() as m: m.add_records(table, [{"Name": "Alice"}]) records = table.all() assert len(table.all()) == 1
If you use pytest, you might want to include this as a fixture.
import pytest from pyairtable.testing import MockAirtable @pytest.fixture(autouse=True) def mock_airtable(): with MockAirtable() as m: yield m def test_your_function(): ...
Not all API methods are supported; if your test calls a method that would make a network request, a RuntimeError will be raised instead.
>>> with MockAirtable() as m: ... table.schema() ... Traceback (most recent call last): ... RuntimeError: unhandled call to Api.request
You can allow unhandled requests by setting the
passthroughargument to True, either on the constructor or temporarily on the MockAirtable instance. This is useful when using another library, like requests-mock, to prepare responses for complex cases (like code that retrieves the schema).def test_your_function(requests_mock, mock_airtable, monkeypatch): base = Api.base("baseId") # load and cache our mock schema requests_mock.get( base.meta_url("tables"), json={"tables": [...]} ) with mock_airtable.enable_passthrough(): base.schema() # code below will fail if any more unhandled requests are made ...
- __init__(passthrough=False)[source]¶
- Parameters
passthrough (
bool, default:False) – if True, unmocked methods will still be allowed to perform real network requests. If False, they will raise an error.
- set_passthrough(allowed)[source]¶
Context manager that temporarily changes whether unmocked methods are allowed to perform real network requests. For convenience, there are also shortcuts
enable_passthrough()anddisable_passthrough().Usage:
with MockAirtable() as m: with m.enable_passthrough(): schema = base.schema() hooks = table.webhooks() # no more network requests allowed ...
- Parameters
allowed (
bool) – IfTrue, unmocked methods will be allowed to perform real network requests within this context manager. IfFalse, they will not be allowed.- Return type
Iterator[Self]
- add_records(base_id: str, table_id_or_name: str, /, records: Iterable[Dict[str, Any]]) List[pyairtable.api.types.RecordDict][source]¶
- add_records(table: pyairtable.api.table.Table, /, records: Iterable[Dict[str, Any]]) List[pyairtable.api.types.RecordDict]
Add a list of records to the mock Airtable instance. These will be returned from methods like
all()andget().Can be called with either a base ID and table name, or an instance of
Table:m = MockAirtable() m.add_records("baseId", "tableName", [{"Name": "Alice"}]) m.add_records(table, records=[{"id": "recFake", {"Name": "Alice"}}])
Note
The parameters to
all()are not supported by MockAirtable, and constraints likeformula=andlimit=will be ignored. It is assumed that you are adding records to specifically test a particular use case. MockAirtable is not a full in-memory replacement for the Airtable API.- Parameters
base_id – An Airtable base ID. This must be the first positional argument.
table_id_or_name – An Airtable table ID or name. Table name should be unencoded, as shown on browser. This should be the same ID or name used in the code under test. This must be the second positional argument.
table – An instance of
Table. This is an alternative to providing base and table IDs, and must be the first positional argument.records – A sequence of
RecordDict,UpdateRecordDict,CreateRecordDict, orFields.
- Return type
List[RecordDict]
- set_records(base_id: str, table_id_or_name: str, /, records: Iterable[Dict[str, Any]]) None[source]¶
- set_records(table: pyairtable.api.table.Table, /, records: Iterable[Dict[str, Any]]) None
Set the mock records for a particular base and table, replacing any existing records. See
add_records()for more information.- Parameters
base_id – An Airtable base ID. This must be the first positional argument.
table_id_or_name – An Airtable table ID or name. Table name should be unencoded, as shown on browser. This should be the same ID or name used in the code under test. This must be the second positional argument.
table – An instance of
Table. This is an alternative to providing base and table IDs, and must be the first positional argument.records – A sequence of
RecordDict,UpdateRecordDict,CreateRecordDict, orFields.
- Return type
None
- pyairtable.testing.coerce_fake_record(record)[source]¶
Coerce a record dict or field mapping to the expected format for an Airtable record, creating a fake ID and createdTime if necessary.
>>> coerce_fake_record({"Name": "Alice"}) {'id': 'rec000...', 'createdTime': '...', 'fields': {'Name': 'Alice'}}
- Return type
API: pyairtable.utils¶
- pyairtable.utils.attachment(url, filename='')[source]¶
Build a
dictin the expected format for creating attachments.When creating an attachment,
urlis required, andfilenameis optional. Airtable will download the file at the given url and keep its own copy of it. All other attachment object properties will be generated server-side soon afterward.Note
Attachment field values must be an array of
AttachmentDictorCreateAttachmentByUrl; it is not valid to pass a single item to the API.- Usage:
>>> table = Table(...) >>> profile_url = "https://example.com/profile.jpg" >>> rec = table.create({"Profile Photo": [attachment(profile_url)]}) { 'id': 'recZXOZ5gT9vVGHfL', 'fields': { 'attachment': [ { 'id': 'attu6kbaST3wUuNTA', 'url': 'https://content.airtable.com/...', 'filename': 'profile.jpg' } ] }, 'createdTime': '2021-08-21T22:28:36.000Z' }
- Return type
- pyairtable.utils.cache_unless_forced(func)[source]¶
Wrap a method (e.g.
Base.shares()) in a decorator that will save a memoized version of the return value for future reuse, but will also allow callers to passforce=Trueto recompute the memoized version.- Return type
_FetchMethod[TypeVar(C, contravariant=True),TypeVar(R, covariant=True)]
- pyairtable.utils.chunked(iterable, chunk_size)[source]¶
Break a sequence into chunks.
- Parameters
iterable (
Sequence[TypeVar(T)]) – Any sequence.chunk_size (
int) – Maximum items to yield per chunk.
- Return type
Iterator[Sequence[TypeVar(T)]]
- pyairtable.utils.coerce_iso_str(value)[source]¶
Given an input that might be a date or datetime, or an ISO 8601 formatted str, convert the value into an ISO 8601 formatted str.
- Return type
Optional[str]
- pyairtable.utils.coerce_list_str(value)[source]¶
Given an input that is either a str or an iterable of str, return a list.
- Return type
List[str]
- pyairtable.utils.date_from_iso_str(value)[source]¶
Convert ISO 8601 date string into a
dateobject.- Parameters
value (
str) – date string, e.g. “2014-09-05”- Return type
date
- pyairtable.utils.date_to_iso_str(value)[source]¶
Convert a
dateordatetimeinto an Airtable-compatible ISO 8601 string- Parameters
value (
Union[date,datetime]) – date or datetime object, e.g. “2014-09-05”- Return type
str
- pyairtable.utils.datetime_from_iso_str(value)[source]¶
Convert an ISO 8601 datetime string into a
datetimeobject.- Parameters
value (
str) – datetime string, e.g. “2014-09-05T07:00:00.000Z”- Return type
datetime
- pyairtable.utils.datetime_to_iso_str(value)[source]¶
Convert
datetimeobject into Airtable compatible ISO 8601 string e.g. “2014-09-05T12:34:56.000Z”- Parameters
value (
datetime) – datetime object- Return type
str
- pyairtable.utils.enterprise_only(wrapped, /, modify_docstring=True)[source]¶
Wrap a function or method so that if Airtable returns a 404, we will annotate the error with a helpful note to the user.
- Return type
TypeVar(F, bound=Callable[...,Any])
- pyairtable.utils.fieldgetter(*fields, required=False)[source]¶
Create a function that extracts ID, created time, or field values from a record. Intended to be used in similar situations as operator.itemgetter.
>>> record = {"id": "rec001", "fields": {"Name": "Alice"}} >>> fieldgetter("Name")(record) 'Alice' >>> fieldgetter("id")(record) 'rec001' >>> fieldgetter("id", "Name", "Missing")(record) ('rec001', 'Alice', None)
- Parameters
fields (
str) – The field names to extract from the record. The values"id"and"createdTime"are special cased; all other values are interpreted as field names.required (
Union[bool,Iterable[str]], default:False) – If True, will raise KeyError if a value is missing. If False, missing values will return as None. If a sequence of field names is provided, only those names will be required.
- Return type
Callable[[Union[RecordDict,CreateRecordDict,UpdateRecordDict]],Any]
- pyairtable.utils.is_airtable_id(value, prefix='')[source]¶
Check whether the given value is an Airtable ID.
- Parameters
value (
Any) – The value to check.prefix (
str, default:'') – If provided, the ID must have the given prefix.
- Return type
bool
- pyairtable.utils.is_base_id(value: Any, *, prefix: str = 'app') bool¶
Check whether the given value is an Airtable ID.
- Parameters
value – The value to check.
prefix – If provided, the ID must have the given prefix.
- pyairtable.utils.is_field_id(value: Any, *, prefix: str = 'fld') bool¶
Check whether the given value is an Airtable ID.
- Parameters
value – The value to check.
prefix – If provided, the ID must have the given prefix.
- pyairtable.utils.is_record_id(value: Any, *, prefix: str = 'rec') bool¶
Check whether the given value is an Airtable ID.
- Parameters
value – The value to check.
prefix – If provided, the ID must have the given prefix.
- pyairtable.utils.is_table_id(value: Any, *, prefix: str = 'tbl') bool¶
Check whether the given value is an Airtable ID.
- Parameters
value – The value to check.
prefix – If provided, the ID must have the given prefix.
- pyairtable.utils.is_user_id(value: Any, *, prefix: str = 'usr') bool¶
Check whether the given value is an Airtable ID.
- Parameters
value – The value to check.
prefix – If provided, the ID must have the given prefix.
- class pyairtable.utils.Url[source]¶
Wrapper for
strthat adds Path-like syntax for extending URL components and adding query params.>>> url = Url('http://example.com') >>> url Url('http://example.com') >>> url / 'foo' & {'a': 1, 'b': [2, 3, 4]} Url('http://example.com/foo?a=1&b=2&b=3&b=4') >>> url // [1, 2, 3, 4] Url('http://example.com/1/2/3/4')
- add_path(*others)[source]¶
Build a copy of this URL with additional path segments.
>>> url = Url('http://example.com') >>> url.add_path("a", "b", "c") Url('http://example.com/a/b/c')
The shorthand
/has the same effect and can be used with a single path segment. The shorthand//can be used with an iterable of path segments.>>> url / "a" / "b" / "c" Url('http://example.com/a/b/c') >>> url // ["a", "b", "c"] Url('http://example.com/a/b/c')
- Return type
Self
- add_qs(params=None, **other_params)[source]¶
Build a copy of this URL with additional query parameters. The shorthand
&has the same effect.>>> url = Url('http://example.com') >>> url.add_qs({"a": 1}, b=[2, 3, 4]) Url('http://example.com?a=1&b=2&b=3&b=4') >>> url & {"a": 1, "b": [2, 3, 4]} Url('http://example.com?a=1&b=2&b=3&b=4')
- Return type
Self
- class pyairtable.utils.UrlBuilder[source]¶
Utility for defining URL patterns within an Airtable API class. Each instance of UrlBuilder will inspect its own class attributes and modify them to reflect the actual URL that should be used based on the context (Table, Base, etc.) provided.
The pattern for use in pyAirtable is:
from functools import cached_property from pyairtable.utils import UrlBuilder class SomeObject: attr1: str attr2: int class _urls(UrlBuilder): url1 = "/path/to/{attr1}" url2 = "/path/to/{attr2}" urls = cached_property(_urls)
…which ensures the URLs are built only once and are accessible via
.urls, and have theSomeObjectinstance available as context, and build readable docstrings for theSomeObjectclass documentation.Warning
This class is intended for use within pyAirtable only, and is tailored to the type of documentation this library produces. Its behavior may change in the future in ways that are not suitable for other projects.