Custom Sources
Create custom source connectors to extract data from any API or system not covered by built-in connectors.
Overview
Section titled “Overview”A custom source consists of:
- A config class extending
SourceConfig - A source class implementing
AbstractSource
Quick Start
Section titled “Quick Start”-
Create the source file
Create
my_source.py:from typing import List, Optional, Tuple, Typefrom requests.auth import AuthBasefrom bizon.source.source import AbstractSourcefrom bizon.source.config import SourceConfigfrom bizon.source.models import SourceIteration, SourceRecordfrom bizon.source.auth.builder import AuthBuilderfrom pydantic import Fieldclass 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):@staticmethoddef streams() -> List[str]:return ["users", "orders"]@staticmethoddef get_config_class() -> Type[SourceConfig]:return MySourceConfigdef get_authenticator(self) -> Optional[AuthBase]:if self.config.authentication:return AuthBuilder.from_config(self.config.authentication)return Nonedef check_connection(self) -> Tuple[bool, Optional[str]]:try:response = self.session.get(f"{self.config.api_url}/health")return response.ok, Noneexcept Exception as e:return False, str(e)def get_total_records_count(self) -> Optional[int]:return None # Unknowndef get(self, pagination: dict = None) -> SourceIteration:page = pagination.get("page", 1) if pagination else 1response = 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_sizenext_pagination = {"page": page + 1} if has_more else {}return SourceIteration(records=records, next_pagination=next_pagination) -
Create the config file
Create
config.yml:name: my-custom-pipelinesource:name: my_sourcestream: usersapi_url: https://api.example.compage_size: 100authentication:type: api_keyparams:token: ${env://API_TOKEN}destination:name: loggerconfig: {} -
Run the pipeline
Terminal window bizon run config.yml --custom-source ./my_source.py
Config Class
Section titled “Config Class”Define source-specific configuration by extending SourceConfig:
from pydantic import Fieldfrom 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")Inherited Fields
Section titled “Inherited Fields”Your config automatically includes these base fields:
| Field | Type | Default | Description |
|---|---|---|---|
name | string | Required | Source identifier |
stream | string | Required | Stream to sync |
sync_mode | enum | full_refresh | Sync mode |
cursor_field | string | None | Passed to get_records_after as source_state.cursor_field |
authentication | object | None | Auth config |
http | object | None | HTTP policy of the default session. See HTTP Policy |
force_ignore_checkpoint | bool | false | Restart the in-flight job from iteration 0 |
max_iterations | int | None | Limit iterations |
reset | bool | false | Deprecated: use bizon run --reset or bizon stream reset |
Unknown Keys
Section titled “Unknown Keys”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.
Source Class
Section titled “Source Class”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 passPagination Patterns
Section titled “Pagination Patterns”Cursor-Based
Section titled “Cursor-Based”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 {} )Offset-Based
Section titled “Offset-Based”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} )Page-Based
Section titled “Page-Based”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} )Incremental Sync
Section titled “Incremental Sync”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: incrementalThe 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:
| Field | Description |
|---|---|
last_run | Start time (created_at) of the last successful job |
run_started_at | Start 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 |
state | The next_state saved by the last successful job ({} if none) |
cursor_field | source.cursor_field from the config |
Persisting Source State
Section titled “Persisting Source State”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_statemust be JSON-serializable; a value that isn’t fails on the iteration that emits it.- The last non-
Nonenext_stateof 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.
Multi-Table Routing
Section titled “Multi-Table Routing”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={})Authentication
Section titled “Authentication”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 NoneOr 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 )Error Handling
Section titled “Error Handling”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.
HTTP Policy
Section titled “HTTP Policy”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| Key | Default | Description |
|---|---|---|
timeout | [10, 60] | (connect, read) timeout in seconds, or a single number, for requests that don’t pass timeout= |
raise_for_status | true | Raise requests.HTTPError on 4xx/5xx. Disable for sources that inspect non-2xx responses |
retries.total | 10 | Maximum retries, across all causes |
retries.backoff_factor | 2 | Exponential 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_max | 120 | Cap 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. Settinghttp: {timeout: 120}on a connector that defaultsraise_for_status: falsekeeps it false. - Exhausted retries: raise a
requests.HTTPErrorcarrying the last response whenraise_for_statusis on; otherwise the last response is returned.
A connector sets its own default by redeclaring the field:
from typing import Optionalfrom pydantic import Fieldfrom 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), ) )Tuning Retries in Code
Section titled “Tuning Retries in Code”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 )Session Hardening
Section titled “Session Hardening”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 explicittimeout=wins, and the default session useshttp.timeoutinstead. - A response body cut off mid-read (
ChunkedEncodingError, urllib3ProtocolError) 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.
GraphQL Sources
Section titled “GraphQL Sources”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.
| Helper | Description |
|---|---|
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] |
PhantomProbe | Optional 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 Optionalfrom pydantic import Fieldfrom bizon.source.config import HttpConfig, SourceConfigfrom 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 {} ), )Testing
Section titled “Testing”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: {}bizon run config.yml --custom-source ./my_source.py --log-level DEBUGComplete Example
Section titled “Complete Example”Full REST API source implementation:
from datetime import datetimefrom typing import List, Optional, Tuple, Typefrom requests.auth import AuthBasefrom pydantic import Fieldfrom pytz import UTC
from bizon.source.source import AbstractSourcefrom bizon.source.config import SourceConfigfrom 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 {} )Next Steps
Section titled “Next Steps”- Custom Source Tutorial - Step-by-step guide
- Sources Overview - AbstractSource API reference
- Authentication - Auth configuration