Created on September 3, 2024
This function automates the process of importing a CSV file into Airtable using the Airtable API.
To use the Airtable API, you'll need the following credentials:
This uniquely identifies your Airtable base.
https://airtable.com/app??????/tbl??????/viwXXXXXX
app??????
part of the URL.For example, if your URL is https://airtable.com/app12345678/tblAbCdEfGh/viwXyZaBcD
, your Base ID is app12345678
.
The name of the specific table you're importing data into. This is simply the name of your table as it appears in Airtable.
This authenticates your API requests.
data.records:write
scope to create new recordsschema.bases:read
scope to read the base schemaExample CSV structure:
Name,Email,Phone
John Doe,john@example.com,123-456-7890
Jane Smith,jane@example.com,987-654-3210
import csv
import requests
import os
from io import StringIO
def fetch_from_gdrive(gdrive_file_id):
"""
To run this sample code in Codeupify we have to upload the file to a location that's accessible from
Codeupify's serverless environment. If you are going to run this code locally you can skip this method.
To get the Google Drive file ID:
1. Upload the file to Google Drive
2. Share the file with "everyone" and copy the share link
3. The file id is going to be the long string of numbers and letters - https://drive.google.com/file/d/[YOUR_FILE_ID]/view?usp=drive_link
"""
gdrive_url = f'https://drive.google.com/uc?export=download&id={gdrive_file_id}'
response = requests.get(gdrive_url)
if response.status_code != 200:
raise Exception(f"Failed to fetch file from Google Drive. Status code: {response.status_code}")
# Save the CSV data to a file
with open('/tmp/airtable_import.csv', 'w') as f:
f.write(response.text)
print("CSV data successfully saved to /tmp/airtable_import.csv")
def handler(request):
# Get gdrive_file_id from the request body
gdrive_file_id = request['body'].get('gdrive_file_id')
if not gdrive_file_id:
print("No Google Drive file ID provided.")
return
try:
# Fetch and save data from Google Drive
fetch_from_gdrive(gdrive_file_id)
except Exception as e:
print(str(e))
return
# Prepare Airtable API credentials
personal_access_token = os.getenv('PERSONAL_ACCESS_TOKEN')
base_id = os.getenv('BASE_ID')
table_name = os.getenv('TABLE_NAME')
API_URL = f'https://api.airtable.com/v0/{base_id}/{table_name}'
headers = {
'Authorization': f'Bearer {personal_access_token}',
'Content-Type': 'application/json'
}
# Read from the saved CSV file and upload to Airtable
with open('/tmp/airtable_import.csv', 'r') as f:
csv_reader = csv.DictReader(f)
for row in csv_reader:
response = requests.post(API_URL, json={'fields': row}, headers=headers)
if response.status_code == 200:
print(f"Uploaded: {row}")
else:
print(f"Failed to upload: {row}, Error: {response.text}")
print("CSV data successfully uploaded to Airtable")