可以在API请求中添加一个检查步骤以确保不会重复创建记录。首先,利用Airtable API获取Airtable表中的所有记录,然后在请求之前检查要创建的记录是否已经存在。如果已经存在,则不要提交API请求。以下是一个示例代码段:
import requests
# Airtable API endpoint and authentication headers
api_key = "YOUR_API_KEY"
base_id = "YOUR_BASE_ID"
table_name = "YOUR_TABLE_NAME"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
url = f"https://api.airtable.com/v0/{base_id}/{table_name}"
# Get all records from table
response = requests.get(url, headers=headers)
records = response.json().get("records")
# Check if new record already exists
new_record = {
"fields": {
"Name": "John Doe",
"Age": 30,
"Email": "john.doe@email.com"
}
}
for record in records:
if record.get("fields") == new_record.get("fields"):
print("Record already exists!")
break
else:
# Create new record
response = requests.post(url, headers=headers, json=new_record)
print("New record created successfully.")
在上述例子中,“new_record”变量包含要创建的新记录的字段。检查循环遍历“records”变量,与新记录进行比较。如果找到匹配项,执行“break”语句以退出循环并打印消息“Record already exists!”。如果没有找到匹配项,则执行“else”语句,向Airtable表中添加新记录,并打印消息“New record created successfully.”
上一篇:API线程和静态方法