API Reference¶
Module: 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).
- __init__(api_key, *, timeout=None, retry_strategy=True, endpoint_url='https://api.airtable.com')[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. IfNone
orFalse
, 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.
- property api_key: str¶
Airtable API key or access token to use on all connections.
- Return type
str
- table(base_id, table_name)[source]¶
Returns a new
Table
instance that uses this instance ofApi
.- Return type
- build_url(*components)[source]¶
Returns a URL to the Airtable API endpoint with the given URL components, including the API version number.
- Return type
str
- request(method, url, fallback=None, options=None, params=None, json=None)[source]¶
Makes a request to the Airtable API, optionally converting a GET to a POST if the URL exceeds the API’s maximum URL length.
See https://support.airtable.com/docs/enforcement-of-url-length-limit-for-web-api-requests
- 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
[Fields
], default:None
) – Airtable-specific query params to use while fetching records. See Parameters for valid options.params (
Optional
[Fields
], default:None
) – Additional query params to append to the URL as-is.json (
Optional
[Fields
], default:None
) – The JSON payload for a POST/PUT/PATCH/DELETE request.
- Return type
Any
- iterate_requests(method, url, fallback=None, options=None, offset_field='offset')[source]¶
Makes 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
[Fields
], default:None
) – Airtable-specific query params to use while fetching records. See Parameters for valid options.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]¶
Iterates 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
)]]
- 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
- class pyairtable.Base[source]¶
Represents an Airtable base.
- __init__(api, base_id)[source]¶
Old style constructor takes
str
arguments, 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")
- api: pyairtable.api.api.Api¶
The connection to the Airtable API.
- id: str¶
The base ID, in the format
appXXXXXXXXXXXXXX
- table(table_name)[source]¶
Returns a new
Table
instance using all shared attributes fromBase
.- Parameters
table_name (
str
) – An Airtable table name. Table name should be unencoded, as shown on browser.- Return type
- webhooks()[source]¶
Retrieves all the base’s webhooks from the API (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="2023-07-01T00:00:00.000Z", specification: WebhookSpecification(...) ) ]
- Return type
List
[Webhook
]
- webhook(webhook_id)[source]¶
Returns a single webhook or raises
KeyError
if 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]¶
Creates 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='2023-07-01T00:00:00.000Z' )
- 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
CreateWebhookResponse
- class pyairtable.Table[source]¶
Represents an Airtable table.
- Usage:
>>> api = Api(access_token) >>> table = api.table("base_id", "table_name") >>> records = table.all()
- __init__(api_key: str, base_id: str, table_name: str, *, timeout: Optional[pyairtable.api.api.TimeoutTuple] = '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)
Old style constructor takes
str
arguments, and will create its own instance ofApi
. This constructor can also be provided with keyword arguments to theApi
class.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
None
as 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 url: str¶
Returns the URL for this table.
- Return type
str
- record_url(record_id, *components)[source]¶
Returns the URL for the given record ID, with optional trailing components.
- Return type
str
- property api: pyairtable.api.api.Api¶
Returns the same API connection as table’s
Base
.- Return type
- get(record_id, **options)[source]¶
Retrieves 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 https://support.airtable.com/hc/en-us/articles/216141558-Supported-timezones-for-SET-TIMEZONE for valid values.
user_locale – The user locale that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/220340268-Supported-locale-modifiers-for-SET-LOCALE for valid values.
return_fields_by_field_id – An optional boolean value that lets you return field objects where the key is the field id. This defaults to false, which returns field objects where the key is the field name.
- Return type
- iterate(**options)[source]¶
Iterates 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. For example, to only include records whereCOLUMN_A
isn’t empty, pass informula="{COLUMN_A}"
.cell_format – The cell format to request from the Airtable API. Supported options are json (the default) and string. json will return cells as a JSON object. string will return the cell as a string. user_locale and time_zone must be set when using string.
user_locale – The user locale that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/220340268-Supported-locale-modifiers-for-SET-LOCALE for valid values.
time_zone – The time zone that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/216141558-Supported-timezones-for-SET-TIMEZONE for valid values.
return_fields_by_field_id – An optional boolean value that lets you return field objects where the key is the field id. This defaults to false, which returns field objects where the key is the field name.
- Return type
Iterator
[List
[RecordDict
]]
- all(**options)[source]¶
Retrieves 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. For example, to only include records whereCOLUMN_A
isn’t empty, pass informula="{COLUMN_A}"
.cell_format – The cell format to request from the Airtable API. Supported options are json (the default) and string. json will return cells as a JSON object. string will return the cell as a string. user_locale and time_zone must be set when using string.
user_locale – The user locale that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/220340268-Supported-locale-modifiers-for-SET-LOCALE for valid values.
time_zone – The time zone that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/216141558-Supported-timezones-for-SET-TIMEZONE for valid values.
return_fields_by_field_id – An optional boolean value that lets you return field objects where the key is the field id. This defaults to false, which returns field objects where the key is the field name.
- Return type
List
[RecordDict
]
- first(**options)[source]¶
Retrieves the first matching record. Returns
None
if no records are returned.This is similar to
all()
, except it setspage_size
andmax_records
to1
.- 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. For example, to only include records whereCOLUMN_A
isn’t empty, pass informula="{COLUMN_A}"
.cell_format – The cell format to request from the Airtable API. Supported options are json (the default) and string. json will return cells as a JSON object. string will return the cell as a string. user_locale and time_zone must be set when using string.
user_locale – The user locale that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/220340268-Supported-locale-modifiers-for-SET-LOCALE for valid values.
time_zone – The time zone that should be used to format dates when using string as the cell_format. See https://support.airtable.com/hc/en-us/articles/216141558-Supported-timezones-for-SET-TIMEZONE for valid values.
return_fields_by_field_id – An optional boolean value that lets you return field objects where the key is the field id. This defaults to false, which returns field objects where the key is the field name.
- Return type
Optional
[RecordDict
]
- create(fields, typecast=False, return_fields_by_field_id=False)[source]¶
Creates a new record
>>> record = {'Name': 'John'} >>> table = api.table('base_id', 'table_name') >>> table.create(record)
- Parameters
fields (
Fields
) – 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.return_fields_by_field_id (
bool
, default:False
) – 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.
- Return type
- batch_create(records, typecast=False, return_fields_by_field_id=False)[source]¶
Creats 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 (
List
[Fields
]) – List of dicts representing records to be created.typecast (
bool
, default:False
) – The Airtable API will perform best-effort automatic data conversion from string values.return_fields_by_field_id (
bool
, default:False
) – 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.
- Return type
List
[RecordDict
]
- update(record_id, fields, replace=False, typecast=False)[source]¶
Updates 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 (
Fields
) – 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 bet set to null. If False, only provided fields are updated.typecast (
bool
, default:False
) – The Airtable API will perform best-effort automatic data conversion from string values.
- Return type
- batch_update(records, replace=False, typecast=False, return_fields_by_field_id=False)[source]¶
Updates several records in batches.
- Parameters
records (
List
[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 bet set to null. If False, only provided fields are updated.typecast (
bool
, default:False
) – The Airtable API will perform best-effort automatic data conversion from string values.return_fields_by_field_id (
bool
, default:False
) – 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.
- Return type
List
[RecordDict
]- Returns
The list of updated records.
- batch_upsert(records, key_fields, replace=False, typecast=False, return_fields_by_field_id=False)[source]¶
Updates or creates records in batches, either using
id
(if given) or using a set of fields (key_fields
) to look for matches. For more information on how this operation behaves, see Airtable’s API documentation for Update multiple records.New in version 1.5.0.
- Parameters
records (
List
[UpdateRecordDict
]) – 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 bet set to null. If False, only provided fields are updated.typecast (
bool
, default:False
) – The Airtable API will perform best-effort automatic data conversion from string values.return_fields_by_field_id (
bool
, default:False
) – 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.
- Return type
- Returns
Lists of created/updated record IDs, along with the list of all records affected.
- delete(record_id)[source]¶
Deletes 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]¶
Deletes the given records, operating in batches.
>>> table.batch_delete(['recwPQIfs4wKPyc9D', 'recwDxIfs3wDPyc3F']) [ {'id': 'recwPQIfs4wKPyc9D', 'deleted': True}, {'id': 'recwDxIfs3wDPyc3F', 'deleted': True} ]
- Parameters
record_ids (
List
[str
]) – Record IDs to delete- Return type
List
[RecordDeletedDict
]- Returns
Confirmation that the records were deleted.
- comments(record_id)[source]¶
Returns a list of comments on the given record.
- Usage:
>>> table = Api.table("appNxslc6jG0XedVM", "tblslc6jG0XedVMNx") >>> table.comments("recMNxslc6jG0XedV") [ Comment( id='comdVMNxslc6jG0Xe', text='Hello, @[usrVMNxslc6jG0Xed]!', created_time='2023-06-07T17:46:24.435891', 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]¶
Creates 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
- pyairtable.retry_strategy(*, status_forcelist=(429,), backoff_factor=0.1, total=5, allowed_methods=None, **kwargs)[source]¶
Creates a Retry instance with adjustable default values.
Api
accepts 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 that0
means no retries, whereas1
will execute a total of two requests (original + 1 retry).**kwargs – Accepts any valid parameter to Retry.
- Return type
Retry
Module: 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
str
used internally for disambiguation. Record IDs for Airtable look like"recAdw9EjV90xbZ"
.
- pyairtable.api.types.Timestamp¶
An alias for
str
used 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
str
used internally for disambiguation. Field names can be any valid string.
- class pyairtable.api.types.AttachmentDict[source]¶
A
dict
representing 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.CreateAttachmentDict[source]¶
A
dict
representing 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
dict
representing 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
dict
representing 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' } } }
- pyairtable.api.types.FieldValue: typing_extensions.TypeAlias = typing.Any¶
Represents the types of values that we might receive from the API. At present, is an alias for
Any
because 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
[pyairtable.api.types.CreateAttachmentDict
],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
[pyairtable.api.types.CreateAttachmentDict
],List
[pyairtable.api.types.CollaboratorDict
],List
[pyairtable.api.types.CollaboratorEmailDict
]]]
- class pyairtable.api.types.RecordDict[source]¶
A
dict
representing 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'} }
- class pyairtable.api.types.CreateRecordDict[source]¶
A
dict
representing the payload passed to the Airtable API to create a record.
- class pyairtable.api.types.UpdateRecordDict[source]¶
A
dict
representing the payload passed to the Airtable API to update a record.- Usage:
>>> update_records = [ ... {"id": "recAdw9EjV90xbW", "fields": {"Email": "alice@example.com"}}, ... {"id": "recAdw9EjV90xbX", "fields": {"Email": "bob@example.com"}}, ... ] >>> table.batch_update(update_records)
- class pyairtable.api.types.RecordDeletedDict[source]¶
A
dict
representing 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
dict
representing 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
dict
representing the Get user ID & scopes endpoint.- Usage:
>>> api.whoami() {'id': 'usrX9e810wHn3mMLz'}
- 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
)]
Module: pyairtable.formulas¶
- pyairtable.formulas.match(dict_values, *, match_any=False)[source]¶
Creates one or more
EQUAL()
expressions for each provided dict value. If more than one assetions is included, the expressions are groupped together into usingAND()
(all values must match).If
match_any=True
, expressions are grouped withOR()
, record is return if any of the values match.This function also handles escaping field names and casting python values to the appropriate airtable types using
to_airtable_value()
on all provided values to help generate the expected formula syntax.If you need more advanced matching you can build similar expressions using lower level forumula primitives.
- Parameters
dict_values (
Fields
) – dictionary containing column names and values- Keyword Arguments
default (match_any (bool,) –
False
): IfTrue
, matches if any of the provided values match. Otherwise, all values must match.
- Usage:
>>> match({"First Name": "John", "Age": 21}) "AND({First Name}='John',{Age}=21)" >>> match({"First Name": "John", "Age": 21}, match_any=True) "OR({First Name}='John',{Age}=21)" >>> match({"First Name": "John"}) "{First Name}='John'" >>> match({"Registered": True}) "{Registered}=1" >>> match({"Owner's Name": "Mike"}) "{Owner\'s Name}='Mike'"
- Return type
str
- pyairtable.formulas.escape_quotes(value)[source]¶
Ensures any quotes are escaped. Already escaped quotes are ignored.
- Parameters
value (
str
) – text to be escaped
- Usage:
>>> escape_quotes("Player's Name") Player\'s Name >>> escape_quotes("Player\'s Name") Player\'s Name
- Return type
str
- pyairtable.formulas.to_airtable_value(value)[source]¶
Cast value to appropriate airtable types and format. For example, to check
bool
values in formulas, you actually to compare to 0 and 1.Input
Output
bool
int
str
str
; text is wrapped in ‘single quotes’; existing quotes are escaped.all others
unchanged
- Parameters
value (
Any
) – value to be cast.- Return type
Any
- pyairtable.formulas.EQUAL(left, right)[source]¶
Creates an equality assertion
>>> EQUAL(2,2) '2=2'
- Return type
str
- pyairtable.formulas.FIELD(name)[source]¶
Creates a reference to a field. Quotes are escaped.
- Parameters
name (
str
) – field name
- Usage:
>>> FIELD("First Name") '{First Name}' >>> FIELD("Guest's Name") "{Guest\'s Name}"
- Return type
str
- pyairtable.formulas.STR_VALUE(value)[source]¶
Wraps string in quotes. This is needed when referencing a string inside a formula. Quotes are escaped.
>>> STR_VALUE("John") "'John'" >>> STR_VALUE("Guest's Name") "'Guest\'s Name'" >>> EQUAL(STR_VALUE("John"), FIELD("First Name")) "'John'={First Name}"
- Return type
str
- pyairtable.formulas.IF(logical, value1, value2)[source]¶
Creates an IF statement
>>> IF(1=1, 0, 1) 'IF(1=1, 0, 1)'
- Return type
str
- pyairtable.formulas.FIND(what, where, start_position=0)[source]¶
Creates a FIND statement
>>> FIND(STR(2021), FIELD('DatetimeCol')) "FIND('2021', {DatetimeCol})"
- Parameters
what (
str
) – String to search forwhere (
str
) – Where to search. Could be a string, or a field reference.start_position (
int
, default:0
) – Index of where to start search. Default is 0.
- Return type
str
- pyairtable.formulas.AND(*args)[source]¶
Creates an AND Statement
>>> AND(1, 2, 3) 'AND(1, 2, 3)'
- Return type
str
Module: 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.
- class 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 adict
as well.- id: str¶
Airtable’s unique ID for the user, in the format
usrXXXXXXXXXXXXXX
.
- email: Optional[str]¶
The email address of the user.
- name: Optional[str]¶
The display name of the user.
- class 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='2023-06-07T17:46:24.435891', 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()
- id: str¶
The unique ID of the comment.
- text: str¶
The text of the comment.
- created_time: str¶
The ISO 8601 timestamp of when the comment was created.
- last_updated_time: Optional[str]¶
The ISO 8601 timestamp of when the comment was last edited.
- author: pyairtable.models.collaborator.Collaborator¶
The account which created the comment.
- mentioned: Optional[Dict[str, Comment.Mentioned]]¶
Users or groups that were mentioned in the text.
- class Mentioned[source]¶
A user or group that was mentioned within a comment. Stored as a
dict
that 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.
- class 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='2023-07-01T00:00:00.000Z' ) >>> 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="2023-07-01T00:00:00.000Z", specification: WebhookSpecification(...) ) >>> webhooks[0].disable_notifications() >>> webhooks[0].enable_notifications() >>> webhooks[0].extend_expiration() >>> webhooks[0].delete()
- 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="2022-02-01T21:25:05.663Z", 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
]
- class 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.payloads
to retrieve the actual payloads describing the change(s) which triggered the webhook.You will also need some way to persist the
cursor
of the webhook payload, so that on subsequent calls you do not retrieve the same payloads again.- Usage:
from flask import Flask, request from pyairtable import Api from pyairtable.models import WebhookNotification app = Flask(__name__) @app.route("/airtable-webhook", methods=["POST"]) def airtable_webhook(): body = request.data header = request.headers["X-Airtable-Content-MAC"] secret = app.config["AIRTABLE_WEBHOOK_SECRET"] event = WebhookNotification.from_request(body, header, secret) airtable = Api(app.config["AIRTABLE_API_KEY"]) webhook = airtable.base(event.base.id).webhook(event.webhook.id) cursor = int(your_db.get(f"cursor_{event.webhook}", 0)) + 1 for payload in webhook.payloads(cursor=cursor): # ...do stuff... your_db.set(f"cursor_{event.webhook}", payload.cursor) return ("", 204) # intentionally empty response
See Webhook notification delivery for more information on how these payloads are structured.
- classmethod from_request(body, header, secret)[source]¶
Validates 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.
- class pyairtable.models.WebhookPayload[source]¶
Payload returned by
Webhook.payloads()
. See API docs: Webhooks payload.- cursor: Optional[int]¶
This is not a part of Airtable’s webhook payload specification. This indicates the cursor field in the response which provided this payload.
Module: pyairtable.orm¶
- class pyairtable.orm.Model[source]¶
Supports creating ORM-style classes representing Airtable tables. For more details, see ORM.
A nested class called
Meta
is 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
.
from pyairtable.orm import Model, fields class Contact(Model): first_name = fields.TextField("First Name") age = fields.IntegerField("Age") class Meta: base_id = "appaPqizdsNHDvlEm" table_name = "Contact" api_key = "keyapikey" timeout = (5, 5) typecast = True
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): first_name = fields.TextField("First Name") age = fields.IntegerField("Age") class Meta: base_id = "appaPqizdsNHDvlEm" table_name = "Contact" @staticmethod def api_key(): return get_secret("AIRTABLE_API_KEY")
- __init__(**fields)[source]¶
Constructs 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'>
- save()[source]¶
Saves or updates a model.
If the instance does not exist already, it will be created; otherwise, the existing record will be updated.
Returns
True
if a record was created andFalse
if it was updated.- Return type
bool
- delete()[source]¶
Deletes the record.
- Raises
ValueError – if the record does not exist.
- Return type
bool
- classmethod all(**kwargs)[source]¶
Returns all records for this model. For all supported keyword arguments, see
Table.all
.- Return type
List
[Self
]
- classmethod first(**kwargs)[source]¶
Returns the first record for this model. For all supported keyword arguments, see
Table.first
.- Return type
Optional
[Self
]
- to_record(only_writable=False)[source]¶
Returns a dictionary object as an Airtable record. This method converts internal field values into values expected by Airtable. For example, a
datetime
value fromDatetimeField
is 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_id(record_id, fetch=True)[source]¶
Create an instance from a record ID.
- Parameters
record_id (
str
) – An Airtable record id.fetch (
bool
, default:True
) – IfTrue
, record will be fetched and field values will be updated. IfFalse
, a new instance is created with the provided ID, but field values are unset.
- Return type
Self
- fetch()[source]¶
Fetches field values from the API and resets instance field values.
- Return type
None
- classmethod from_ids(record_ids, fetch=True)[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.
- Return type
List
[Self
]
- classmethod batch_save(models)[source]¶
Saves 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]¶
Deletes 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
Module: pyairtable.orm.fields¶
Field are used to define the Airtable column type for your pyAirtable models.
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,
}
}
- 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 two type parameters,
T_API
andT_ORM
, which indicate the type returned by the API and the type used to store values internally.Subclasses should also define
valid_types
as a type or tuple of types, which will be used to validate the type of field values being set via this descriptor.- __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]¶
Returns the value which should be persisted to the API.
- Return type
Any
- pyairtable.orm.fields.AnyField¶
An alias for any type of Field.
alias of
pyairtable.orm.fields.Field
[Any
,Any
]
- class pyairtable.orm.fields.TextField[source]¶
Used for all Airtable text fields. Accepts
str
.See Single line text and Long text.
- class pyairtable.orm.fields.NumberField[source]¶
Number field with unspecified precision. Accepts either
int
orfloat
.See Number.
- class pyairtable.orm.fields.IntegerField[source]¶
Number field with integer precision. Accepts only
int
values.See Number.
- class pyairtable.orm.fields.FloatField[source]¶
Number field with decimal precision. Accepts only
float
values.See Number.
- class pyairtable.orm.fields.RatingField[source]¶
Accepts
int
values that are greater than zero.See Rating.
- class pyairtable.orm.fields.CheckboxField[source]¶
Returns
False
instead ofNone
if the field is empty on the Airtable base.See Checkbox.
- class pyairtable.orm.fields.DatetimeField[source]¶
DateTime field. Accepts only datetime values.
See Date and time.
- class pyairtable.orm.fields.DateField[source]¶
Date field. Accepts only date values.
See Date.
- class pyairtable.orm.fields.DurationField[source]¶
Duration field. Accepts only timedelta values.
See Duration. Airtable’s API returns this as a number of seconds.
- pyairtable.orm.fields.LinkSelf = _LinkFieldOptions.LinkSelf¶
Sentinel option for the model= param to
LinkField
- 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
.- __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
str
that is the fully qualified module and class name. For example,"your.module.Model"
will importModel
fromyour.module
.You can provide a
str
that 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 oly IDs; callfetch()
to retrieve values.
- property linked_model: Type[pyairtable.orm.fields.T_Linked]¶
Resolves a
Model
class based on themodel=
constructor parameter to this field instance.- Return type
Type
[Model
]
- class pyairtable.orm.fields.AttachmentsField[source]¶
Accepts a list of dicts in the format detailed in Attachments.
- class pyairtable.orm.fields.AutoNumberField[source]¶
Equivalent to
IntegerField(readonly=True)
.See Auto number.
- class pyairtable.orm.fields.BarcodeField[source]¶
Accepts a dict that should conform to the format detailed in the Barcode documentation.
- class pyairtable.orm.fields.ButtonField[source]¶
Read-only field that returns a dict. For more information, read the Button documentation.
- class pyairtable.orm.fields.CollaboratorField[source]¶
Accepts a dict that should conform to the format detailed in the Collaborator documentation.
- class pyairtable.orm.fields.CountField[source]¶
Equivalent to
IntegerField(readonly=True)
.See Count.
- class pyairtable.orm.fields.CreatedByField[source]¶
Equivalent to
CollaboratorField(readonly=True)
.See Created by.
- class pyairtable.orm.fields.CreatedTimeField[source]¶
Equivalent to
DatetimeField(readonly=True)
.See Created time.
- class pyairtable.orm.fields.CurrencyField[source]¶
Equivalent to
NumberField
.See Currency.
- class pyairtable.orm.fields.ExternalSyncSourceField[source]¶
Equivalent to
TextField(readonly=True)
.See Sync source.
- class pyairtable.orm.fields.LastModifiedByField[source]¶
Equivalent to
CollaboratorField(readonly=True)
.See Last modified by.
- class pyairtable.orm.fields.LastModifiedTimeField[source]¶
Equivalent to
DatetimeField(readonly=True)
.See Last modified time.
- 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", ...]
See Lookup.
- class pyairtable.orm.fields.MultipleCollaboratorsField[source]¶
Accepts a list of dicts in the format detailed in Multiple Collaborators.
- class pyairtable.orm.fields.MultipleSelectField[source]¶
Accepts a list of
str
.See Multiple select.
- class pyairtable.orm.fields.PercentField[source]¶
Equivalent to
NumberField
.See Percent.
- class pyairtable.orm.fields.SelectField[source]¶
Equivalent to
TextField
.See Single select.
- pyairtable.orm.fields.ALL_FIELDS¶
Set of all Field subclasses exposed by the library.
- pyairtable.orm.fields.READONLY_FIELDS¶
Set of all read-only Field subclasses exposed by the library.
- pyairtable.orm.fields.FIELD_TYPES_TO_CLASSES¶
Mapping of Airtable field type names to their ORM classes. See https://airtable.com/developers/web/api/field-model and Formulas, Rollups, and Lookups.
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
.
- pyairtable.orm.fields.FIELD_CLASSES_TO_TYPES¶
Mapping of field classes to the set of supported Airtable field types.
Module: pyairtable.utils¶
- pyairtable.utils.datetime_to_iso_str(value)[source]¶
Converts
datetime
object into Airtable compatible ISO 8601 string e.g. “2014-09-05T12:34:56.000Z”- Parameters
value (
datetime
) – datetime object- Return type
str
- pyairtable.utils.datetime_from_iso_str(value)[source]¶
Convert an ISO 8601 datetime string into a
datetime
object.- Parameters
value (
str
) – datetime string, e.g. “2014-09-05T07:00:00.000Z”- Return type
datetime
- pyairtable.utils.date_to_iso_str(value)[source]¶
Converts a
date
ordatetime
into 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.date_from_iso_str(value)[source]¶
Converts ISO 8601 date string into a
date
object.- Parameters
value (
str
) – date string, e.g. “2014-09-05”- Return type
date
- pyairtable.utils.attachment(url, filename='')[source]¶
Returns a dictionary using the expected dictionary format for creating attachments.
When creating an attachment,
url
is required, andfilename
is 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
AttachmentDict
orCreateAttachmentDict
; it is not valid to pass a single item to the API.- Usage:
>>> table = Table(...) >>> profile_url = "https://myprofile.com/id/profile.jpg >>> rec = table.create({"Profile Photo": [attachment(profile_url)]}) { 'id': 'recZXOZ5gT9vVGHfL', 'fields': { 'attachment': [ { 'id': 'attu6kbaST3wUuNTA', 'url': 'https://aws1.discourse-cdn.com/airtable/original/2X/4/411e4fac00df06a5e316a0585a831549e11d0705.png', 'filename': '411e4fac00df06a5e316a0585a831549e11d0705.png' } ] }, 'createdTime': '2021-08-21T22:28:36.000Z' }
- Return type