This guide demonstrates how to fetch data from an Airtable table using the pyairtable library in Python. pyairtable makes it super easy to interact with Airtable. You’ll learn how to set up your environment, configure your API key, and query records from an Airtable table. You can find more details in the pyairtable documentation.
fetch_airtable_data.py
Copy
import osfrom dotenv import load_dotenvfrom pyairtable import Apifrom pyairtable.formulas import match# Load environment variables from .env fileload_dotenv()# Get Airtable API key and base ID from environment variablesairtable_api_key = os.getenv('AIRTABLE_API_KEY')airtable_base_id = os.getenv('AIRTABLE_BASE_ID')airtable_table_name = os.getenv('AIRTABLE_TABLE_NAME')# Initialize the Airtable API and tableapi = Api(airtable_api_key)table = api.table(airtable_base_id, airtable_table_name)# Define the formula to match records (optional)# Example formula to filter records where the "Name" field is "John Doe"formula = match({"Name": "John Doe"}) # Modify as needed or set to None if no filtering is required# Fetch all records, applying the formula if it existsrecords = table.all(formula=formula)# Print the retrieved recordsfor record in records: print(record)
Create a Python script named fetch_airtable_data.py with the following content:
fetch_airtable_data.py
Copy
import osfrom dotenv import load_dotenvfrom pyairtable import Apifrom pyairtable.formulas import match# Load environment variables from .env fileload_dotenv()# Get Airtable API key and base ID from environment variablesairtable_api_key = os.getenv('AIRTABLE_API_KEY')airtable_base_id = os.getenv('AIRTABLE_BASE_ID')airtable_table_name = os.getenv('AIRTABLE_TABLE_NAME')# Initialize the Airtable API and tableapi = Api(airtable_api_key)table = api.table(airtable_base_id, airtable_table_name)# Define the formula to match records (optional)# Example formula to filter records where the "Name" field is "John Doe"formula = match({"Name": "John Doe"}) # Modify as needed or set to None if no filtering is required# Fetch all records, applying the formula if it existsrecords = table.all(formula=formula)# Print the retrieved recordsfor record in records: print(record)
You have successfully retrieved data from an Airtable table using the pyairtable library with the new Api.table() method! This guide provided a basic example to get you started. You can now expand on this by customizing the queries and handling different tables and fields in your Airtable base.