Background
I’m working on a project where I need to read information from a CSV file and use it to modify existing entries in my Airtable database through Python.
My Table Structure
Here’s what the API documentation shows for updating records:
curl -X PATCH https://api.airtable.com/v0/APP_ID/TABLE_NAME \
-H "Authorization: Bearer API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"records": [
{
"id": "recABC123XYZ789",
"fields": {
"LastName": "Smith",
"FirstName": "John",
"StatusField": "Active",
"EmployeeID": "E123456",
"PhoneNumber": "0612345678",
"MonthlySalary": 8000,
"WorkDaysCount": 22,
"StartDate": "2021-03-15",
"AdvanceRate": 0.25,
"EmailAddress": "[email protected]",
"MaxAdvanceAmount": 4000,
"MonthlyAdvanceLimit": 2,
"FreeAdvancesPerMonth": 1,
"ProcessingFee": 8
}
}
]
}'
What I Want to Accomplish
I only need to update the WorkDaysCount field, and I’ll use EmployeeID as my lookup key.
My CSV structure is simple:
EmployeeID,WorkDaysCount
Current Progress
Step 1 - Reading CSV data:
with open(csv_file, "rt") as file_handle:
reader = csv.DictReader(file_handle)
for index, row in enumerate(reader):
csv_data[index] = row
Step 2 - Converting to JSON format:
formatted_data = json.loads(json.dumps(csv_data, indent=4))
Step 3 - This is where I’m having trouble. I need to transform my CSV data into the proper Airtable format:
update_payload = {
"records": [
{
"fields": {
"EmployeeID": "some_value",
"WorkDaysCount": some_number
}
}
]
}
Possible Solutions I’m Considering
Option A - Build the structure by iterating through my data:
for index in range(len(formatted_data)):
update_payload["records"][index]["fields"]["EmployeeID"] = some_value
update_payload["records"][index]["fields"]["WorkDaysCount"] = some_value
Option B - Create a list first, then add it to the main structure
Final Step - Send the update request:
api_base = f"https://api.airtable.com/v0/{os.environ['app_id']}"
request_headers = {
"Authorization": f"Bearer {os.environ['api_token']}",
"Content-Type": "application/json",
}
def update_table(table_name, payload):
api_url = f"{api_base}/{table_name}"
response = requests.patch(url=api_url, json=payload, headers=request_headers)
return response.json()
Can someone help me figure out the best way to structure my data for the PATCH request?