Skip to content

Custom Sources

Create custom source connectors to extract data from any API or system not covered by built-in connectors.

A custom source consists of:

  1. A config class extending SourceConfig
  2. A source class implementing AbstractSource
  1. Create the source file

    Create my_source.py:

    from typing import List, Optional, Tuple, Type
    from requests.auth import AuthBase
    from bizon.source.source import AbstractSource
    from bizon.source.config import SourceConfig
    from bizon.source.models import SourceIteration, SourceRecord
    from bizon.source.auth.builder import AuthBuilder
    from pydantic import Field
    class MySourceConfig(SourceConfig):
    """Configuration for MySource."""
    api_url: str = Field(..., description="API base URL")
    page_size: int = Field(100, description="Records per page")
    class MySource(AbstractSource):
    @staticmethod
    def streams() -> List[str]:
    return ["users", "orders"]
    @staticmethod
    def get_config_class() -> Type[SourceConfig]:
    return MySourceConfig
    def get_authenticator(self) -> Optional[AuthBase]:
    if self.config.authentication:
    return AuthBuilder.from_config(self.config.authentication)
    return None
    def check_connection(self) -> Tuple[bool, Optional[str]]:
    try:
    response = self.session.get(f"{self.config.api_url}/health")
    return response.ok, None
    except Exception as e:
    return False, str(e)
    def get_total_records_count(self) -> Optional[int]:
    return None # Unknown
    def get(self, pagination: dict = None) -> SourceIteration:
    page = pagination.get("page", 1) if pagination else 1
    response = self.session.get(
    f"{self.config.api_url}/{self.config.stream}",
    params={"page": page, "limit": self.config.page_size}
    )
    data = response.json()
    records = [
    SourceRecord(id=str(item["id"]), data=item)
    for item in data["items"]
    ]
    has_more = len(records) == self.config.page_size
    next_pagination = {"page": page + 1} if has_more else {}
    return SourceIteration(records=records, next_pagination=next_pagination)
  2. Create the config file

    Create config.yml:

    name: my-custom-pipeline
    source:
    name: my_source
    stream: users
    api_url: https://api.example.com
    page_size: 100
    authentication:
    type: api_key
    params:
    token: ${env://API_TOKEN}
    destination:
    name: logger
    config: {}
  3. Run the pipeline

    Terminal window
    bizon run config.yml --custom-source ./my_source.py

Define source-specific configuration by extending SourceConfig:

from pydantic import Field
from bizon.source.config import SourceConfig
class MySourceConfig(SourceConfig):
# Required fields
api_url: str = Field(..., description="API base URL")
# Optional fields with defaults
page_size: int = Field(100, description="Records per page")
timeout: int = Field(30, description="Request timeout in seconds")
include_deleted: bool = Field(False, description="Include deleted records")

Your config automatically includes these base fields:

FieldTypeDefaultDescription
namestringRequiredSource identifier
streamstringRequiredStream to sync
sync_modeenumfull_refreshSync mode
cursor_fieldstringNonePassed to get_records_after as source_state.cursor_field
authenticationobjectNoneAuth config
httpobjectNoneHTTP policy of the default session. See HTTP Policy
force_ignore_checkpointboolfalseRestart the in-flight job from iteration 0
max_iterationsintNoneLimit iterations
resetboolfalseDeprecated: use bizon run --reset or bizon stream reset

A source: key that your config class does not declare is dropped and logged as a warning, which usually catches a typo or a key that belongs under destination.config. To accept arbitrary keys, declare the class with extra="allow":

from pydantic import ConfigDict
class MySourceConfig(SourceConfig):
model_config = ConfigDict(extra="allow")

Custom source files can use from __future__ import annotations: string annotations that name a type defined in the same file resolve correctly.

Implement AbstractSource with required methods:

from bizon.source.source import AbstractSource
class MySource(AbstractSource):
@staticmethod
def streams() -> List[str]:
"""Return available stream names."""
return ["users", "orders", "products"]
@staticmethod
def get_config_class() -> Type[SourceConfig]:
"""Return the config class."""
return MySourceConfig
def get_authenticator(self) -> Optional[AuthBase]:
"""Return authenticator for the session."""
if self.config.authentication:
return AuthBuilder.from_config(self.config.authentication)
return None
def check_connection(self) -> Tuple[bool, Optional[str]]:
"""Test connectivity. Return (success, error_message)."""
try:
response = self.session.get(f"{self.config.api_url}/ping")
return response.ok, None
except Exception as e:
return False, str(e)
def get_total_records_count(self) -> Optional[int]:
"""Return total record count if known."""
response = self.session.get(f"{self.config.api_url}/count")
return response.json().get("total")
def get(self, pagination: dict = None) -> SourceIteration:
"""Fetch next batch of records."""
# Implementation here
pass
def get(self, pagination: dict = None) -> SourceIteration:
cursor = pagination.get("cursor") if pagination else None
params = {"limit": self.config.page_size}
if cursor:
params["cursor"] = cursor
response = self.session.get(
f"{self.config.api_url}/{self.config.stream}",
params=params
)
data = response.json()
records = [
SourceRecord(id=str(item["id"]), data=item)
for item in data["items"]
]
next_cursor = data.get("next_cursor")
return SourceIteration(
records=records,
next_pagination={"cursor": next_cursor} if next_cursor else {}
)
def get(self, pagination: dict = None) -> SourceIteration:
offset = pagination.get("offset", 0) if pagination else 0
response = self.session.get(
f"{self.config.api_url}/{self.config.stream}",
params={"offset": offset, "limit": self.config.page_size}
)
data = response.json()
records = [
SourceRecord(id=str(item["id"]), data=item)
for item in data["items"]
]
if len(records) < self.config.page_size:
return SourceIteration(records=records, next_pagination={})
return SourceIteration(
records=records,
next_pagination={"offset": offset + self.config.page_size}
)
def get(self, pagination: dict = None) -> SourceIteration:
page = pagination.get("page", 1) if pagination else 1
response = self.session.get(
f"{self.config.api_url}/{self.config.stream}",
params={"page": page, "per_page": self.config.page_size}
)
data = response.json()
records = [
SourceRecord(id=str(item["id"]), data=item)
for item in data["items"]
]
total_pages = data.get("total_pages", 1)
if page >= total_pages:
return SourceIteration(records=records, next_pagination={})
return SourceIteration(
records=records,
next_pagination={"page": page + 1}
)

Support incremental mode by implementing get_records_after:

from bizon.source.models import SourceIncrementalState
class MySource(AbstractSource):
def get_records_after(
self,
source_state: SourceIncrementalState,
pagination: dict = None
) -> SourceIteration:
"""Fetch records updated in [last_run, run_started_at)."""
cursor = pagination.get("cursor") if pagination else None
params = {
"updated_since": source_state.last_run.strftime("%Y-%m-%dT%H:%M:%SZ"),
"updated_before": source_state.run_started_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
"limit": self.config.page_size
}
if cursor:
params["cursor"] = cursor
response = self.session.get(
f"{self.config.api_url}/{self.config.stream}",
params=params
)
data = response.json()
records = [
SourceRecord(id=str(item["id"]), data=item)
for item in data["items"]
]
next_cursor = data.get("next_cursor")
return SourceIteration(
records=records,
next_pagination={"cursor": next_cursor} if next_cursor else {}
)

Then use incremental mode:

source:
name: my_source
stream: users
sync_mode: incremental

The first incremental run has no previous successful job, so it calls get() instead and fetches everything. Later runs call get_records_after with a SourceIncrementalState:

FieldDescription
last_runStart time (created_at) of the last successful job
run_started_atStart time of the current job, stable across resumes. It becomes the next run’s last_run, so using it as the window’s upper bound makes consecutive windows tile with no gap
stateThe next_state saved by the last successful job ({} if none)
cursor_fieldsource.cursor_field from the config

A watermark that isn’t a timestamp (a sequence number, an export id, a per-partition cursor) can be carried between runs with next_state:

def get_records_after(self, source_state, pagination=None) -> SourceIteration:
since_id = source_state.state.get("max_id", 0)
items = self.fetch_items(since_id=since_id, pagination=pagination)
return SourceIteration(
records=[SourceRecord(id=str(i["id"]), data=i) for i in items],
next_pagination={},
next_state={"max_id": max((i["id"] for i in items), default=since_id)},
)
  • next_state must be JSON-serializable; a value that isn’t fails on the iteration that emits it.
  • The last non-None next_state of a run is saved, and only if the job succeeds.
  • A run that emits none carries the previous state forward.
  • A stream reset starts from an empty state.

Route records to different destinations:

def get(self, pagination: dict = None) -> SourceIteration:
# Fetch data...
records = []
for item in data["items"]:
record = SourceRecord(
id=str(item["id"]),
data=item,
destination_id=f"project.dataset.{item['type']}_events"
)
records.append(record)
return SourceIteration(records=records, next_pagination={})

Use Bizon’s built-in authenticators:

from bizon.source.auth.builder import AuthBuilder
def get_authenticator(self) -> Optional[AuthBase]:
if self.config.authentication:
return AuthBuilder.from_config(self.config.authentication)
return None

Or create a custom authenticator:

from requests.auth import AuthBase
class CustomAuth(AuthBase):
def __init__(self, api_key: str, secret: str):
self.api_key = api_key
self.secret = secret
def __call__(self, request):
signature = self._sign(request)
request.headers["X-API-Key"] = self.api_key
request.headers["X-Signature"] = signature
return request
def _sign(self, request):
# Custom signing logic
pass
class MySource(AbstractSource):
def get_authenticator(self) -> Optional[AuthBase]:
return CustomAuth(
api_key=self.config.api_key,
secret=self.config.api_secret
)

The default session retries 429, 5xx and Cloudflare 52x responses itself, honouring Retry-After, before your code sees anything. With raise_for_status: true (the default), an error that survives the retries is raised from inside self.session.get(...) as a requests.HTTPError carrying the last response, so there is no need to call response.raise_for_status():

from requests.exceptions import HTTPError
def get(self, pagination: dict = None) -> SourceIteration:
try:
response = self.session.get(f"{self.config.api_url}/{self.config.stream}")
except HTTPError as e:
# Retries are already spent here, including for a 429.
raise RuntimeError(
f"API error {e.response.status_code}: {e.response.text[:200]}"
) from e
data = response.json()
# Process data...

To treat some statuses as data (a 404 meaning “no records”, say), give the config class an http default with raise_for_status: False and inspect response.status_code yourself. Retries still apply.

self.session is built from the source’s http block. Every key is optional:

source:
name: my_source
stream: users
http:
timeout: [10, 60]
raise_for_status: true
retries:
total: 10
backoff_factor: 2
status_forcelist: [429, 500, 502, 503, 504, 520, 522, 524]
allowed_methods: [GET, POST]
retry_after_max: 120
KeyDefaultDescription
timeout[10, 60](connect, read) timeout in seconds, or a single number, for requests that don’t pass timeout=
raise_for_statustrueRaise requests.HTTPError on 4xx/5xx. Disable for sources that inspect non-2xx responses
retries.total10Maximum retries, across all causes
retries.backoff_factor2Exponential backoff factor, in seconds
retries.status_forcelist[429, 500, 502, 503, 504, 520, 522, 524]Statuses retried with or without a Retry-After header
retries.allowed_methods[GET, POST]Methods that may be retried
retries.retry_after_max120Cap in seconds on a Retry-After wait. null honours the header as sent
  • Unset: the connector’s own default applies. A source that declares none gets the values above.
  • Partial block: merged over the connector’s default, including inside retries. Setting http: {timeout: 120} on a connector that defaults raise_for_status: false keeps it false.
  • Exhausted retries: raise a requests.HTTPError carrying the last response when raise_for_status is on; otherwise the last response is returned.

A connector sets its own default by redeclaring the field:

from typing import Optional
from pydantic import Field
from bizon.source.config import HttpConfig, HttpRetryConfig, SourceConfig
class MySourceConfig(SourceConfig):
http: Optional[HttpConfig] = Field(
default_factory=lambda: HttpConfig(
raise_for_status=False,
retries=HttpRetryConfig(total=50, backoff_factor=1),
)
)

Override get_retry_policy() to change retries while keeping the default session (and its timeout and raise_for_status hook). It returns a urllib3 Retry; CappedRetry adds the Retry-After cap:

from bizon.source.session import CappedRetry
class MySource(AbstractSource):
def get_retry_policy(self):
return CappedRetry(
total=5,
backoff_factor=1,
status_forcelist=[429, 503],
allowed_methods=["GET"],
respect_retry_after_header=True,
max_retry_after=60,
raise_on_status=False, # hand back the last response so raise_for_status raises HTTPError
)

Whatever session a source uses, including a plain requests.Session returned by an overridden get_session():

  • A request that passes no timeout= gets (10, 300). The read timeout bounds an idle socket, so it only fires on a stalled connection. An explicit timeout= wins, and the default session uses http.timeout instead.
  • A response body cut off mid-read (ChunkedEncodingError, urllib3 ProtocolError) is retried up to 3 times with backoff, for non-streaming requests whose method the mounted retry policy allows (GET and POST if it has none).

An overridden session’s adapters, retry policy and hooks are otherwise left untouched.

bizon.source.graphql is a shared transport for GraphQL APIs. It sends requests through your session and leaves auth, error vocabulary and pageInfo location to you.

HelperDescription
graphql_post(session, url, query, variables=None, **opts)POST with bounded retries; returns the parsed JSON body. Transient errors get 3 attempts (waits (15, 60) s), rate limits 6 (waits (60, 900) s), both doubling per retry
graphql_post_adaptive(session, url, query, variables, *, page_size_var, start_size, ...)Like graphql_post, but on a persistent transient error it shrinks variables[page_size_var] and retries the same cursor. Returns (body, size_that_worked)
build_page_shrink_sequence(start_size, floor=1, steps=(25, 10, 5, 1))The page-size ladder used by the adaptive call, e.g. 100 → [100, 25, 10, 5, 1]
PhantomProbeOptional probe= for the adaptive call: a pageInfo-only query that steps past index entries the API can no longer resolve, with per-page and per-run skip limits
default_classifier(response, body)429 → rate limited; 5xx or transient errors[] → transient; other errors[] → fatal. Pass your own as classify=
GRAPHQL_TIMEOUT(10, 120), the default timeout

Errors: GraphQLError (fatal errors[]), TransientGraphQLError (transient budget spent) and GraphQLRateLimited (rate-limit budget spent, with wait_seconds). A non-2xx response the classifier doesn’t claim surfaces as HTTPError.

graphql_post needs to see non-2xx responses, so default raise_for_status to false:

from typing import Optional
from pydantic import Field
from bizon.source.config import HttpConfig, SourceConfig
from bizon.source.graphql import graphql_post_adaptive
ISSUES = """
query Issues($first: Int!, $after: String) {
issues(first: $first, after: $after) {
nodes { id title updatedAt }
pageInfo { hasNextPage endCursor }
}
}
"""
class MyGraphQLConfig(SourceConfig):
http: Optional[HttpConfig] = Field(default_factory=lambda: HttpConfig(raise_for_status=False))
class MyGraphQLSource(AbstractSource):
def get(self, pagination: dict = None) -> SourceIteration:
pagination = pagination or {}
body, size = graphql_post_adaptive(
self.session,
"https://api.example.com/graphql",
ISSUES,
{"after": pagination.get("cursor")},
page_size_var="first",
start_size=pagination.get("page_size", 100),
max_size=100,
label="issues",
)
issues = body["data"]["issues"]
page_info = issues["pageInfo"]
return SourceIteration(
records=[SourceRecord(id=n["id"], data=n) for n in issues["nodes"]],
next_pagination=(
{"cursor": page_info["endCursor"], "page_size": size}
if page_info["hasNextPage"] else {}
),
)

Test your source with the logger destination:

source:
name: my_source
stream: users
api_url: https://api.example.com
max_iterations: 3 # Limit for testing
destination:
name: logger
config: {}
Terminal window
bizon run config.yml --custom-source ./my_source.py --log-level DEBUG

Full REST API source implementation:

from datetime import datetime
from typing import List, Optional, Tuple, Type
from requests.auth import AuthBase
from pydantic import Field
from pytz import UTC
from bizon.source.source import AbstractSource
from bizon.source.config import SourceConfig
from bizon.source.models import (
SourceIteration,
SourceRecord,
SourceIncrementalState
)
from bizon.source.auth.builder import AuthBuilder
class RestApiSourceConfig(SourceConfig):
"""Configuration for REST API Source."""
base_url: str = Field(..., description="API base URL")
page_size: int = Field(100, description="Records per page")
timeout: int = Field(30, description="Request timeout")
class RestApiSource(AbstractSource):
"""Generic REST API source connector."""
@staticmethod
def streams() -> List[str]:
return ["users", "orders", "products"]
@staticmethod
def get_config_class() -> Type[SourceConfig]:
return RestApiSourceConfig
def get_authenticator(self) -> Optional[AuthBase]:
if self.config.authentication:
return AuthBuilder.from_config(self.config.authentication)
return None
def check_connection(self) -> Tuple[bool, Optional[str]]:
try:
response = self.session.get(
f"{self.config.base_url}/health",
timeout=self.config.timeout
)
return response.ok, None
except Exception as e:
return False, str(e)
def get_total_records_count(self) -> Optional[int]:
try:
response = self.session.get(
f"{self.config.base_url}/{self.config.stream}/count"
)
return response.json().get("total")
except:
return None
def get(self, pagination: dict = None) -> SourceIteration:
cursor = pagination.get("cursor") if pagination else None
params = {"limit": self.config.page_size}
if cursor:
params["after"] = cursor
response = self.session.get(
f"{self.config.base_url}/{self.config.stream}",
params=params,
timeout=self.config.timeout
)
response.raise_for_status()
data = response.json()
records = [
SourceRecord(
id=str(item["id"]),
data=item,
timestamp=datetime.fromisoformat(
item.get("updated_at", datetime.now(UTC).isoformat())
)
)
for item in data.get("data", [])
]
next_cursor = data.get("pagination", {}).get("next_cursor")
return SourceIteration(
records=records,
next_pagination={"cursor": next_cursor} if next_cursor else {}
)
def get_records_after(
self,
source_state: SourceIncrementalState,
pagination: dict = None
) -> SourceIteration:
cursor = pagination.get("cursor") if pagination else None
params = {
"limit": self.config.page_size,
"updated_since": source_state.last_run.strftime("%Y-%m-%dT%H:%M:%SZ")
}
if cursor:
params["after"] = cursor
response = self.session.get(
f"{self.config.base_url}/{self.config.stream}",
params=params,
timeout=self.config.timeout
)
response.raise_for_status()
data = response.json()
records = [
SourceRecord(
id=str(item["id"]),
data=item,
timestamp=datetime.fromisoformat(item["updated_at"])
)
for item in data.get("data", [])
]
next_cursor = data.get("pagination", {}).get("next_cursor")
return SourceIteration(
records=records,
next_pagination={"cursor": next_cursor} if next_cursor else {}
)