To level up my SQL and Python, I decided to try something a bit different for my latest project: fetching data from a web API without using any external ETL servers, Airflow DAGs, or paid connectors. Using Snowflake’s External Access Integration, I built a pipeline that pings the Food Standards Agency open API directly from the database, grabs the raw JSON food recall alerts, and cleans the nested payloads into structured tables for Tableau. Here is the exact walkthrough of how I set up the ingestion logic, along with a few lessons learned if you want to build something similar!

Steps Followed:

  1. Identify the API and Read Documentation
  2. Create a Database and a Schema in Snowflake
  3. Create Network Rule and External Access Integration
  4. Define a Snowflake User-Defined Function (UDF) that fetches food recall alerts from the FSA open API
  5. Ingest Data into a Staging Table
  6. Unnest JSON and clean resulting data

Identify the API and read documentation

Firstly, I made a conscious effort to become familiar with the data definition and the type of requests I could make using the API by taking a look at the documentation available on FSA's website (found here). I then began to form an idea of how I could get the data I was after, and which URLs to use in order to get a list of food safety alerts spanning 2018 to 2026 but also the allergen and pathogen lists.


Create a Database and a Schema in Snowflake

Before calling the API and getting the data, I prepared a landing space for the returned response by creating a database and a schema. In this case I already had a database so I replaced create with use.

If you don't already have a database or schema, don't worry it's quick and easy to set one up - just need to make sure your role has granted privileges to do so.


Create Network Rule and External Access Integration

By default, Snowflake's internal environment is strictly isolated from the public internet to prevent data exfiltration and unauthorized network traffic. Because the FSA data is an external source I used a Network Rule to whitelist the domain name 'data.food.gov.uk' first so that I could send GET requests to it from within Snowflake.

From there, I created an External Access Integration that utilizes the Network Rule created previously, acting as a secure bridge between Snowflake and the API endpoint. You need a role with granted privileges to create EAIs.

You can run SHOW EXTERNAL ACCESS INTEGRATIONS to double check that your EAI was created successfully.


Define a Snowflake User-Defined Function (UDF) that fetches food recall alerts from the FSA API

Traditionally, fetching external REST API data into a cloud data warehouse required an external ETL pipeline (e.g., running Python scripts locally, setting up AWS Lambda functions, using Airflow, or configuring Fivetran/Meltano).

Here, I used a custom function that accepts dynamic query parameters directly from SQL as a key-value OBJECT and maps them straight into the FSA endpoint using Python's 'requests' library. I instructed Snowflake to execute this code inside its built-in Python 3.10 sandbox environment by specifying the LANGUAGE and RUNTIME_VERSION, and store the returned response as VARIANT data type.

VARIANT allows semi-structured data (like JSON objects) to be stored safely without losing data or breaking the ingestion pipeline.

Remember the EAI we created earlier, this must be referenced in the function header to allow outbound network access so Python can ping 'data.food.gov.uk'.

Here, I declared HANDLER = 'get_alerts_flexible', which instructs Snowflake to look inside the double dollar signs ($$ ... $$) for a Python function with that exact name when executing the UDF.

Inside the double dollar signs, I've imported Python's requests library to manage HTTP communication and defined the function get_alerts_flexible that is executed in the UDF above. Then, I specified the target URL https://data.food.gov.uk/food-alerts/id and configured the HTTP headers to request standard JSON responses.

From there, I executed the API request using requests.get(...). By mapping the SQL query_filters dictionary straight into the params argument, the script dynamically translates SQL key-value inputs into valid URL parameters (like ?_limit=500&_offset=0), while enforcing a 30-second timeout for safety.

Finally, I needed to implement robust error handling. If the request succeeds (200 OK), the function converts and returns the raw JSON payload using response.json(). If the API throws an HTTP error (such as a 404 or 500) or times out, the function catches the exception and returns a structured JSON error dictionary. This ensures that an API hiccup fails gracefully without crashing my downstream SQL queries.


Ingest Data into a Staging Table

Inside the database and schema created in Step 2, I've created a staging table to store my nested JSON response from the API call. Here, I kept the data type as VARIANT to prevent losing data and added a timestamp to track when the pipeline was ran each time.

To populate the staging table, I used an INSERT INTO ... SELECT statement that evaluates the Python function created in the previous step. The query constructs the dynamic filter parameters on the fly using OBJECT_CONSTRUCT(), which wraps the key-value pairs into the OBJECT format expected by the function's query_filters parameter.

As you may have noticed, I used pagination to fetch the data by capping each request at 500 records (_limit: 500) and incrementing the _offset by 500 in each query.

This approach was necessary because the FSA API enforces strict limits on how many items can be returned per call. Also, breaking the data into smaller chunks prevents network timeouts and Snowflake memory failures. Combining offset pagination with a strict sort order (_sort: '-modified') guarantees that we step cleanly through the dataset without skipping records or ingesting duplicates.

The resulting table looks something like this, inside the raw_payload field we've successfully captured the nested JSON response which will be cleaned at a later stage.


Unnest JSON objects and clean resulting data

Now that the raw, semi-structured data has safely landed in Snowflake, the next step is moving from the Load phase to the Transform phase. To make the nested JSON easy to query, I created an intermediate view to unpack the payload using Snowflake's LATERAL FLATTEN() function. This explodes nested JSON arrays such as individual products or allergens listed within a single alert into distinct relational rows without losing their parent context.

With our array elements exploded into individual rows, the real data-cleansing work begins. Now, I won't bore you with the endless lines of data cleaning, you know the drill.

Between regex functions wrestling company names out of free-text titles, COALESCE statements standardizing hazard types, and window functions wiping out duplicates, the cleansing script gets pretty deep in the weeds.


Conclusion

Building this pipeline proved that Snowflake is far more than just a place to store clean data, it can handle the heavy lifting of live web ingestion directly inside its cloud engine. What made this project particularly rewarding was the iterative feedback loop between data engineering and visualization. Taking the transformed data downstream into Tableau quickly exposed subtle data-cleaning gaps and missing edge cases, sending me right back into the pipeline to refine my regex logic and error handling. It was a great reminder that pipelines are rarely built perfectly on the first pass, and wrestling with those real-world API quirks was easily the best learning experience of the entire build.

I really enjoyed putting this together and seeing a serverless pipeline come to life end-to-end. I hope this walkthrough gives you a solid blueprint (and saves you a few headaches) whenever you decide to tackle your own direct API ingestion inside Snowflake!