Snowflake External Functions for Web Search: Five Routes and When Each Fits
.png)

TLDR: To call a web search API from Snowflake, you rarely need an external function anymore. An external access integration lets a Python UDF or stored procedure call the API directly, with the key held in a Snowflake secret. Use a UDF for small lookups, a scheduled procedure that fills a cache table for anything recurring, and the built-in Cortex Agents web search only for conversational questions.
Five ways to get web results into Snowflake
External functions were Snowflake's original way to reach outside services, which is why teams still search for them. In November 2026 there are five routes, and one property decides most designs: whether SQL can call the route once per row.
| Route | How it reaches the search API | Callable per row in a SELECT | Who retries | Fits |
|---|---|---|---|---|
| Cortex Agents web search tool | Snowflake calls the Brave Search API for the agent | No, it is an agent tool | Snowflake | Ad hoc questions in an agent or Snowflake CoWork |
| Marketplace app or vendor recipe | Vendor code in your account, through an integration you approve | Only if it ships a function rather than a procedure | Vendor code | Fast setup with one provider |
| External function | Snowflake, then a cloud API gateway, then your function (for example AWS Lambda), then the search API | Yes | Snowflake, per batch | Teams that already run a gateway and serverless functions |
| External access with a Python UDF | The handler calls the API directly | Yes | Your code | Small, ad hoc lookups |
| External access with a procedure and a cache table | A scheduled job calls the API and writes a table | SQL reads the table | Your code | Anything recurring or larger than a few hundred rows |
The built-in tool is the least work when it fits. Snowflake's agent documentation says Cortex Agents use the Brave Web Search API, that queries and results cross the public internet, and that Snowflake has zero data retention with Brave. An ACCOUNTADMIN enables it in Snowsight under AI & ML, Agents, Settings, then adds it to each agent. Snowflake says it can add cost beyond orchestration, with rates in its Service Consumption Table. It is a tool the agent chooses to call, so it cannot fill a column for every row.
Before installing a vendor package for enrichment, check whether it ships a procedure or a function. Exa's Snowflake guide creates EXA_SEARCH as a stored procedure, and Tavily's native app exposes TAVILY_WEB_SEARCH as a procedure you CALL. A procedure runs once per call: fine for an agent tool, wrong for a SELECT over 50,000 accounts. Exa's guide covers whole tables with a separate thread-pool procedure on a scheduled task, much like the cache pattern below. Nimble's Cortex Agents guide defines NIMBLE_SEARCH as a scalar Python UDF that returns VARIANT, so it can run per row.
Why an external function is rarely the right starting point
An external function holds no code of its own. Snowflake sends batches of rows to a proxy service such as Amazon API Gateway, which relays them to a remote service you host, such as a Lambda function. The request body uses Snowflake's own format: a data array in which the first column of every row is its row number, and the response must return the same row numbers. None of the search APIs named here accepts that shape, so you also run a function that unpacks each batch, calls the API per row, and packs the answers back.
Two behaviors matter when every call costs money:
- Repeated rows. Snowflake retries batches after transport errors, 429s and 5XX responses, up to a retry timeout you cannot configure, and its external function best practices warn that the remote service may see a row more than once. Each repeat is another billed search unless your function skips batch IDs it has already answered.
- Overhead. Snowflake says external functions carry more overhead than internal UDFs and usually run more slowly, and it caps each batch response at 10 MB.
External functions still fit teams that already route outbound traffic through API Gateway, or that want the remote code in Go or C#.
An external access integration removes the middle tier. You declare the host the code may reach in a network rule, store the API key in a secret, bundle both into an integration, and reference it from a Python, Java or Scala UDF or procedure. Calls to any host outside the rule are denied. Retries and pacing move into your code. Check two constraints first. Snowflake does not enable external access for trial accounts by default, per its limitations page, and private connectivity instead of the public internet requires Business Critical Edition or higher.
Set up external access for the You.com Web Search API
The You.com Web Search API is a single endpoint, POST https://ydc-index.io/v1/search, authenticated with an X-API-Key header. Ranked results come back under results.web, per the API reference. The You.com docs have no Snowflake-specific integration as of November 2026, so external access is the route. One network rule for ydc-index.io also covers the Contents API. Add api.you.com to the rule only if you call the Answer or Research APIs.
-- Run as ACCOUNTADMIN, or a role with CREATE INTEGRATION on the account
-- and CREATE NETWORK RULE / CREATE SECRET on the schema.
CREATE OR REPLACE NETWORK RULE enrich.web.ydc_search_rule
MODE = EGRESS
TYPE = HOST_PORT
VALUE_LIST = ('ydc-index.io'); -- port 443 is the default
CREATE OR REPLACE SECRET enrich.web.ydc_api_key
TYPE = GENERIC_STRING
SECRET_STRING = '<your You.com API key>';
CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION ydc_search_eai
ALLOWED_NETWORK_RULES = (enrich.web.ydc_search_rule)
ALLOWED_AUTHENTICATION_SECRETS = (enrich.web.ydc_api_key)
ENABLED = TRUE;
-- The role that creates the function needs USAGE on the integration
-- and READ on the secret, plus USAGE on the secret's database and schema.
GRANT USAGE ON INTEGRATION ydc_search_eai TO ROLE enrich_dev;
GRANT USAGE ON DATABASE enrich TO ROLE enrich_dev;
GRANT USAGE ON SCHEMA enrich.web TO ROLE enrich_dev;
GRANT READ ON SECRET enrich.web.ydc_api_key TO ROLE enrich_dev;
Only roles with READ on the secret can build a function that uses it, so your security team has one object to audit. It also has one switch: set the integration's ENABLED to false and every dependent handler loses network access.
A scalar UDF for small lookups
For a one-off question over a few hundred rows, a scalar UDF is the shortest path. This one returns a VARIANT that SQL can flatten into rows.
CREATE OR REPLACE FUNCTION enrich.web.ydc_search(query STRING, max_results INT, freshness STRING)
RETURNS VARIANT
LANGUAGE PYTHON
RUNTIME_VERSION = '3.12'
PACKAGES = ('requests')
HANDLER = 'search'
EXTERNAL_ACCESS_INTEGRATIONS = (ydc_search_eai)
SECRETS = ('ydc' = enrich.web.ydc_api_key)
AS
$$
import datetime
import time
import _snowflake
import requests
URL = "https://ydc-index.io/v1/search"
RETRYABLE = {429, 500, 502, 503, 504}
# One Session per handler instance, so rows reuse TCP connections.
SESSION = requests.Session()
SESSION.headers.update({"Content-Type": "application/json",
"User-Agent": "snowflake-enrichment/1.0"})
def web_results(r):
"""results.web from a 200 response, or None when the body is not the documented JSON."""
try:
web = (r.json().get("results") or {}).get("web") or []
return [{"url": w.get("url"), "title": w.get("title"),
"description": w.get("description"), "page_age": w.get("page_age")} for w in web]
except (ValueError, AttributeError):
return None
def search(query, max_results, freshness):
if query is None or not query.strip():
return {"ok": False, "error": "empty_query"}
body = {"query": query.strip(), "count": max(1, min(int(max_results or 5), 100))}
if freshness:
body["freshness"] = freshness
headers = {"X-API-Key": _snowflake.get_generic_secret_string("ydc")}
error = "not_attempted"
for attempt in range(4):
wait = 2 ** attempt
try:
r = SESSION.post(URL, json=body, headers=headers, timeout=20)
except requests.RequestException as exc:
error = type(exc).__name__ # never the message: it can echo the request
else:
if r.status_code == 200:
results = web_results(r)
if results is not None:
return {"ok": True,
"fetched_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"results": results}
error = "bad_response" # a gateway page served as 200: retry like a 5XX
else:
error = "http_%d" % r.status_code
if r.status_code not in RETRYABLE:
break # 401, 402, 403, 422: retrying will not help
retry_after = r.headers.get("Retry-After", "")
if retry_after.isdigit():
wait = int(retry_after)
if attempt < 3:
time.sleep(min(wait, 8))
return {"ok": False, "error": error}
$$;
Five choices in that function matter:
- Failures are rows, not exceptions. An exception can fail the whole query after you have paid for every row that succeeded. That includes a 200 whose body is not the documented JSON.
- It retries only what can recover. 429 and 5XX responses, and a 200 that is not JSON, get up to four attempts, honoring
Retry-Afteras the rate limit docs recommend. A 401, 402, 403 or 422 fails at once. - No exception text. Errors hold a status code or class name, so the key can never surface in a result.
- One HTTP session per instance. Snowflake limits the connections a UDF can open and recommends reusing a
requestsSession, because exhausting them surfaces as "Cannot assign requested address". - It records its own
fetched_at. The API documentspage_ageas optional and describes it as the age of the result, not your fetch time. In our test on 12 November 2026, 51 of the top 200 web results (26%) from 20 enrichment-style queries had nopage_ageat all.
Call it on a sample first. Every row is one billable search, and OUTER => TRUE keeps the rows whose call failed, so you can see them.
-- Each row is one billable call. Start with a sample, never a full table.
WITH hits AS (
SELECT account_id,
company_name,
enrich.web.ydc_search(company_name || ' headquarters', 3, NULL) AS res
FROM crm.accounts SAMPLE (20 ROWS)
)
SELECT h.account_id,
h.company_name,
h.res:ok::BOOLEAN AS ok,
h.res:error::STRING AS error,
r.value:url::STRING AS url,
r.value:title::STRING AS title
FROM hits h,
LATERAL FLATTEN(input => h.res:results, OUTER => TRUE) r;
A vectorized UDF does not help here. The endpoint takes one query per request, and Snowflake's vectorized UDF documentation gives each batch, which can hold a few thousand rows, 180 seconds. At one second per search, run one after another, 1,000 rows would overrun it.
What per-row calls cost
A UDF has no memory, so every query that touches it pays again, including each refresh of a view built on it. The Web Search API costs $5.00 per 1,000 calls as of November 2026, with up to 100 results per call, per the billing page, and self-serve accounts default to 10 requests per second. Here is the arithmetic for a 100,000-row accounts table with one search per account:
| Pattern | Calls per month | Search cost per month | Time per full pass |
|---|---|---|---|
| UDF inside a view that a dashboard refreshes 30 times a month | 3,000,000 | $15,000 | At least 10,000 seconds (2.8 hours) per refresh at 10 requests per second |
| UDF run once into a table with CREATE TABLE AS SELECT | 100,000 | $500 | 2.8 hours, once |
| Cache table, 30-day TTL, daily task of about 3,334 queries | About 100,000 | About $500 | About 7 minutes a day at 8 requests per second |
| Cache table, 90-day TTL for facts that rarely change | About 33,334 | About $167 | About 2.3 minutes a day |
Repetition is the expensive part, and most of it buys nothing new. On 12 November 2026 we ran 20 enrichment-style queries (headquarters, executives, funding news) twice, about two minutes apart, through You.com's keyless MCP endpoint, which returns the same results.web shape as the API. The keyless tier refused three queries on the second pass. The 17 that completed both passes returned identical top-10 URL lists in the same order. The interval is short, so it shows that a repeat call pays for the same answer, not how long results stay stable.
Two other costs are smaller but real:
- Warehouse time. The warehouse bills while handlers wait on the network. A Gen1 X-Small uses 1 credit per hour, billed per second with a 60-second minimum, according to the warehouse documentation, so the 7-minute daily task above uses about 0.12 credits plus any idle time before the warehouse suspends. A larger warehouse runs more handler instances in parallel, which raises your request rate but not your rate limit. Past 10 requests per second you collect 429s and pay for handlers that sleep.
- Egress. Snowflake bills request payloads for external access as data transfer, which appears as
EXTERNAL_ACCESSin theDATA_TRANSFER_HISTORYview. A request is a few hundred bytes, so this stays small.
The production pattern: a cache table filled on a schedule
For anything recurring, move the calls into a stored procedure that a task runs on a schedule. Reports join to a table, so a refresh costs nothing extra.
CREATE TABLE IF NOT EXISTS enrich.web.search_cache (
query STRING,
response VARIANT,
ok BOOLEAN,
fetched_at TIMESTAMP_NTZ -- UTC; your own clock, not the result's page_age
);
-- The queue is a view you own: one column named QUERY, built with the same
-- expression your reports use to join back to the cache.
CREATE OR REPLACE VIEW enrich.web.search_queue AS
SELECT DISTINCT TRIM(company_name) || ' headquarters' AS query
FROM crm.accounts
WHERE company_name IS NOT NULL;
CREATE OR REPLACE PROCEDURE enrich.web.refresh_search_cache(ttl_days INT, max_calls INT, rps FLOAT)
RETURNS STRING
LANGUAGE PYTHON
RUNTIME_VERSION = '3.12'
PACKAGES = ('snowflake-snowpark-python', 'requests')
HANDLER = 'run'
EXTERNAL_ACCESS_INTEGRATIONS = (ydc_search_eai)
SECRETS = ('ydc' = enrich.web.ydc_api_key)
AS
$$
import datetime
import json
import threading
import time
from concurrent.futures import ThreadPoolExecutor
import _snowflake
import requests
URL = "https://ydc-index.io/v1/search"
RETRYABLE = {429, 500, 502, 503, 504}
class Pacer:
"""Spaces request starts at most `rps` per second across all worker threads."""
def __init__(self, rps):
self.gap, self.next_at, self.lock = 1.0 / max(float(rps), 0.1), time.monotonic(), threading.Lock()
def wait(self):
with self.lock:
now = time.monotonic()
start = max(now, self.next_at)
self.next_at = start + self.gap
time.sleep(max(0.0, start - now))
def web_results(r):
"""results.web from a 200 response, or None when the body is not the documented JSON."""
try:
web = (r.json().get("results") or {}).get("web") or []
return [{k: w.get(k) for k in ("url", "title", "description", "page_age")} for w in web]
except (ValueError, AttributeError):
return None
def call(session, key, pacer, query):
error = "not_attempted"
for attempt in range(4):
pacer.wait()
wait = 2 ** attempt
try:
r = session.post(URL, json={"query": query, "count": 5},
headers={"X-API-Key": key}, timeout=20)
except requests.RequestException as exc:
error = type(exc).__name__
else:
if r.status_code == 200:
keep = web_results(r)
if keep is not None:
return query, {"results": keep}, True
error = "bad_response"
else:
error = "http_%d" % r.status_code
if r.status_code not in RETRYABLE:
break
ra = r.headers.get("Retry-After", "")
if ra.isdigit():
wait = int(ra)
if attempt < 3:
time.sleep(min(wait, 30))
return query, {"error": error}, False
def run(snowpark, ttl_days, max_calls, rps):
todo = [row[0] for row in snowpark.sql(
"""SELECT q.query
FROM enrich.web.search_queue q
LEFT JOIN enrich.web.search_cache c ON c.query = q.query
WHERE q.query <> ''
AND (c.query IS NULL OR NOT c.ok
OR c.fetched_at < DATEADD(day, -%d, SYSDATE()))
ORDER BY c.fetched_at NULLS FIRST
LIMIT %d""" % (int(ttl_days), int(max_calls))).collect()]
if not todo:
return "nothing to refresh"
key = _snowflake.get_generic_secret_string("ydc")
workers = max(1, min(16, int(rps * 2)))
pacer, http = Pacer(float(rps)), requests.Session()
http.mount("https://", requests.adapters.HTTPAdapter(pool_maxsize=workers))
def one(q):
try:
return call(http, key, pacer, q)
except Exception as exc: # one bad row must not discard a paid batch
return q, {"error": type(exc).__name__}, False
with ThreadPoolExecutor(max_workers=workers) as pool:
done = list(pool.map(one, todo))
now = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None, microsecond=0)
rows = [(q, json.dumps(resp), ok, now) for q, resp, ok in done]
snowpark.create_dataframe(rows, schema=["QUERY", "RESPONSE_JSON", "OK", "FETCHED_AT"]) \
.write.mode("overwrite").save_as_table("enrich.web.search_cache_stage", table_type="temporary")
# A failed refresh never overwrites a good cached answer.
snowpark.sql(
"""MERGE INTO enrich.web.search_cache c
USING (SELECT query, PARSE_JSON(response_json) AS response, ok, fetched_at
FROM enrich.web.search_cache_stage) s
ON c.query = s.query
WHEN MATCHED AND (s.ok OR NOT c.ok) THEN UPDATE SET
response = s.response, ok = s.ok, fetched_at = s.fetched_at
WHEN NOT MATCHED THEN INSERT (query, response, ok, fetched_at)
VALUES (s.query, s.response, s.ok, s.fetched_at)""").collect()
good = sum(1 for _, _, ok in done if ok)
return "called %d queries: %d ok, %d failed" % (len(done), good, len(done) - good)
$$;
CREATE OR REPLACE TASK enrich.web.refresh_search_cache_daily
WAREHOUSE = enrich_xs
SCHEDULE = 'USING CRON 0 5 * * * UTC'
AS
CALL enrich.web.refresh_search_cache(30, 5000, 8);
ALTER TASK enrich.web.refresh_search_cache_daily RESUME; -- tasks are created suspended
The procedure applies four controls that a per-row UDF cannot:
- Deduplication. The queue is a
DISTINCTview, so 40 accounts named "Acme Corp" cost one search. - A hard ceiling. It refreshes only queries that are missing, failed, or older than
ttl_days, oldest first, capped atmax_calls. A cap of 5,000 queries keeps a day's successful searches at $25 or less. - One pacer for the whole job. All worker threads in the procedure share a single pacer, set to 8 requests per second. That stays under the 10-per-second default and leaves room for ad hoc UDF calls on the same account. In our offline test, 10 per second put 11 starts into the busiest one-second window and 8 per second put 9.
- A failed refresh never replaces a good answer, and a bad response never discards the batch. The
MERGEupdates a cached row on failure only when that row had already failed, and an unparseable response becomes a failed row instead of an exception.
Reports then read the table and flatten the stored results. Build the join key with the same expression the queue view uses.
SELECT a.account_id,
r.index + 1 AS rank,
r.value:url::STRING AS url,
r.value:title::STRING AS title,
c.fetched_at
FROM crm.accounts a
JOIN enrich.web.search_cache c
ON c.query = TRIM(a.company_name) || ' headquarters'
, LATERAL FLATTEN(input => c.response:results) r
WHERE c.ok;
Set the TTL by how fast the fact changes. Headquarters and official websites can sit for 30 to 90 days. Funding, layoffs and outages need a shorter TTL and the freshness parameter on the request. Give them a separate queue.
Cortex Agents: the built-in tool or a custom one
For an agent that answers questions such as "why did EMEA renewals dip last quarter?", the built-in Brave tool is the right first step. A custom tool earns its place when you need one of these:
- Source control. The Web Search API accepts
include_domainsas a strict allowlist of up to 500 domains, plusfreshness,countryandlanguage, described in the request controls guide. A UDF can fix those values so the agent cannot drift to sources you do not trust. - Predictable cost. A custom tool can fix the result count and log every call.
- A check on what leaves the account. The agent builds its query from the conversation, which can include customer or employee names. Snowflake's documentation says the built-in tool sends that query to Brave over the public internet. A custom procedure can run AI_REDACT on the query before it goes out.
Cortex Agents accept stored procedures and UDFs as custom tools, so the function above can serve as one. Describe what it returns and when not to call it, because the agent relies on that description when it picks a tool. For the residency and retention questions your security review will ask, see the guide to data residency for a search API.
What to test before you ship
- Access. Confirm external access is enabled, then run the UDF on one row.
- Failure paths. Use a revoked or wrong key and confirm rows come back with
okfalse rather than failing the query. - Rate limits. Run the procedure on a small queue with
rpsabove your limit and confirm the 429 retries recover. - Call counts. Compare API calls in your You.com usage with distinct queries in the queue.
- What leaves. Read a sample of real queries with your security team before a schedule sends thousands a day.
We tested the Python above offline on 12 November 2026 with 41 checks against a local server that returned documented-shape payloads and injected 429, 503, 422, 401 and non-JSON 200 responses. A 429 recovered after its Retry-After wait, a persistent 503 became a failed row after four attempts, and a non-JSON 200 became a failed row without stopping the batch. The Snowpark session and the secret call were stubs, and we could not run the SQL in Snowflake, so run each statement on a development account first.
The You.com Web Search API fits when you need ranked web results with source control and flat per-call pricing. It is not a company database: a headquarters address arrives inside a snippet, not as a field, so columns take your own parsing or Snowflake's AI_EXTRACT. If you need structured firmographics, the company data enrichment API guide compares providers built for that. The guide to the web search API JSON response explains each response field, and the Web Search API product page is the place to start.
Frequently Asked Questions
Yes. Create a network rule for the API's host, store the key in a secret, bundle both into an external access integration, and reference it from a Python, Java or Scala UDF or stored procedure. Calls to hosts outside the rule are denied. Trial accounts need an account representative to enable external access. External functions are the older route and send requests through a proxy service such as Amazon API Gateway.
An external function holds no code. Snowflake sends batches of rows in its own JSON format through a proxy service to a remote function you host, and Snowflake retries 429 and 5XX responses for you. External access lets UDF or procedure code call the API directly, so you write the retries. For a search API, external access avoids running a gateway and a translation function.
Yes, for Cortex Agents. The tool uses the Brave Web Search API, and Snowflake has zero data retention with Brave. An ACCOUNTADMIN enables it in Snowsight under AI & ML, Agents, Settings, then adds it to each agent. It is an agent tool, not a SQL function, so it cannot enrich a column row by row. Use a UDF or a scheduled procedure for that.
There are three parts: the API fee, $5.00 per 1,000 Web Search API calls as of November 2026; warehouse time while handlers wait on the network; and a small egress charge for request payloads. Repetition drives the total. A UDF in a view that refreshes 30 times a month over 100,000 rows makes 3,000,000 calls, or $15,000. A cache table with a 30-day TTL makes about 100,000.
Snowflake runs handler instances in parallel, so a larger warehouse raises your request rate but not your rate limit. For small lookups, retry 429 responses after the Retry-After wait and cap the attempts. For large jobs, call the API from a stored procedure whose worker threads share one pacer set below your limit, such as 8 requests per second against the default 10, and write results to a table.
LI Test
LI Test
Share Article:
Related resources.
.webp)
Search 1B+ professional profiles, 100M+ companies with Knowledge Pro
December 2, 2026
Product Updates

Introducing the You.com Extract API: fetch and parse any URL, with 80% higher accuracy on PDFs
November 17, 2026
Product Updates

FDA Approval Monitoring API: Sources, Lag and a Working Pipeline
November 15, 2026
Blog

Equity Research Automation API: What to Automate and How to Check the Numbers
November 14, 2026
Blog

Retail Assortment Monitoring API: How to Track What Competitors Add, Drop, and Carry
November 13, 2026
Blog