### Install pyAirtable using pip Source: https://pyairtable.readthedocs.io/en/3.3.0/getting-started This command installs the pyAirtable library, which allows you to interact with Airtable from your Python projects. Ensure you have pip installed and accessible in your environment. ```bash $ pip install pyairtable ``` -------------------------------- ### Setup pyAirtable Project and Dependencies Source: https://pyairtable.readthedocs.io/en/3.3.0/about This snippet details the steps to clone the pyAirtable repository, set up a virtual environment, and install the package with its dependencies. It also includes commands for running tests, linting, and building documentation locally. ```bash git clone git@github.com:gtalarico/pyairtable.git cd pyairtable # Create Virtual Environment python3 -m venv .venv source .venv/bin/activate make setup # Sets up githooks and install package and depedencies make test # run test complete suite # Optional, use as needed make lint # lints locally - also done in pre-merge CI make docs # builds docs locally - see `docs/build/index.html` ``` -------------------------------- ### Quickstart pyAirtable API Operations Source: https://pyairtable.readthedocs.io/en/3.3.0/getting-started Demonstrates how to connect to Airtable using an API key stored as an environment variable, and perform common table operations: fetching all records, creating a new record, updating an existing record, and deleting a record. It requires the 'AIRTABLE_API_KEY' environment variable to be set. ```python >>> import os >>> from pyairtable import Api >>> api = Api(os.environ['AIRTABLE_API_KEY']) >>> table = api.table('appExampleBaseId', 'tblExampleTableId') >>> table.all() [ { "id": "rec5eR7IzKSAOBHCz", "createdTime": "2017-03-14T22:04:31.000Z", "fields": { "Name": "Alice", "Email": "alice@example.com" } } ] >>> table.create({"Name": "Bob"}) { "id": "recwAcQdqwe21asdf", "createdTime": "...", "fields": {"Name": "Bob"} } >>> table.update("recwAcQdqwe21asdf", {"Name": "Robert"}) { "id": "recwAcQdqwe21asdf", "createdTime": "...", "fields": {"Name": "Robert"} } >>> table.delete("recwAcQdqwe21asdf") {'id': 'recwAcQdqwe21asdf', 'deleted': True} ``` -------------------------------- ### Install and Use pyAirtable CLI Source: https://pyairtable.readthedocs.io/en/3.3.0/cli Installs the pyAirtable CLI with necessary dependencies and demonstrates basic usage for authentication and retrieving data. Requires setting the AIRTABLE_API_KEY environment variable. ```bash % pip install 'pyairtable[cli]' % read -s AIRTABLE_API_KEY ... % export AIRTABLE_API_KEY % pyairtable whoami {"id": "usrXXXXXXXXXXXX", "email": "you@example.com"} % pyairtable base YOUR_BASE_ID table YOUR_TABLE_NAME records [{"id": "recXXXXXXXXXXXX", "fields": {...}}, ...] ``` -------------------------------- ### Airtable Button Dictionary Example (Python) Source: https://pyairtable.readthedocs.io/en/3.3.0/api Illustrates the dictionary format for values in an Airtable 'Button' field. This example shows how to retrieve the button's label and the associated URL. ```python >>> record = table.get('recW8eG2x0ew1Af') >>> record['fields']['Click Me'] {'label': 'Click Me', 'url': 'http://example.com'} ``` -------------------------------- ### Example Usage of Mentioned Model Source: https://pyairtable.readthedocs.io/en/3.3.0/api Demonstrates how to access the 'mentioned' attribute from a comment object to retrieve a dictionary of mentioned users or groups. The example shows a typical output structure. ```python comment = table.add_comment(record_id, "Hello, @[usrVMNxslc6jG0Xed]!") print(comment.mentioned) # Expected output: # { # "usrVMNxslc6jG0Xed": Mentioned( # display_name='Alice', # email='alice@example.com', # id='usrVMNxslc6jG0Xed', # type='user' # ) # } ``` -------------------------------- ### Example of Accessing Bidirectional Links in pyAirtable Source: https://pyairtable.readthedocs.io/en/3.3.0/orm Provides an example of accessing linked records in a scenario with cyclical links, demonstrating traversal through `manager`, `reports`, and `company.employees` fields. ```python >>> person = Person.from_id("recZ6qSLw0OCA61ul") >>> person.manager >>> person.manager.reports [, ...] >>> person.company.employees [, , ...] ``` -------------------------------- ### Airtable Barcode Dictionary Example (Python) Source: https://pyairtable.readthedocs.io/en/3.3.0/api Provides an example of the dictionary structure for values stored in an Airtable 'Barcode' field. It shows how to access the barcode type and its text representation. ```python >>> record = table.get('recW8eG2x0ew1Af') >>> record['fields']['Barcode'] {'type': 'upce', 'text': '01234567'} ``` -------------------------------- ### Airtable Attachment Dictionary Example (Python) Source: https://pyairtable.readthedocs.io/en/3.3.0/api Illustrates the dictionary format for attachments stored in an Airtable 'Attachments' field. This example shows how to access attachment details like ID, URL, and filename. ```python >>> record = table.get('recW8eG2x0ew1Af') >>> record['fields']['Attachments'] [ { 'id': 'attW8eG2x0ew1Af', 'url': 'https://example.com/hello.jpg', 'filename': 'hello.jpg' } ] ``` -------------------------------- ### Instantiate pyairtable ORM Model Source: https://pyairtable.readthedocs.io/en/3.3.0/api Provides examples of how to instantiate a pyairtable ORM Model. It shows creating a new unsaved record and creating a record with a pre-existing ID. ```python from pyairtable.orm import Model, fields from datetime import date class Contact(Model): class Meta: base_id = "appaPqizdsNHDvlEm" table_name = "Contact" api_key = "keyapikey" first_name = fields.TextField("First Name") age = fields.IntegerField("Age") # Example 1: Creating an unsaved instance Contact(name="Alice", birthday=date(1980, 1, 1)) # Example 2: Creating an instance with a specific ID Contact(id="recWPqD9izdsNvlE", name="Bob") ``` -------------------------------- ### Pytest Fixture for Mock Airtable Source: https://pyairtable.readthedocs.io/en/3.3.0/tables Shows how to set up MockAirtable as an autouse pytest fixture. This automatically mocks Airtable for all tests within the scope, simplifying test setup. ```python import pytest from pyairtable.testing import MockAirtable @pytest.fixture(autouse=True) def mock_airtable(): with MockAirtable() as m: yield m def test_your_function(): ... ``` -------------------------------- ### Example of UpsertResultDict in Python Source: https://pyairtable.readthedocs.io/en/3.3.0/api Illustrates the structure of UpsertResultDict, returned after an upsert operation. It contains lists of 'createdRecords', 'updatedRecords', and all 'records' involved in the operation. This provides a summary of the upsert process. ```python >>> table.batch_upsert(records, key_fields=["Name"]) { 'createdRecords': [...], 'updatedRecords': [...], 'records': [...] } ``` -------------------------------- ### Manage Shares on a Base (pyAirtable) Source: https://pyairtable.readthedocs.io/en/3.3.0/enterprise Demonstrates how to manage existing shares on a base using pyAirtable. This includes disabling, enabling, and deleting shares. ```python >>> share = base.shares()[0] >>> share.disable() >>> share.enable() >>> share.delete() ``` -------------------------------- ### Get Week Number - WEEKNUM Function Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/formulas The WEEKNUM function calculates the week number within a year. Similar to WEEKDAY, it allows an optional second argument to define the start of the week ('Sunday' or 'Monday'). The default start day for the week is Sunday. ```python def WEEKNUM(date: FunctionArg, start_day_of_week: Optional[FunctionArg] = None, /) -> FunctionCall: """ 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 FunctionCall('WEEKNUM', date, *(v for v in [start_day_of_week] if v is not None)) ``` -------------------------------- ### Get Day of Week - WEEKDAY Function Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/formulas The WEEKDAY function returns the day of the week as an integer from 0 (Sunday) to 6 (Saturday). It can optionally accept a second argument to specify the start of the week as either 'Sunday' or 'Monday'. If omitted, the week defaults to starting on Sunday. ```python def WEEKDAY(date: FunctionArg, start_day_of_week: Optional[FunctionArg] = None, /) -> FunctionCall: """ 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 FunctionCall('WEEKDAY', date, *(v for v in [start_day_of_week] if v is not None)) ``` -------------------------------- ### Mock Airtable for Basic Testing Source: https://pyairtable.readthedocs.io/en/3.3.0/tables Demonstrates how to use MockAirtable as a context manager to mock pyAirtable APIs for testing. It shows adding records and asserting their presence without actual network requests. ```python 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 ``` -------------------------------- ### Define User and Scopes Structure (Python) Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/api/types Defines the dictionary structure returned by the 'Get user ID & scopes' endpoint of the Airtable API. It includes the user's 'id' and a list of their associated 'scopes'. An example shows the output of the `api.whoami()` method. ```python from typing import Dict, List, Any, Union, TypeAlias, Required class UserAndScopesDict(TypedDict, total=False): """ A ``dict`` representing the `Get user ID & scopes `_ endpoint. Usage: >>> api.whoami() {'id': 'usrX9e810wHn3mMLz'} """ id: Required[str] scopes: List[str] ``` -------------------------------- ### Initialize Api with Options Source: https://pyairtable.readthedocs.io/en/3.3.0/api Illustrates the full initialization of the pyairtable Api class, including optional parameters like timeout, retry strategy, custom endpoint URL, and the use of field IDs. This provides flexibility for different API interaction scenarios. ```python from pyairtable import Api from urllib.retry import Retry api = Api( 'auth_token', timeout=(2, 5), retry_strategy=Retry(total=3), endpoint_url='https://api.airtable.com', use_field_ids=False ) ``` -------------------------------- ### ORM List Type Change Example - Python Source: https://pyairtable.readthedocs.io/en/3.3.0/migrations Demonstrates the change in type for fields containing lists in pyAirtable 3.0. Fields that previously returned a standard `list` now return a `ChangeTrackingList`, a subclass of `list`. This change might affect code relying on exact type checking. ```python >>> isinstance(Foo().atts, list) True >>> type(Foo().atts) is list False >>> type(Foo().atts) ``` -------------------------------- ### Initialize and Get Enterprise Info with pyairtable Source: https://pyairtable.readthedocs.io/en/3.3.0/api Shows how to initialize an `Enterprise` object and retrieve its basic information using the `info` method. This requires an Enterprise billing plan and is part of the `pyairtable.Enterprise` class. ```python >>> enterprise = api.enterprise("entUBq2RGdihxl3vU") >>> enterprise.info().workspace_ids ['wspmhESAta6clCCwF', ...] ``` -------------------------------- ### Iterate Airtable Webhook Payloads (Python) Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/models/webhook Provides an example of how to iterate through webhook payloads from an Airtable webhook using pyairtable. It demonstrates fetching payloads starting from a specific cursor and optionally limiting the number of payloads retrieved. Each payload includes a 'cursor' attribute for resuming retrieval. ```python from pyairtable.api import Api from pyairtable.models.webhook import Webhook # Assuming 'api' is an authenticated Api instance and 'webhook_id' is the ID of an existing webhook webhook = Webhook(api=api, webhook_id='ach00000000000001') # Iterate through all payloads starting from cursor 1 for payload in webhook.payloads(): print(payload) # Iterate through payloads with a limit for payload in webhook.payloads(limit=5): print(payload) ``` -------------------------------- ### Find Substring Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/formulas Finds the starting position of a substring within a larger string. It can optionally take a starting position for the search. Returns 0 if the substring is not found. ```python from pyairtable.formulas import FunctionCall, FunctionArg from typing import Optional def FIND(string_to_find: FunctionArg, where_to_search: FunctionArg, start_from_position: Optional[FunctionArg] = None, /) -> FunctionCall: """ 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 FunctionCall('FIND', string_to_find, where_to_search, *(v for v in [start_from_position] if v is not None)) ``` -------------------------------- ### pyAirtable CLI Usage and Commands Source: https://pyairtable.readthedocs.io/en/3.3.0/cli Provides the general usage syntax for the pyAirtable CLI, including available options for authentication and verbosity, and lists all supported commands with brief descriptions. ```bash Usage: pyairtable [OPTIONS] COMMAND [ARGS]... Options: -k, --key TEXT Your API key. -kf, --key-file PATH File containing your API key. -ke, --key-env VAR Env var containing your API key. -v, --verbose Print verbose output. --help Show this message and exit. Commands: whoami Print the current user's information. bases List all available bases. base ID schema Print the base schema. base ID table ID_OR_NAME records Retrieve records from the table. base ID table ID_OR_NAME schema Print the table's schema as JSON. base ID collaborators Print base collaborators. base ID shares Print base shares. base ID orm Generate a Python ORM module. enterprise ID info Print information about an enterprise. enterprise ID user ID_OR_EMAIL Print one user's information. enterprise ID users ID_OR_EMAIL... Print many users, keyed by user ID. enterprise ID group ID Print a user group's information. enterprise ID groups ID... Print many groups, keyed by group ID. ``` -------------------------------- ### Instantiate Base Object Source: https://pyairtable.readthedocs.io/en/3.3.0/api Shows how to create a `Base` instance using the `base()` method of an `Api` object. It highlights the option to validate the base ID/name against the Airtable metadata API. ```python base = api.base('base_id', validate=True) ``` -------------------------------- ### PyAirtable v2.0 Constructor Patterns Source: https://pyairtable.readthedocs.io/en/3.3.0/migrations Demonstrates supported and unsupported ways to instantiate Api, Base, and Table objects in PyAirtable v2.0. Highlights patterns that will raise deprecation warnings or TypeErrors due to changes in class inheritance and constructor arguments. ```python >>> api = Api(api_key, timeout=..., retry_strategy=..., endpoint_url=...) >>> base = api.base(base_id) # [str] >>> base = Base(api, base_id) # [Api, str] >>> table = base.table(table_name) # [str] >>> table = api.table(base_id, table_name) # [str, str] >>> table = Table(None, base, table_name) # [None, Base, str] # The following are still supported but will issue a DeprecationWarning: >>> base = Base(api_key, base_id) # [str, str] >>> table = Table(api_key, base_id, table_name) # [str, str, str] # The following will raise a TypeError for mixing str & instances: >>> table = Table(api_key, base, table_name) # [str, Base, str] >>> table = Table(api, base_id, table_name) # [Api, str, str] # The following will raise a TypeError. We do this proactively # to avoid situations where self.api and self.base don't align. >>> table = Table(api, base, table_name) # [Api, Base, str] ``` -------------------------------- ### Example of CreateRecordDict in Python Source: https://pyairtable.readthedocs.io/en/3.3.0/api Illustrates the structure of a CreateRecordDict, used for creating new records in Airtable. It requires a 'fields' dictionary containing the data for the new record. This is essential for adding new entries to your Airtable base. ```python >>> table.create({ ... "fields": { ... "Field Name": "Field Value", ... "Other Field": ["Value 1", "Value 2"] ... } ... }) ``` -------------------------------- ### Airtable Collaborator Dictionary Example (Python) Source: https://pyairtable.readthedocs.io/en/3.3.0/api Shows the dictionary structure for collaborator information returned by the Airtable API, including user ID, email, and name. It also demonstrates how multiple collaborators are represented in a list. ```python >>> 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' } ] ``` -------------------------------- ### String Searching (SEARCH) Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/formulas The SEARCH function finds the starting position of a substring within a larger string. It can optionally start the search from a specified position. If the substring is not found, it returns an empty result. ```Python from pyairtable.formulas import FunctionCall, FunctionArg from typing import Optional def SEARCH(string_to_find: FunctionArg, where_to_search: FunctionArg, start_from_position: Optional[FunctionArg] = None, /) -> FunctionCall: """ 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 FunctionCall('SEARCH', string_to_find, where_to_search, *(v for v in [start_from_position] if v is not None)) ``` -------------------------------- ### Manage Workspaces and Organizations (pyAirtable) Source: https://pyairtable.readthedocs.io/en/3.3.0/enterprise Details pyAirtable functionalities for creating and moving workspaces, moving user groups, and creating descendant enterprises within an organization. ```python >>> workspace_id = enterprise.create_workspace("My New Workspace") >>> enterprise.move_workspaces(["wspId1", "wspId2"], "entTargetEnterpriseId") >>> enterprise.move_groups(["ugpId1", "ugpId2"], "entTargetEnterpriseId") >>> descendant = enterprise.create_descendant("Descendant Organization Name") ``` -------------------------------- ### Instantiate Table Object Source: https://pyairtable.readthedocs.io/en/3.3.0/api Illustrates how to create a `Table` instance using the `table()` method of an `Api` object. Similar to `base()`, it allows for validation of the table ID/name and offers a `force` option to bypass cache. ```python table = api.table('base_id', 'table_name', validate=True) ``` -------------------------------- ### HTTP Methods (GET, POST, PATCH, DELETE) Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/api/api Provides methods to make direct HTTP requests to the Airtable API using GET, POST, PATCH, and DELETE. These methods abstract the underlying request logic and handle response processing. ```APIDOC ## GET /api/resource ### Description Make a GET request to the Airtable API. ### Method GET ### Endpoint /api/resource ### Parameters #### Query Parameters - **kwargs** (Any) - Optional - Additional keyword arguments to pass to the underlying request function. ### Request Example ```python api.get('/your_endpoint') ``` ### Response #### Success Response (200) - **Any** - The response from the Airtable API, processed by the library. ## POST /api/resource ### Description Make a POST request to the Airtable API. ### Method POST ### Endpoint /api/resource ### Parameters #### Query Parameters - **kwargs** (Any) - Optional - Additional keyword arguments to pass to the underlying request function. ### Request Example ```python api.post('/your_endpoint', json={'key': 'value'}) ``` ### Response #### Success Response (200) - **Any** - The response from the Airtable API, processed by the library. ## PATCH /api/resource ### Description Make a PATCH request to the Airtable API. ### Method PATCH ### Endpoint /api/resource ### Parameters #### Query Parameters - **kwargs** (Any) - Optional - Additional keyword arguments to pass to the underlying request function. ### Request Example ```python api.patch('/your_endpoint', json={'key': 'new_value'}) ``` ### Response #### Success Response (200) - **Any** - The response from the Airtable API, processed by the library. ## DELETE /api/resource ### Description Make a DELETE request to the Airtable API. ### Method DELETE ### Endpoint /api/resource ### Parameters #### Query Parameters - **kwargs** (Any) - Optional - Additional keyword arguments to pass to the underlying request function. ### Request Example ```python api.delete('/your_endpoint') ``` ### Response #### Success Response (200) - **Any** - The response from the Airtable API, processed by the library. ``` -------------------------------- ### Create and Save Airtable Record with pyAirtable ORM Source: https://pyairtable.readthedocs.io/en/3.3.0/orm Demonstrates creating a new record object using a pyAirtable ORM model and saving it to Airtable. It shows how to instantiate a model, check if it exists, save it, and verify its existence and retrieve its ID. ```python >>> contact = Contact( ... first_name="Mike", ... last_name="McDonalds", ... email="mike@mcd.com", ... is_registered=False ... ) >>> assert contact.id is None >>> contact.exists() False >>> assert contact.save() >>> contact.exists() True >>> contact.id 'recS6qSLw0OCA6Xul' ``` -------------------------------- ### Get Workspace Name Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/api/workspace Retrieves the name of the workspace. This is an Enterprise-only feature. ```APIDOC ## GET Workspace Name ### Description Get the name of the workspace. This operation is restricted to Enterprise users. ### Method GET (via property) ### Endpoint N/A (accessed via `workspace.name` property) ### Response #### Success Response (200) - **name** (str) - The name of the workspace. #### Response Example ```python 'My Workspace Name' ``` ``` -------------------------------- ### Creating Schema Elements Source: https://pyairtable.readthedocs.io/en/3.3.0/metadata Methods for creating bases, tables, and fields within Airtable. ```APIDOC ## Api.create_base ### Description Create a base in the given workspace. See https://airtable.com/developers/web/api/create-base ### Method POST ### Endpoint /v0/{workspace_id} ### Parameters #### Path Parameters - **workspace_id** (str) - Required - The ID of the workspace where the new base will live. #### Request Body - **name** (str) - Required - The name to give to the new base. Does not need to be unique. - **tables** (Sequence[Dict[str, Any]]) - Required - A list of `dict` objects that conform to Airtable’s Table model. ### Response #### Success Response (200) - **Base** (Base) - The created Base object. ### Request Example ```json { "name": "My New Base", "tables": [ { "name": "My Table", "fields": [ {"name": "Name", "type": "singleLineText"} ] } ] } ``` ### Response Example ```json { "id": "appXXXXXXXXXXXXXX", "name": "My New Base", "tables": [ { "id": "tblXXXXXXXXXXXXXX", "name": "My Table", "fields": [ {"id": "fldXXXXXXXXXXXXXX", "name": "Name", "type": "singleLineText"} ] } ] } ``` ``` ```APIDOC ## Workspace.create_base ### Description Create a base in the given workspace. See https://airtable.com/developers/web/api/create-base ### Method POST ### Endpoint /v0/{workspace_id} ### Parameters #### Path Parameters - **workspace_id** (str) - Required - The ID of the workspace where the new base will live. #### Request Body - **name** (str) - Required - The name to give to the new base. Does not need to be unique. - **tables** (Sequence[Dict[str, Any]]) - Required - A list of `dict` objects that conform to Airtable’s Table model. ### Response #### Success Response (200) - **Base** (Base) - The created Base object. ### Request Example ```json { "name": "My New Base", "tables": [ { "name": "My Table", "fields": [ {"name": "Name", "type": "singleLineText"} ] } ] } ``` ### Response Example ```json { "id": "appXXXXXXXXXXXXXX", "name": "My New Base", "tables": [ { "id": "tblXXXXXXXXXXXXXX", "name": "My Table", "fields": [ {"id": "fldXXXXXXXXXXXXXX", "name": "Name", "type": "singleLineText"} ] } ] } ``` ``` ```APIDOC ## Base.create_table ### Description Create a table in the given base. ### Method POST ### Endpoint /v0/{base_id}/tables ### Parameters #### Path Parameters - **base_id** (str) - Required - The ID of the base where the new table will be created. #### Request Body - **name** (str) - Required - The unique table name. - **fields** (Sequence[Dict[str, Any]]) - Required - A list of `dict` objects that conform to the Airtable field model. - **description** (Optional[str]) - Optional - The table description. Must be no longer than 20k characters. ### Response #### Success Response (200) - **Table** (Table) - The created Table object. ### Request Example ```json { "name": "New Table", "fields": [ {"name": "Column A", "type": "text"}, {"name": "Column B", "type": "number"} ], "description": "This is a new table." } ``` ### Response Example ```json { "id": "tblXXXXXXXXXXXXXX", "name": "New Table", "fields": [ {"id": "fldXXXXXXXXXXXXXX", "name": "Column A", "type": "text"}, {"id": "fldXXXXXXXXXXXXXX", "name": "Column B", "type": "number"} ], "description": "This is a new table." } ``` ``` ```APIDOC ## Table.create_field ### Description Create a field on the table. ### Method POST ### Endpoint /v0/{base_id}/tables/{table_id}/fields ### Parameters #### Path Parameters - **base_id** (str) - Required - The ID of the base. - **table_id** (str) - Required - The ID of the table. #### Request Body - **name** (str) - Required - The unique name of the field. - **field_type** (str) - Required - One of the Airtable field types. - **description** (Optional[str]) - Optional - A long form description of the table. - **options** (Optional[Dict[str, Any]]) - Optional - Only available for some field types. For more information, read about the Airtable field model. ### Response #### Success Response (200) - **FieldSchema** (Union[AITextFieldSchema, AutoNumberFieldSchema, ...]) - The created FieldSchema object. ### Request Example ```json { "name": "Attachments", "field_type": "multipleAttachment" } ``` ### Response Example ```json { "id": "fldslc6jG0XedVMNx", "name": "Attachments", "type": "multipleAttachment", "description": null, "options": { "is_reversed": false } } ``` ``` -------------------------------- ### Define Airtable Model with Dictionary Meta Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/orm/model This example demonstrates an alternative way to define an Airtable model 'Contact' using a dictionary for the 'Meta' attribute. This approach is functionally equivalent to using a nested class for 'Meta'. It includes the same connection details and field definitions as the class-based 'Meta' example. ```python 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") ``` -------------------------------- ### Make Airtable API Request - Pyairtable Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/api/api Handles making HTTP requests to the Airtable API. It supports GET and POST methods and can automatically convert a GET request to a POST if the URL exceeds the maximum length limit, using a fallback method and URL. It also manages query parameters and JSON payloads. ```python [docs] def request( self, method: str, url: str, fallback: Optional[Tuple[str, str]] = None, options: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, Any]] = None, json: Optional[Dict[str, Any]] = None, ) -> Any: """ Make a request to the Airtable API, optionally converting a GET to a POST if the URL exceeds the `maximum URL length `__. Args: method: HTTP method to use. url: The URL we're attempting to call. fallback: The method and URL to use if we have to convert a GET to a POST. options: Airtable-specific query params to use while fetching records. See :ref:`Parameters` for valid options. params: Additional query params to append to the URL as-is. json: The JSON payload for a POST/PUT/PATCH/DELETE request. """ # Convert Airtable-specific options to query params, but give priority to query params # that are explicitly passed via `params=`. This is to preserve backwards-compatibility for # any library users who might be calling `self._request` directly. request_params = { **options_to_params(options or {}), **(params or {}), } # Build a requests.PreparedRequest so we can examine how long the URL is. prepared = self.session.prepare_request( requests.Request( method, url=url, params=request_params, json=json, ) ) # If our URL is too long, move *most* (not all) query params into a POST body. if ( fallback and method.upper() == "GET" and len(str(prepared.url)) >= self.MAX_URL_LENGTH ): json, spare_params = options_to_json_and_params(options or {}) return self.request( method=fallback[0], url=fallback[1], params={**spare_params, **(params or {})}, json=json, ) ``` -------------------------------- ### Model Instance Methods Source: https://pyairtable.readthedocs.io/en/3.3.0/api Details the methods available on a model instance for interacting with Airtable records. ```APIDOC ## Model Instance Methods ### Description These methods allow you to perform actions on a model instance, such as initializing, checking existence, saving, deleting, and retrieving records. ### `__init__` #### Description Construct a model instance with field values based on the given keyword arguments. #### Example ```python # Create a new unsaved instance Contact(name="Alice", birthday=date(1980, 1, 1)) # # Create an instance with a pre-existing ID Contact(id="recWPqD9izdsNvlE", name="Bob") # ``` ### `exists()` #### Description Checks if the instance has been saved to Airtable already. #### Return Type `bool` ### `save(_*_, force=False)` #### Description 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`) - If `True`, all fields will be saved, even if they have not changed. #### Return Type `SaveResult` ### `delete()` #### Description Delete the record. #### Raises - **ValueError** - if the record does not exist. #### Return Type `bool` ### `all(*, memoize=None, **kwargs)` #### Description Retrieve all records for this model. For all supported keyword arguments, see `Table.all`. #### Parameters - **memoize** (`Optional[bool]`, default: `None`) - If `True`, any objects created will be memoized for future reuse. If `False`, objects created will _not_ be memoized. The default behavior is defined on the `Model` subclass. #### Return Type `List[Self]` ### `first(*, memoize=None, **kwargs)` #### Description Retrieve the first record for this model. For all supported keyword arguments, see `Table.first`. #### Parameters - **memoize** (`Optional[bool]`, default: `None`) - If `True`, any objects created will be memoized for future reuse. If `False`, objects created will _not_ be memoized. The default behavior is defined on the `Model` subclass. #### Return Type `Optional[Self]` ### `to_record(only_writable=False)` #### Description Build a `RecordDict` to represent this instance. #### Parameters - **only_writable** (`bool`, default: `False`) - If `True`, only writable fields are included in the record. #### Return Type `RecordDict` ``` -------------------------------- ### Webhook.payloads Source: https://pyairtable.readthedocs.io/en/3.3.0/webhooks Iterates through all webhook payloads for a given webhook, starting from a specified cursor. ```APIDOC ## GET /bases/{baseId}/webhooks/{webhookId}/payloads ### Description Iterates through all payloads for a specific webhook, starting from a given cursor. Each payload includes a `cursor` attribute that should be stored to resume retrieval later. ### Method GET ### Endpoint `/bases/{baseId}/webhooks/{webhookId}/payloads` ### Parameters #### Path Parameters - **baseId** (string) - Required - The ID of the base containing the webhook. - **webhookId** (string) - Required - The ID of the webhook whose payloads are to be retrieved. #### Query Parameters - **cursor** (integer) - Optional - The cursor of the first webhook payload to retrieve. Defaults to 1. - **limit** (integer) - Optional - The maximum number of payloads to yield. If not provided, all remaining payloads are retrieved. #### Request Body None ### Request Example ```python webhook = base.webhook("ach00000000000001") iter_payloads = webhook.payloads(cursor=1, limit=10) for payload in iter_payloads: print(payload) ``` ### Response #### Success Response (200) - **Iterator[WebhookPayload]** - An iterator yielding `WebhookPayload` objects. #### Response Example ```json { "timestamp": "2023-10-27T10:00:00Z", "base_transaction_number": 4, "payload_format": "v0", "action_metadata": { "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": null, "error_code": null, "cursor": 1 } ``` ``` -------------------------------- ### Example of a RecordDict in Python Source: https://pyairtable.readthedocs.io/en/3.3.0/api Demonstrates the structure of a RecordDict, which represents a record returned from the Airtable API. It includes the record's ID, creation time, and fields. This can be used to display or process fetched record data. ```python >>> 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 } ``` -------------------------------- ### UserAndScopesDict Source: https://pyairtable.readthedocs.io/en/3.3.0/api Represents the dictionary returned by the Get user ID & scopes endpoint. ```APIDOC ## UserAndScopesDict ### Description A `dict` representing the Get user ID & scopes endpoint. ### Method N/A (Represents a data structure) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) - **id** (str) - The user's ID. #### Response Example ```json { "id": "usrX9e810wHn3mMLz" } ``` ``` -------------------------------- ### Add Collaborators to Base, Interface, or Workspace (pyAirtable) Source: https://pyairtable.readthedocs.io/en/3.3.0/enterprise Demonstrates adding collaborators to a base, interface, or workspace using pyAirtable. Supports adding users, groups, or specifying roles like 'read', 'edit', or 'comment'. ```python >>> base.collaborators().add_user("usrUserId", "read") >>> base.collaborators().add_group("ugpGroupId", "edit") >>> base.collaborators().add("user", "usrUserId", "comment") >>> base.collaborators().interfaces[pbd].add_user("usrUserId", "read") >>> base.collaborators().interfaces[pbd].add_group("ugpGroupId", "read") >>> base.collaborators().interfaces[pbd].add("user", "usrUserId", "read") >>> workspace.collaborators().add_user("usrUserId", "read") >>> workspace.collaborators().add_group("ugpGroupId", "edit") >>> workspace.collaborators().add("user", "usrUserId", "comment") ``` -------------------------------- ### Get Workspace Collaborators Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/api/workspace Retrieves collaborators and invite links for a workspace. This is an Enterprise-only feature. ```APIDOC ## GET /meta/workspaces/{id} ### Description Retrieve basic information, collaborators, and invite links for the given workspace, caching the result. This endpoint is restricted to Enterprise users. See https://airtable.com/developers/web/api/get-workspace-collaborators ### Method GET ### Endpoint /meta/workspaces/{id} ### Parameters #### Path Parameters - **id** (str) - Required - The ID of the workspace. #### Query Parameters - **include** (List[str]) - Optional - Specifies additional information to include in the response. Expected values: `["collaborators", "inviteLinks"]`. ### Response #### Success Response (200) - **name** (str) - The name of the workspace. - **collaborators** (List[Dict[str, Any]]) - A list of collaborators in the workspace. - **inviteLinks** (List[Dict[str, Any]]) - A list of invite links for the workspace. - **baseIds** (List[str]) - A list of base IDs within the workspace. #### Response Example ```json { "name": "My Workspace", "collaborators": [ { "id": "usr123", "name": "John Doe", "email": "john.doe@example.com", "permissionLevel": "admin" } ], "inviteLinks": [ { "id": "inv123", "url": "https://airtable.com/invite/abcde" } ], "baseIds": [ "app123", "app456" ] } ``` ``` -------------------------------- ### Get Table Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/api/api Builds and returns a Table instance for a specific table within a given base. ```APIDOC ## GET /bases/{base_id}/tables/{table_name} ### Description Build a new :class:`Table` instance that uses this instance of :class:`Api`. ### Method GET ### Endpoint /bases/{base_id}/tables/{table_name} ### Parameters #### Path Parameters - **base_id** (str) - Required - The ID of the base. - **table_name** (str) - Required - The Airtable table's ID or name. #### Query Parameters - **validate** (bool) - Optional - If true, validates the table schema. - **force** (bool) - Optional - If true, forces a refresh of the metadata. ### Request Example ```python api.table(base_id='appSW9...', table_name='MyTable') ``` ### Response #### Success Response (200) - **table** (Table) - The requested Table object. #### Response Example ```json { "table": "" } ``` ``` -------------------------------- ### Create Airtable Base using Workspace Source: https://pyairtable.readthedocs.io/en/3.3.0/metadata Creates a new Airtable base within the current workspace context. Requires the base name and a list of table definitions. Returns a Base object. ```python Workspace.create_base(_name_, _tables_) ``` -------------------------------- ### Get Comments for a Record Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/orm/model Retrieves a list of comments associated with a specific record. ```APIDOC ## GET /records/{record_id}/comments ### Description Return a list of comments on this record. ### Method GET ### Endpoint /records/{record_id}/comments ### Parameters #### Path Parameters - **record_id** (str) - Required - The ID of the record to retrieve comments for. ### Response #### Success Response (200) - **List[Comment]** - A list of comment objects. #### Response Example ```json [ { "id": "comXXXXXXXXXXXXXX", "text": "This is a comment.", "createdAgo": "1 day ago", "user": { "id": "usrXXXXXXXXXXXXXX", "name": "User Name" } } ] ``` ``` -------------------------------- ### Create Base Source: https://pyairtable.readthedocs.io/en/3.3.0/_modules/pyairtable/api/api Creates a new base within a specified workspace. Requires workspace ID, base name, and a list of table definitions. ```APIDOC ## POST /workspaces/{workspace_id}/bases ### Description Create a base in the given workspace. See https://airtable.com/developers/web/api/create-base ### Method POST ### Endpoint /workspaces/{workspace_id}/bases ### Parameters #### Path Parameters - **workspace_id** (str) - Required - The ID of the workspace where the new base will live. #### Request Body - **name** (str) - Required - The name to give to the new base. Does not need to be unique. - **tables** (Sequence[Dict[str, Any]]) - Required - A list of ``dict`` objects that conform to Airtable's `Table model `__. ### Request Example ```json { "name": "My New Base", "tables": [ { "name": "Table 1", "primaryFieldId": "fld1", "fields": [ {"id": "fld1", "name": "Name", "type": "singleLineText"} ] } ] } ``` ### Response #### Success Response (200) - **base** (Base) - The newly created Base object. #### Response Example ```json { "base": "" } ``` ``` -------------------------------- ### Create Airtable Attachment by URL Example (Python) Source: https://pyairtable.readthedocs.io/en/3.3.0/api Demonstrates creating a dictionary for a new attachment using its URL and filename. This method is used when adding new files from external sources to an Airtable 'Attachments' field. ```python >>> 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"]) ```