Feb 03, 202401:42 PM - edited Feb 05, 202403:25 AM
Hey everyone, I just started learning Airtable scripts and I wanted to share my first project. This script uses the free Radar.com API to lookup a valid address from a partial address string, and saves the first matching result back to the table with individual fields for each component of the address.
Just add the Script extension and paste in this script, then fill out the settings pane with your API and field names.
Features
Skips rows that already have a complete address
Caches results while looping over the table, then performs a bulk update to increase performance
Splits bulk update into batches of 50 to avoid issues on large dataset
let cfg = input.config({
title: 'Radar.com API Address Validation',
description: 'Validates addresses using Radar.com API. Requires an API Key from Radar.com.',
items: [
input.config.text('radarApiKey', { label: 'Radar.com API Key' }),
input.config.table('selectedTable', { label: 'Table to use', description: 'Select a table.' }),
input.config.field('selectedField', { label: 'Address Field', parentTable: 'selectedTable' }),
input.config.field('street', { label: 'Street', parentTable: 'selectedTable' }),
input.config.field('city', { label: 'City', parentTable: 'selectedTable' }),
input.config.field('state', { label: 'State', parentTable: 'selectedTable' }),
input.config.field('zip', { label: 'ZIP Code', parentTable: 'selectedTable' })
]
});
const endpoint = "https://api.radar.io/v1/search/autocomplete";
const apiKey = cfg.radarApiKey;
// Function to perform the address lookup
async function lookupAddress(query) {
const url = `${endpoint}?query=${
encodeURIComponent(query)
}`;
const options = {
method: "GET",
headers: {
Authorization: apiKey
}
};
try {
const response = await fetch(url, options);
if (! response.ok)
throw new Error(`HTTP error! Status: ${
response.status
}`);
return await response.json();
} catch (error) {
console.error("Error during address lookup:", error);
return null; // Return null to indicate an error occurred
}
}
const table = base.getTable(cfg.selectedTable.id);
const rows = await table.selectRecordsAsync();
const updates = [];
for (const row of rows.records) {
if (! row.getCellValue('Street')) {
const query = row.getCellValueAsString(cfg.selectedField);
const responseData = await lookupAddress(query);
if (responseData && responseData.addresses.length > 0) {
const {
number,
street,
city,
state,
postalCode
} = responseData.addresses[0];
updates.push({
id: row.id,
fields: {
'Street': `${number} ${street}`,
'City': city,
'State': state,
'Zip': postalCode
}
});
}
}
}
// Perform batch updates to minimize API calls
while (updates.length > 0) {
await table.updateRecordsAsync(updates.slice(0, 50));
updates.splice(0, 50); // Remove updated records from the array
}
This was a fun project! I hope others find this helpful. I'm looking for more script ideas, so feel free to comment below or send a message if you need help with any APIs or scripts.