Describe what you need in plain language and build it.
02
Field Agents
Run AI across all of your records.
03
HyperDB
Work from one trusted source at 100M-record scale.
04
App library
Package and share high-impact apps across the organization.
""",
)
@app.get("/solutions", response_class=HTMLResponse)
def solutions_page() -> HTMLResponse:
teams = [
("product", "Product teams", "Set your roadmap, act on feedback, and launch products customers love."),
("marketing", "Marketing teams", "Manage campaigns through every stage and report on outcomes."),
("operations", "Operations teams", "Connect initiatives and streamline critical workflows."),
("hr", "Human Resources teams", "Orchestrate hiring, onboarding, and employee programs."),
("sales", "Sales teams", "Keep account teams in sync and manage every opportunity."),
("finance", "Finance teams", "Connect planning, reporting, budgets, and approvals."),
("projects", "Project Management", "Manage strategic work around outcomes, not just tasks."),
]
cards = "".join(
f'↗
{name}
{copy}
Explore solutions →'
for slug, name, copy in teams
)
return public_shell(
"Solutions",
f"""
AIRTABLE SOLUTIONS
Solutions to empower every team
Customize the right workflows to fit your needs and help your team find success with Airtable.
No matter your workflow, you can build it in Airtable
Explore solutions for every type of team.
{cards}
Start building on Airtable today
Start building for freeContact sales""",
)
@app.get("/resources", response_class=HTMLResponse)
def resources_page() -> HTMLResponse:
resources = [
("Webinar", "Getting started in Airtable", "Learn the foundations for connected, AI-powered workflows."),
("Demo", "Automate your workflow with Airtable", "See how teams remove busywork and keep projects moving."),
("Demo", "Modern marketing teams run on Airtable", "Bring campaign planning, production, and reporting together."),
("Quick Read", "The next era of work", "Move from isolated automation to human-agent orchestration."),
("Guide", "Getting the most out of Omni", "Write better prompts and build complete workflows faster."),
("Customer Story", "Scale operations on shared data", "See how leading teams replace silos with one source of truth."),
]
cards = "".join(
f'{kind}
{name}
{copy}
Read more →'
for kind, name, copy in resources
)
return public_shell(
"Resource Center",
f"""
RESOURCES AND INSIGHTS
Resource Center
Stay one step ahead of the trends.
Demos, best practices, industry trends, and the latest ways teams are putting AI to work.
Build better processes, faster, with Airtable. Backed by advanced data security, no-code capabilities, and embedded AI, Airtable helps teams drive better results.
Trusted by 50% of the Fortune 1000
For technical or product support, please visit our Help Center.
""",
)
@app.get("/templates", response_class=HTMLResponse)
def templates_page(request: Request) -> HTMLResponse:
_, account = session(request, create=False)
if account and account.get("account_id"):
return shell("Templates", workspace_body(account, "templates"), app_mode=True, account=account)
use_cases = [("🗒️","Project Management"),("📣","Marketing"),("🚀","Product Management"),("🧵","Sales & CRM"),("👥","HR & Recruiting")]
case_cards = "".join(f'{icon}{label}' for icon,label in use_cases)
featured = "".join(
f'
"
)
plans = [("Free","For individuals or very small teams just getting started with Airtable","Free","Try for free",["500 AI credits per editor each month.","Unlimited bases","1,000 records per base"]),("Team","For teams building apps to collaborate on shared workflows","$20","Try for free",["15,000 AI credits per paid user each month.","50,000 records per base","25,000 automation runs"]),("Business","For teams and departments who need advanced features and basic administration","$45","Purchase now",["20,000 AI credits per paid user each month.","125,000 records per base","100,000 automation runs"]),("Enterprise Scale","For organizations looking to build scalable, flexible apps with powerful governance and administration","Custom","Contact Sales",["25,000 AI credits per paid user each month at list price.","500,000 records per base","500,000 automation runs"])]
cards = "".join(f'
{name}
{desc}
{price}{" USDper seat/month billed annually" if price.startswith("$") else ""}
""",
)
def auth_page(mode: str, message: str = "") -> HTMLResponse:
signup = mode == "signup"
email_label = "Work email" if signup else "Email"
email_placeholder = "name@company.com" if signup else "Email address"
second_fields = (
""
if signup
else ""
) + ""
legal = (
"By using Airtable, you agree to the Terms of Service and Privacy Policy."
if signup
else "By signing up, you agree to the Terms of Service and Privacy Policy."
)
promo = "" if signup else """"""
google_icon = """"""
apple_icon = """"""
chatgpt_icon = """"""
title = "Sign up" if signup else "Log in"
notice = f'
{html.escape(message)}
' if message else ""
return HTMLResponse(
f"""{title} · Airtable
Revoke every other local session while keeping this browser signed in.
' if security else f'')}'''
else:
descriptions = {"starred":"Bases you mark as important appear here.","shared":"Workspaces and bases shared with this local account.","workspaces":"Manage your deterministic local workspaces.","templates":"Create a base from a synthetic starter workflow.","marketplace":"Add local-only extensions to your workflow.","import":"Bring synthetic CSV data into a local base."}
controls = {"starred":base_cards or '
No starred bases yet.
',"shared":base_cards,"workspaces":f'
{base_cards}
',"templates":'',"marketplace":'
Local extensions
',"import":'
Import data
Choose a local file from the import dialog. Nothing is uploaded remotely.
'}
content = f'
{label}
{descriptions.get(page, "")}
{controls.get(page, "")}'
return f'
{side}{content}
'
@app.get("/app", response_class=HTMLResponse)
def workspace_home(request: Request):
token, account = session(request, create=False)
if not account or not account.get("account_id"):
return RedirectResponse("/login", 303)
return shell("Home", workspace_body(account, "home"), app_mode=True, account=account)
@app.get("/starred", response_class=HTMLResponse)
@app.get("/marketplace", response_class=HTMLResponse)
@app.get("/account", response_class=HTMLResponse)
@app.get("/import", response_class=HTMLResponse)
@app.get("/shared", response_class=HTMLResponse)
@app.get("/workspaces", response_class=HTMLResponse)
def app_section(request: Request, tab: str = "profile"):
page_name = request.url.path.removeprefix("/")
_, account = session(request, create=False)
if not account or not account.get("account_id"):
return RedirectResponse(f"/login?next=/{page_name}", 303)
return shell(page_name.title(), workspace_body(account, page_name, tab), app_mode=True, account=account)
def base_body(
base_id: str,
account: dict[str, Any],
query: str = "",
status: str = "",
sort: str = "",
mode: str = "data",
page: int = 1,
) -> str:
with connection() as conn:
require_resource_capability(conn, account, "base", base_id, "read")
base = conn.execute(
"SELECT * FROM at_bases WHERE id=? AND trashed=0", (base_id,)
).fetchone()
if base is None:
raise HTTPException(404, "Base not found")
table = conn.execute(
"SELECT * FROM at_tables WHERE base_id=? ORDER BY position LIMIT 1",
(base_id,),
).fetchone()
fields = conn.execute(
"SELECT * FROM at_fields WHERE table_id=? ORDER BY position", (table["id"],)
).fetchall()
views = conn.execute(
"SELECT * FROM at_views WHERE table_id=? ORDER BY rowid", (table["id"],)
).fetchall()
records = biz.list_records(
conn, table["id"], query=query, status=status, sort=sort
)
page_size = 25
total_records = len(records)
total_pages = max(1, (total_records + page_size - 1) // page_size)
page_index = min(max(1, page), total_pages)
page_start = (page_index - 1) * page_size
page_records = records[page_start : page_start + page_size]
field_names = [r["name"] for r in fields if not r["hidden"]][:7]
source_labels = {"Speaker": "Name", "Company": "Notes", "Track": "Assignee", "Status": "Status"}
headers = "".join(
f"
{html.escape(source_labels.get(n, n))}
"
for n in field_names
)
rows = ""
for idx, record in enumerate(page_records, page_start + 1):
cells = "".join(
f"
"""
stage = {
"data": data_stage,
"automations": automations_stage,
"interfaces": interfaces_stage,
"forms": forms_stage,
}.get(mode, data_stage)
labels = {"data": "Data", "automations": "Automations", "interfaces": "Interfaces", "forms": "Forms"}
nav = "".join(
f''
for key, label in labels.items()
)
omni_footer_title = (
"Automations catalog" if mode == "automations" else "Connect your favorite AI tool"
)
omni_footer_copy = (
"Easily set up automated workflows with Omni"
if mode == "automations"
else "Bring Airtable to where you work"
)
omni = f""""""
onboarding = (
"""
Welcome, Airtable
We’d love to show you around so you can see what Airtable is all about. It’ll only take a couple minutes.
"""
if base_id == "base-untitled" and mode == "data"
else ""
)
# Preserve the source-observed fixture label used by the private visual
# contracts, while making every user-created base visibly addressable by
# its persisted name.
displayed_base_name = (
"Untitled Base"
if base_id in {"base-conference", "base-untitled"}
else str(base["name"])
)
base_name = html.escape(displayed_base_name)
return f"""
"""
@app.get("/base/{base_id}", response_class=HTMLResponse)
def base_page(
base_id: str, request: Request, q: str = "", status: str = "", sort: str = "", page: int = 1
):
token, account = session(request, create=False)
if not account or not account.get("account_id"):
return RedirectResponse(f"/login?next=/base/{base_id}", 303)
return shell(
"Conference Tracker",
base_body(base_id, account, q, status, sort, page=page),
app_mode=True,
account=account,
)
@app.get("/base/{base_id}/{mode}", response_class=HTMLResponse)
def base_mode_page(
base_id: str,
mode: str,
request: Request,
q: str = "",
status: str = "",
sort: str = "",
page: int = 1,
):
if mode not in {"automations", "interfaces", "forms"}:
raise HTTPException(404, "Base mode unavailable")
_, account = session(request, create=False)
if not account or not account.get("account_id"):
return RedirectResponse(f"/login?next=/base/{base_id}/{mode}", 303)
return shell(
f"{mode.title()} · Conference Tracker",
base_body(base_id, account, q, status, sort, mode, page),
app_mode=True,
account=account,
)
@app.get("/base/{base_id}/record/{record_id}", response_class=HTMLResponse)
def record_detail_page(base_id: str, record_id: str, request: Request):
_, account = session(request, create=False)
if not account or not account.get("account_id"):
return RedirectResponse(f"/login?next=/base/{base_id}/record/{record_id}", 303)
with connection() as conn:
require_resource_capability(conn, account, "base", base_id, "read")
row = conn.execute(
"SELECT r.*,b.name AS base_name FROM at_records r "
"JOIN at_tables t ON t.id=r.table_id JOIN at_bases b ON b.id=t.base_id "
"WHERE r.id=? AND b.id=? AND r.trashed=0",
(record_id, base_id),
).fetchone()
if row is None:
raise HTTPException(404, "Record not found")
values = json.loads(row["values_json"] or "{}")
fields = "".join(
f"
{html.escape(str(key))}{html.escape(str(value or ''))}
"
for key, value in values.items()
)
title = str(values.get("Speaker") or values.get("Name") or "Untitled")
return shell(
f"{title} · {row['base_name']}",
f"← Back to base
RECORD DETAIL
{html.escape(title)}
{fields}
Status{html.escape(row['status'])}
Priority{html.escape(row['priority'])}
",
app_mode=True,
account=account,
)
@app.get("/share/{share_token}", response_class=HTMLResponse)
def public_share(share_token: str):
with connection() as conn:
base = conn.execute(
"SELECT * FROM at_bases WHERE share_token=? AND trashed=0", (share_token,)
).fetchone()
if base is None:
raise HTTPException(404, "This shared view is unavailable")
table = conn.execute(
"SELECT * FROM at_tables WHERE base_id=? LIMIT 1", (base["id"],)
).fetchone()
records = biz.list_records(conn, table["id"])
cards = "".join(
f"
{html.escape(str(r['values'].get('Speaker') or r['values'].get('Name')))}
{html.escape(r['status'])}"
for r in records
)
return shell(
f"Shared · {base['name']}",
f"
SHARED VIEW · READ ONLY
{html.escape(base['name'])}
This public link is served entirely by the local clone.
{cards}",
)
@app.get("/forms/{base_id}", response_class=HTMLResponse)
def form_view(base_id: str):
with connection() as conn:
base = form_capability(conn, base_id)
if base is None:
raise HTTPException(404, "Form unavailable")
return shell(
"Speaker nomination",
f"""
Speaker nomination
Suggest a speaker for {html.escape(base["name"])}. Required fields are marked.
""",
)
@app.get("/interface/{base_id}", response_class=HTMLResponse)
def interface_view(base_id: str, request: Request):
_, account = session(request, create=False)
if not account:
return RedirectResponse("/login", 303)
with connection() as conn:
require_resource_capability(conn, account, "base", base_id, "read")
base = conn.execute(
"SELECT name FROM at_bases WHERE id=?", (base_id,)
).fetchone()
table = conn.execute(
"SELECT id FROM at_tables WHERE base_id=? LIMIT 1", (base_id,)
).fetchone()
records = biz.list_records(conn, table["id"]) if table else []
confirmed = sum(1 for r in records if r["status"] == "Confirmed")
bars = "".join(
f"
{html.escape(str(r['values'].get('Speaker') or r['values'].get('Name')))}
"
for r in records[:8]
)
return shell(
"Conference dashboard",
f"""
Conference overview
Total speakers{len(records)}current recordsConfirmed{confirmed}ready to scheduleConfirmation rate{round(100 * confirmed / max(1, len(records)))}%local calculation
Speaker score
{bars}
""",
app_mode=True,
account=account,
)
@app.post("/api/auth/login")
async def api_login(request: Request):
data = await json_object(request)
token, _ = session(request)
try:
result = services()[1].sign_in(
token,
email=str(data.get("email", "")),
password=str(data.get("password", "")),
)
except Exception as exc:
raise payload_error(exc)
response = JSONResponse(
{"ok": True, "account": result["account"], "redirect": "/"}
)
set_session(response, result["session_token"], request)
return response
@app.post("/api/auth/signup")
async def api_signup(request: Request):
data = await json_object(request)
token, _ = session(request)
auth = services()[1]
try:
auth.start_registration(
token,
email=str(data.get("email", "")),
display_name=str(data.get("name", "")),
password=str(data.get("password", "")),
)
mail = auth.local_mail_for_session(token, purpose="registration")
except Exception as exc:
raise payload_error(exc)
response = JSONResponse(
{
"ok": True,
"verification_required": True,
"local_code": mail.get("verification_code") if mail else None,
"message": "Verification message created in the local inbox.",
}
)
set_session(response, token, request)
return response
@app.post("/api/auth/signup/verify")
async def api_signup_verify(request: Request):
data = await json_object(request)
token, _ = session(request)
auth = services()[1]
try:
auth.verify_registration_code(token, str(data.get("code", "")))
result = auth.complete_registration(token)
except Exception as exc:
raise payload_error(exc)
response = JSONResponse(
{"ok": True, "account": result["account"], "redirect": "/"}
)
set_session(response, result["session_token"], request)
return response
@app.post("/api/auth/logout")
def api_logout(request: Request):
token, _ = session(request, create=False)
services()[1].sign_out(token)
response = JSONResponse({"ok": True, "redirect": "/login"})
if token:
response.delete_cookie(cookie_name(request), path="/")
return response
@app.post("/api/auth/reset")
async def api_reset(request: Request):
data = await json_object(request)
token, _ = session(request)
auth = services()[1]
try:
result = auth.start_password_reset(token, email=str(data.get("email", "")))
mail = auth.local_mail_for_session(token, purpose="password-reset")
except Exception as exc:
raise payload_error(exc)
response = JSONResponse(
{
**result,
"ok": True,
"local_code": mail.get("verification_code") if mail else None,
}
)
set_session(response, token, request)
return response
@app.post("/api/auth/reset/complete")
async def api_reset_complete(request: Request):
data = await json_object(request)
token, _ = session(request)
auth = services()[1]
try:
auth.verify_password_reset_code(token, str(data.get("code", "")))
new_token = auth.complete_password_reset(
token, new_password=str(data.get("password", ""))
)
except Exception as exc:
raise payload_error(exc)
response = JSONResponse({"ok": True, "message": "Password updated"})
set_session(response, new_token, request)
return response
@app.post("/api/workspaces")
async def api_create_workspace(request: Request):
_, account = require_account(request)
data = await request.json()
try:
with connection() as conn:
result = biz.create_workspace(
conn, owner_of(account), str(data.get("name", ""))
)
except Exception as exc:
raise payload_error(exc)
return {"ok": True, "workspace": result}
@app.post("/api/bases")
async def api_create_base(request: Request):
_, account = require_account(request)
data = await request.json()
try:
with connection() as conn:
workspace_id = str(data.get("workspace_id") or "")
require_workspace_capability(conn, account, workspace_id, "schema")
result = biz.create_base(
conn,
owner_of(account),
workspace_id,
str(data.get("name", "")),
str(data.get("template")) if data.get("template") else None,
)
except Exception as exc:
raise payload_error(exc)
return {"ok": True, "base": result, "redirect": f"/base/{result['id']}"}
@app.get("/api/bases/{base_id}")
def api_base(base_id: str, request: Request):
_, account = require_account(request)
with connection() as conn:
require_resource_capability(conn, account, "base", base_id, "read")
base = conn.execute(
"SELECT * FROM at_bases WHERE id=? AND trashed=0", (base_id,)
).fetchone()
if base is None:
raise HTTPException(404, "Base not found")
tables = [
dict(r)
for r in conn.execute(
"SELECT * FROM at_tables WHERE base_id=? ORDER BY position", (base_id,)
)
]
for table in tables:
table["fields"] = [
dict(r)
for r in conn.execute(
"SELECT * FROM at_fields WHERE table_id=? ORDER BY position",
(table["id"],),
)
]
table["views"] = [
dict(r)
for r in conn.execute(
"SELECT * FROM at_views WHERE table_id=?", (table["id"],)
)
]
table["records"] = biz.list_records(conn, table["id"])
return {"ok": True, "base": dict(base), "tables": tables}
@app.post("/api/tables/{table_id}/records")
async def api_create_record(table_id: str, request: Request):
_, account = require_account(request)
data = await request.json()
try:
with connection() as conn:
require_resource_capability(conn, account, "table", table_id, "data")
result = biz.create_record(
conn,
owner_of(account),
table_id,
dict(data.get("values") or {}),
status=str(data.get("status") or "Planned"),
priority=str(data.get("priority") or "Medium"),
assignee=data.get("assignee"),
due_date=data.get("due_date"),
)
except Exception as exc:
raise payload_error(exc)
return {"ok": True, "record": result}
@app.patch("/api/records/{record_id}")
async def api_update_record(record_id: str, request: Request):
_, account = require_account(request)
data = await request.json()
try:
with connection() as conn:
require_resource_capability(conn, account, "record", record_id, "data")
result = biz.update_record(
conn,
owner_of(account),
record_id,
data,
data.get("expected_updated_at"),
)
except Exception as exc:
raise payload_error(exc)
return {"ok": True, "record": result}
@app.delete("/api/records/{record_id}")
def api_delete_record(record_id: str, request: Request):
_, account = require_account(request)
with connection() as conn:
require_resource_capability(conn, account, "record", record_id, "data")
row = conn.execute(
"SELECT table_id,values_json FROM at_records WHERE id=? AND trashed=0",
(record_id,),
).fetchone()
if row is None:
raise HTTPException(404, "Record not found")
changed = conn.execute(
"UPDATE at_records SET trashed=1,updated_at=? WHERE id=? AND trashed=0",
(biz.now(), record_id),
)
if changed.rowcount == 0:
raise HTTPException(404, "Record not found")
base_id = conn.execute(
"SELECT base_id FROM at_tables WHERE id=?", (row["table_id"],)
).fetchone()[0]
biz.log(
conn,
owner_of(account),
"moved record to trash",
base_id=base_id,
entity_type="record",
entity_id=record_id,
snapshot=json.loads(row["values_json"]),
)
return {"ok": True, "state": "trashed"}
@app.post("/api/records/bulk")
async def api_bulk_records(request: Request):
_, account = require_account(request)
data = await request.json()
ids = [str(x) for x in data.get("record_ids", [])]
if not ids or len(ids) > 100:
raise HTTPException(422, "Select 1 to 100 records")
action = str(data.get("action", ""))
placeholders = ",".join("?" for _ in ids)
with connection() as conn:
rows = conn.execute(
f"SELECT id FROM at_records WHERE id IN ({placeholders})", ids
).fetchall()
if len(rows) != len(set(ids)):
raise HTTPException(404, "Record not found")
workspace_ids = {
workspace_id_for(conn, "record", record_id) for record_id in ids
}
if None in workspace_ids or len(workspace_ids) != 1:
raise HTTPException(404, "Records not found")
require_workspace_capability(
conn, account, next(iter(workspace_ids)), "data"
)
if action == "confirm":
conn.execute(
f"UPDATE at_records SET status='Confirmed',updated_at=? WHERE id IN ({placeholders})",
(biz.now(), *ids),
)
elif action == "archive":
conn.execute(
f"UPDATE at_records SET archived=1,updated_at=? WHERE id IN ({placeholders})",
(biz.now(), *ids),
)
elif action == "trash":
conn.execute(
f"UPDATE at_records SET trashed=1,updated_at=? WHERE id IN ({placeholders})",
(biz.now(), *ids),
)
else:
raise HTTPException(422, "Unsupported bulk action")
changed = conn.execute(
f"SELECT COUNT(*) FROM at_records WHERE id IN ({placeholders})", ids
).fetchone()[0]
biz.log(
conn,
owner_of(account),
f"bulk {action}",
entity_type="records",
snapshot={"count": changed},
)
return {"ok": True, "changed": changed, "action": action}
@app.post("/api/tables/{table_id}/fields")
async def api_create_field(table_id: str, request: Request):
_, account = require_account(request)
data = await request.json()
name = " ".join(str(data.get("name", "")).split())
typ = str(data.get("type", "singleLineText"))
allowed = {
"singleLineText",
"longText",
"number",
"singleSelect",
"multipleSelect",
"date",
"checkbox",
"email",
"url",
"attachment",
"collaborator",
"linkedRecord",
"lookup",
"rollup",
"formula",
}
if not name or typ not in allowed:
raise HTTPException(422, "Choose a valid field name and type")
with connection() as conn:
require_resource_capability(conn, account, "table", table_id, "schema")
pos = conn.execute(
"SELECT COALESCE(MAX(position),-1)+1 FROM at_fields WHERE table_id=?",
(table_id,),
).fetchone()[0]
fid = biz.token("fld")
conn.execute(
"INSERT INTO at_fields VALUES (?,?,?,?,?,?,0)",
(fid, table_id, name, typ, json.dumps(data.get("options") or {}), pos),
)
base = conn.execute(
"SELECT base_id FROM at_tables WHERE id=?", (table_id,)
).fetchone()
if not base:
raise HTTPException(404, "Table not found")
biz.log(
conn,
owner_of(account),
"created field",
base_id=base[0],
entity_type="field",
entity_id=fid,
snapshot={"name": name, "type": typ},
)
return {"ok": True, "field": {"id": fid, "name": name, "type": typ}}
@app.post("/api/tables/{table_id}/views")
async def api_create_view(table_id: str, request: Request):
_, account = require_account(request)
data = await request.json()
typ = str(data.get("type", "grid"))
name = str(data.get("name", f"{typ.title()} view"))
if typ not in {"grid", "gallery", "kanban", "calendar", "form"}:
raise HTTPException(422, "Unsupported view type")
with connection() as conn:
require_resource_capability(conn, account, "table", table_id, "schema")
vid = biz.token("view")
conn.execute(
"INSERT INTO at_views VALUES (?,?,?,?,?,?)",
(
vid,
table_id,
name,
typ,
json.dumps(data.get("config") or {}),
int(bool(data.get("favorite"))),
),
)
return {"ok": True, "view": {"id": vid, "name": name, "type": typ}}
@app.post("/api/records/{record_id}/comments")
async def api_comment(record_id: str, request: Request):
_, account = require_account(request)
data = await request.json()
body = " ".join(str(data.get("body", "")).split())
if not 1 <= len(body) <= 2000:
raise HTTPException(422, "Comment must contain 1 to 2000 characters")
with connection() as conn:
require_resource_capability(conn, account, "record", record_id, "comment")
if (
conn.execute("SELECT 1 FROM at_records WHERE id=?", (record_id,)).fetchone()
is None
):
raise HTTPException(404, "Record not found")
cid = biz.token("comment")
conn.execute(
"INSERT INTO at_comments VALUES (?,?,?,?,?)",
(cid, record_id, owner_of(account), body, biz.now()),
)
if "@" in body:
conn.execute(
"INSERT INTO at_notifications VALUES (?,?,?,?,?)",
(
biz.token("note"),
"seed:member",
f"Mention in a comment: {body[:120]}",
None,
biz.now(),
),
)
return {
"ok": True,
"comment": {"id": cid, "body": body},
"mention_notified": "@" in body,
}
@app.post("/api/workspaces/{workspace_id}/invite")
async def api_invite(workspace_id: str, request: Request):
_, account = require_account(request)
data = await request.json()
email_value = str(data.get("email", "")).strip().casefold()
role = str(data.get("role", "editor"))
if "@" not in email_value or role not in {
"owner",
"creator",
"editor",
"commenter",
"read_only",
}:
raise HTTPException(422, "Enter a valid email and role")
with connection() as conn:
actor_role = require_workspace_capability(
conn, account, workspace_id, "manage"
)
if role == "owner" and actor_role != "owner":
raise HTTPException(403, "Only the workspace owner can grant owner access")
iid = biz.token("invite")
try:
conn.execute(
"INSERT INTO at_collaborators VALUES (?,?,?,?,?,?)",
(iid, workspace_id, email_value, role, "invited-local", biz.now()),
)
except sqlite3.IntegrityError:
conn.execute(
"UPDATE at_collaborators SET role=?,status='invited-local' WHERE workspace_id=? AND email=?",
(role, workspace_id, email_value),
)
biz.log(
conn,
owner_of(account),
"invited collaborator (local delivery)",
entity_type="collaborator",
entity_id=iid,
snapshot={"role": role},
)
return {
"ok": True,
"status": "invited-local",
"delivery": "local-outbox",
"role": role,
}
@app.post("/api/bases/{base_id}/share")
def api_share(base_id: str, request: Request):
_, account = require_account(request)
with connection() as conn:
require_resource_capability(conn, account, "base", base_id, "manage")
base = conn.execute(
"SELECT * FROM at_bases WHERE id=?", (base_id,)
).fetchone()
if base is None:
raise HTTPException(403, "Base unavailable")
share_token = base["share_token"] or biz.token("share")
conn.execute(
"UPDATE at_bases SET share_token=?,updated_at=? WHERE id=?",
(share_token, biz.now(), base_id),
)
return {"ok": True, "share_url": f"/share/{share_token}", "read_only": True}
@app.post("/api/bases/{base_id}/automations")
async def api_automation(base_id: str, request: Request):
_, account = require_account(request)
data = await request.json()
action = str(data.get("action", "create"))
with connection() as conn:
require_resource_capability(conn, account, "base", base_id, "manage")
if action == "run":
aid = str(data.get("automation_id") or "auto-confirm")
row = conn.execute(
"SELECT * FROM at_automations WHERE id=? AND base_id=?", (aid, base_id)
).fetchone()
if row is None:
raise HTTPException(404, "Automation not found")
conn.execute(
"UPDATE at_automations SET run_count=run_count+1,last_status='Succeeded locally' WHERE id=?",
(aid,),
)
conn.execute(
"INSERT INTO at_notifications VALUES (?,?,?,?,?)",
(
biz.token("note"),
owner_of(account),
f"Automation '{row['name']}' completed locally",
None,
biz.now(),
),
)
result = {"id": aid, "status": "Succeeded locally"}
else:
name = str(data.get("name", "Untitled automation"))
aid = biz.token("auto")
conn.execute(
"INSERT INTO at_automations VALUES (?,?,?,?,?,?,?,?)",
(
aid,
base_id,
name,
str(data.get("trigger", "record_created")),
str(data.get("then", "create_notification")),
int(bool(data.get("enabled", True))),
0,
"Never run",
),
)
result = {
"id": aid,
"status": "enabled" if data.get("enabled", True) else "disabled",
}
return {"ok": True, "automation": result, "sandbox": True}
@app.post("/api/bases/{base_id}/integrations")
async def api_integration(base_id: str, request: Request):
_, account = require_account(request)
data = await request.json()
provider = str(data.get("provider", "Local webhook"))
with connection() as conn:
require_resource_capability(conn, account, "base", base_id, "manage")
iid = biz.token("int")
conn.execute(
"INSERT INTO at_integrations VALUES (?,?,?,?,?)",
(iid, base_id, provider, 1, json.dumps({"mode": "offline-simulation"})),
)
return {
"ok": True,
"integration": {"id": iid, "provider": provider, "mode": "offline-simulation"},
}
@app.post("/api/tables/{table_id}/import")
async def api_import(table_id: str, request: Request):
_, account = require_account(request)
text = (await request.body()).decode("utf-8", "replace")
try:
with connection() as conn:
require_resource_capability(conn, account, "table", table_id, "data")
result = biz.csv_import(conn, owner_of(account), table_id, text)
except Exception as exc:
raise payload_error(exc)
return {"ok": True, **result}
@app.get("/api/tables/{table_id}/export")
def api_export(table_id: str, request: Request):
_, account = require_account(request)
with connection() as conn:
require_resource_capability(conn, account, "table", table_id, "read")
text = biz.csv_export(conn, table_id)
return PlainTextResponse(
text,
media_type="text/csv",
headers={"Content-Disposition": "attachment; filename=airtable-export.csv"},
)
@app.post("/api/records/{record_id}/attachments")
async def api_attachment(
record_id: str, request: Request, file: UploadFile = File(...)
):
_, account = require_account(request)
data = await file.read(5_000_001)
if len(data) > 5_000_000:
raise HTTPException(413, "Attachment exceeds the 5 MB offline limit")
safe = (
"".join(
c for c in (file.filename or "attachment.bin") if c.isalnum() or c in ".-_ "
)[:100]
or "attachment.bin"
)
aid = biz.token("attachment")
target = VOLUME_ROOT / "attachments" / f"{aid}-{safe}"
target.parent.mkdir(parents=True, exist_ok=True)
with connection() as conn:
require_resource_capability(conn, account, "record", record_id, "data")
target.write_bytes(data)
conn.execute(
"INSERT INTO at_attachments VALUES (?,?,?,?,?,?,?)",
(
aid,
record_id,
safe,
file.content_type or "application/octet-stream",
len(data),
str(target),
biz.now(),
),
)
biz.log(
conn,
owner_of(account),
"attached file",
entity_type="attachment",
entity_id=aid,
snapshot={"filename": safe, "size": len(data)},
)
return {
"ok": True,
"attachment": {
"id": aid,
"filename": safe,
"size": len(data),
"download": f"/api/attachments/{aid}",
},
}
@app.get("/api/attachments/{attachment_id}")
def api_attachment_download(attachment_id: str, request: Request):
_, account = require_account(request)
with connection() as conn:
require_resource_capability(
conn, account, "attachment", attachment_id, "read"
)
row = conn.execute(
"SELECT * FROM at_attachments WHERE id=?", (attachment_id,)
).fetchone()
if row is None or not Path(row["local_path"]).is_file():
raise HTTPException(404, "Attachment unavailable")
return FileResponse(
row["local_path"], media_type=row["content_type"], filename=row["filename"]
)
@app.post("/api/forms/{base_id}/submit")
async def api_form_submit(base_id: str, request: Request):
data = await json_object(request)
name = str(data.get("Speaker", "")).strip()
email_value = str(data.get("Email", "")).strip()
if not name or "@" not in email_value:
raise HTTPException(422, "Speaker name and a valid email are required")
with connection() as conn:
if form_capability(conn, base_id) is None:
raise HTTPException(404, "Form unavailable")
table = conn.execute(
"SELECT id FROM at_tables WHERE base_id=? LIMIT 1", (base_id,)
).fetchone()
if table is None:
raise HTTPException(404, "Form unavailable")
sid = biz.token("submission")
conn.execute(
"INSERT INTO at_form_submissions VALUES (?,?,?,?)",
(sid, base_id, json.dumps(data), biz.now()),
)
record = biz.create_record(
conn, "public-form", table[0], data, status="Invited"
)
return {
"ok": True,
"submission_id": sid,
"record_id": record["id"],
"message": "Thanks — your response was submitted.",
}
@app.get("/api/history/{base_id}")
def api_history(base_id: str, request: Request):
_, account = require_account(request)
with connection() as conn:
require_resource_capability(conn, account, "base", base_id, "read")
rows = [
dict(r)
for r in conn.execute(
"SELECT * FROM at_history WHERE base_id=? ORDER BY id DESC LIMIT 50",
(base_id,),
)
]
return {"ok": True, "history": rows}
@app.post("/api/history/{history_id}/undo")
def api_undo(history_id: int, request: Request):
_, account = require_account(request)
with connection() as conn:
require_resource_capability(conn, account, "history", history_id, "data")
event = conn.execute(
"SELECT * FROM at_history WHERE id=?", (history_id,)
).fetchone()
if event is None:
raise HTTPException(404, "History entry not found")
snapshot = json.loads(event["snapshot_json"])
if event["entity_type"] == "record" and event["action"] in {
"updated record",
"moved record to trash",
}:
if event["action"] == "moved record to trash":
conn.execute(
"UPDATE at_records SET trashed=0,updated_at=? WHERE id=?",
(biz.now(), event["entity_id"]),
)
else:
conn.execute(
"UPDATE at_records SET values_json=?,status=?,priority=?,assignee=?,due_date=?,updated_at=? WHERE id=?",
(
snapshot["values_json"],
snapshot["status"],
snapshot["priority"],
snapshot["assignee"],
snapshot["due_date"],
biz.now(),
event["entity_id"],
),
)
else:
raise HTTPException(422, "This history entry cannot be undone")
biz.log(
conn,
owner_of(account),
"undo",
base_id=event["base_id"],
entity_type=event["entity_type"],
entity_id=event["entity_id"],
snapshot={"source_history_id": history_id},
)
return {"ok": True, "message": "Change undone"}
@app.post("/api/bases/{base_id}/lifecycle")
async def api_base_lifecycle(base_id: str, request: Request):
_, account = require_account(request)
data = await request.json()
action = str(data.get("action", ""))
states = {
"archive": (1, 0),
"restore": (0, 0),
"trash": (0, 1),
"restore-trash": (0, 0),
}
if action == "permanent-delete":
with connection() as conn:
require_resource_capability(conn, account, "base", base_id, "manage")
base = conn.execute(
"SELECT * FROM at_bases WHERE id=? AND trashed=1", (base_id,)
).fetchone()
if base is None:
raise HTTPException(
409, "Move the base to trash before permanent deletion"
)
conn.execute("DELETE FROM at_bases WHERE id=?", (base_id,))
return {"ok": True, "state": "permanently-deleted"}
if action not in states:
raise HTTPException(422, "Unsupported lifecycle action")
archived, trashed = states[action]
with connection() as conn:
require_resource_capability(conn, account, "base", base_id, "manage")
changed = conn.execute(
"UPDATE at_bases SET archived=?,trashed=?,updated_at=? WHERE id=?",
(archived, trashed, biz.now(), base_id),
).rowcount
if not changed:
raise HTTPException(404, "Base not found")
biz.log(
conn,
owner_of(account),
action,
base_id=base_id,
entity_type="base",
entity_id=base_id,
)
return {"ok": True, "state": action}
@app.get("/api/notifications")
def api_notifications(request: Request):
_, account = require_account(request)
with connection() as conn:
rows = [
dict(r)
for r in conn.execute(
"SELECT * FROM at_notifications WHERE owner=? ORDER BY created_at DESC",
(owner_of(account),),
)
]
return {"ok": True, "notifications": rows}
@app.post("/api/preferences")
async def api_preferences(request: Request):
_, account = require_account(request)
data = await request.json()
owner = owner_of(account)
with connection() as conn:
conn.execute(
"INSERT INTO at_preferences VALUES (?,?,?) ON CONFLICT(owner) DO UPDATE SET values_json=excluded.values_json,updated_at=excluded.updated_at",
(owner, json.dumps(data), biz.now()),
)
return {"ok": True, "preferences": data}
@app.post("/api/security/revoke-sessions")
def api_revoke_sessions(request: Request):
token, account = require_account(request)
auth = services()[1]
with auth.connect() as conn:
digest = auth._session_row(conn, token)["session_digest"]
conn.execute(
"UPDATE local_auth_sessions SET revoked_at=? WHERE account_id=? AND session_digest<>? AND revoked_at IS NULL",
(biz.now(), account["account_id"], digest),
)
changed = conn.total_changes
return {"ok": True, "revoked": changed, "current_session_preserved": True}
@app.delete("/api/account")
def api_delete_account(request: Request):
token, account = require_account(request)
owner = owner_of(account)
auth = services()[1]
with auth.connect() as conn:
owned = conn.execute(
"SELECT COUNT(*) FROM at_workspaces WHERE owner=? AND archived=0", (owner,)
).fetchone()[0]
if owned:
raise HTTPException(
409, "Archive or transfer owned workspaces before deleting the account"
)
conn.execute(
"DELETE FROM local_auth_accounts WHERE account_id=?",
(account["account_id"],),
)
return {"ok": True, "state": "deleted"}
@app.get("/api/formula")
def api_formula(
request: Request, expression: str, speaker: str = "Ada", company: str = "Northstar"
):
require_account(request)
try:
value = biz.evaluate_formula(
expression, {"Speaker": speaker, "Company": company, "Score": 9}
)
except Exception as exc:
raise payload_error(exc)
return {"ok": True, "value": value, "sandbox": True}
@app.exception_handler(HTTPException)
def http_error(request: Request, exc: HTTPException):
if request.url.path.startswith("/api/"):
return JSONResponse(
{
"ok": False,
"error": exc.detail,
"retryable": exc.status_code in {409, 429, 500, 503},
},
status_code=exc.status_code,
)
response = shell(
"Something went wrong",
f"