Skip to main content

Ingest data from an API

Many sources expose data only through an API, such as analytics platforms, SaaS tools and internal services. This page writes a collector that calls the API and writes Parquet to object storage. An ingestion step then loads those files into Bauplan on a data branch and publishes them. The example source returns sessions per day, and can still revise the numbers of the last three days.

The collector runs outside Bauplan, wherever your scheduler runs it (a Lambda, a container job, a CI job). The ingestion step reads the staged files with a pipeline. The examples on this page use this layout:

    • collector.pycalls the API, writes one Parquet file per day and a manifest
    • main.pystages the files, runs the pipeline, publishes
      • bauplan_project.yaml
      • models.pyanalytics.sessions_staging -> analytics.sessions_daily

Collect a trailing window

APIs often revise recent data after the fact. Pull a trailing window of several days on every run rather than only the last day, to pick up the revisions:

collector.py
from datetime import date, timedelta

import requests


def fetch_daily_sessions(api_url: str, token: str, start: date, end: date) -> list[dict]:
"""Follow the API cursor until the last page"""
rows: list[dict] = []
params = {"start_date": start.isoformat(), "end_date": end.isoformat(), "page_size": 1000}
while True:
response = requests.get(api_url, headers={"Authorization": f"Bearer {token}"}, params=params, timeout=30)
response.raise_for_status()
payload = response.json()
rows.extend(payload["results"])
if not payload.get("next_cursor"):
return rows
params["cursor"] = payload["next_cursor"]


end = date.today()
start = end - timedelta(days=3)
rows = fetch_daily_sessions(API_URL, API_TOKEN, start, end)

Handle pagination in whatever form the API uses (cursor, page token, offset). Keep the collector minimal. It only calls the API and writes files. Do the casting and reshaping in Bauplan, where they are versioned and testable.

Write one Parquet file per day

Write the rows under a path that identifies the day the data describes, not the day you collected it. Pulling a day again then overwrites the file of that day instead of adding a second copy:

collector.py
import pandas as pd

frame = pd.DataFrame(rows)
frame["date"] = pd.to_datetime(frame["date"]).dt.date
frame["sessions"] = frame["sessions"].astype("Int64") # fixed dtype, the Parquet type must not flip between runs

files = []
for day, part in frame.groupby("date"):
uri = f"s3://my-bucket/raw/analytics/sessions/date={day}/data.parquet"
part.to_parquet(uri, index=False)
files.append(uri)

Keep the date as a column in the file, not only in the object storage path, as Bauplan does not read values from the URI. Pin the type of every column that can be null or empty in a batch. Libraries infer types per batch, and a column that flips between integer and float, or appears as a null type, breaks table creation and imports.

Last, write a manifest with the window and the files of this run, and pass its location to main.py, for example as a command-line argument from the scheduler:

collector.py
import json
from datetime import datetime, timezone

import boto3

run_id = datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S")
manifest_key = f"raw/analytics/_manifests/sessions-{run_id}.json"
manifest = {"start": start.isoformat(), "end": end.isoformat(), "files": files}
boto3.client("s3").put_object(Bucket="my-bucket", Key=manifest_key, Body=json.dumps(manifest))

It works like the manifest in how to ingest a database with scheduled dumps:

raw/analytics/_manifests/sessions-20261126061500.json
{
"start": "2026-11-23",
"end": "2026-11-26",
"files": [
"s3://my-bucket/raw/analytics/sessions/date=2026-11-23/data.parquet",
"s3://my-bucket/raw/analytics/sessions/date=2026-11-24/data.parquet",
"s3://my-bucket/raw/analytics/sessions/date=2026-11-25/data.parquet",
"s3://my-bucket/raw/analytics/sessions/date=2026-11-26/data.parquet"
]
}

Stage the new files and overwrite the window

The window overlaps with previous runs, and the new files must replace the rows they cover. An import, on the other hand, only appends. Register the new files as an external staging table instead, and let a pipeline overwrite the window in the managed table. This staging pattern is covered in more detail in how to transform data at import time.

note

If the API returns records that never change, such as events with unique IDs, there is no window to overwrite. Write each run under a new path and import the new files directly into a managed table, as in how to ingest data into Bauplan.

main.py
import json
import sys
from datetime import datetime, timezone

import bauplan
import boto3

# The manifest key written by collector.py, passed by the scheduler
manifest_key = sys.argv[1]
manifest = json.loads(boto3.client("s3").get_object(Bucket="my-bucket", Key=manifest_key)["Body"].read())

client = bauplan.Client()
stamp = datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S")
branch = f"{client.info().user.username}.analytics-ingestion-prod-{stamp}"
client.create_branch(branch=branch, from_ref="main", if_not_exists=False)
client.create_namespace(namespace="analytics", branch=branch, if_not_exists=True)

state = client.create_external_table_from_parquet(
table="sessions_staging", search_patterns=manifest["files"], branch=branch, namespace="analytics", overwrite=True,
)
if state.error:
raise RuntimeError(state.error)

The pipeline reads the staging table, casts it, and writes the raw table with OVERWRITE_PARTITIONS, limited to the window passed as parameters:

bauplan_project.yaml
project:
id: 2c5b5f0e-6f3c-4a9e-9d1c-3f3e8f9a1b2c
name: analytics_ingestion
parameters:
start_date:
type: str
required: true
end_date:
type: str
required: true
models.py
from typing import Annotated

import bauplan
import pyarrow as pa


class DailySessions(bauplan.TableSchema):
"""Sessions per day, as reported by the analytics API."""

date: bauplan.Date32
sessions: bauplan.Int64 | None


@bauplan.model(
name="analytics.sessions_daily",
materialization_strategy="OVERWRITE_PARTITIONS",
partitioned_by=["date"],
overwrite_filter="date >= $start_date AND date <= $end_date",
)
@bauplan.python("3.13", pip={"polars": "2.2.0"})
def sessions_daily(
staged: Annotated[pa.Table, bauplan.Model("analytics.sessions_staging")],
) -> Annotated[pa.Table, DailySessions]:
"""Overwrite only the days of this run's window."""
import polars as pl

return (
pl.DataFrame(staged)
.select(pl.col("date").cast(pl.Date), pl.col("sessions").cast(pl.Int64))
.to_arrow()
)

The staging table must have a different name from the target table. Otherwise the DAG reads its own output.

Run, clean up and publish

main.py
run = client.run(
project_dir="analytics_ingestion",
ref=branch,
namespace="analytics",
parameters={"start_date": manifest["start"], "end_date": manifest["end"]},
)
if run.job_status != "SUCCESS":
raise RuntimeError(f"run failed: {run.error}")

# The staging table exists only on this branch and must not reach main
client.delete_table(table="sessions_staging", branch=branch, namespace="analytics")
client.merge_branch(source_ref=branch, into_branch="main")
client.delete_branch(branch=branch)

A run that fails before the merge leaves its timestamped branch behind. See how to clean up branches.

Rerunning the same window produces the same table. The files for each day are overwritten in place, and the pipeline overwrites the same partitions.