This is how you can create an AI agent that’s connected to a live Airtable database.
How to Build a Custom Function with Airtable
from flask import Flask, request, jsonify, render_template
import requests
import os
app = Flask(__name__)
# Airtable configuration
AIRTABLE_API_KEY = 'replace with your key'
AIRTABLE_BASE_ID = 'replace with your key'
AIRTABLE_TABLE_NAME = 'replace with your key' # Replace with actual Table Name if provided
# Field IDs based on the information you provided
# This will be customized to your Airtable database via your API docs
FIELD_ID_NAME = 'fldGprEVDGbIIaFM6'
FIELD_ID_DESCRIPTION = 'fldAzPuEpylWSRH5U'
FIELD_ID_TAGS = 'fld2CdWr5jqRvhMjd'
FIELD_ID_URL = 'fld3LEcLjgQ8P6IL8'
FIELD_ID_VIDEO_LINK = 'fldoe2USaEQnZjVVK'
FIELD_ID_CREATED = 'fldeg2qGCU2nrHV6x'
# Function to fetch data from Airtable and find the closest match
def find_website_info(query):
url = f'<https://api.airtable.com/v0/{AIRTABLE_BASE_ID}/{AIRTABLE_TABLE_NAME}>'
headers = {
'Authorization': f'Bearer {AIRTABLE_API_KEY}'
}
# Use the FIELD_ID_NAME to search for the query in the Name field
params = {
'filterByFormula': f"SEARCH(LOWER('{query}'), LOWER({{{FIELD_ID_NAME}}})) > 0"
}
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
records = response.json().get('records', [])
if records:
return records[0].get('fields', {})
else:
return None
else:
raise Exception(f"Error fetching data from Airtable: {response.status_code}")
@app.route('/get_website_info', methods=['POST'])
def get_website_info():
data = request.json
website_query = data.get('website_query')
if not website_query:
return jsonify({"error": "Please provide a website query"}), 400
try:
website_info = find_website_info(website_query)
if website_info:
return jsonify(website_info), 200
else:
return jsonify({"error": "No matching website found"}), 404
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
port = 8080
app.run(host='0.0.0.0', port=port)