> For the complete documentation index, see [llms.txt](https://v2.dataos.info/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://v2.dataos.info/references/resources/nilus/batch/custom-sources/creating-custom-source.md).

# Building a custom source

Step-by-step reference for building a custom Nilus source: Git repo sync configuration, the implementation contract, source options, and troubleshooting.

Custom sources extend Nilus to upstream systems that are not yet covered by a built-in connector. You implement a Python class, keep it in Git, and invoke it through a `custom://` source address. Nilus still handles orchestration, destination writes, and incremental state when you implement it.

Use [Custom query (SQL)](https://v2.dataos.info/references/resources/nilus/batch/custom-sources/custom-query-sql-sources.md) first when the system is SQL-accessible. Use a custom source only when a first-party connector or a `query:` extract cannot model the source.

### When to use a custom source

* The upstream system is not in the supported source catalog.
* You need source-specific authentication, pagination, or object modeling.
* You want the ingestion logic in version-controlled Python that the team owns end-to-end.

Custom sources run as `spec.type: batch` pipelines only.

### Requirements <a href="#requirements" id="requirements"></a>

Repository access and a compatible runtime are required before Nilus can run a custom source pipeline.

#### Repository access

Before each run, Nilus synchronizes the configured repository and discovers the source implementation. The discovery process determines which class serves the `custom://` address.

1. The runtime clones `spec.repo.url` with git-sync before the pipeline starts.
2. It sets `baseDir` as the custom-resource directory and installs `requirements.txt` when present.
3. It imports every **top-level** `*.py` file in `baseDir` and finds `CustomSource` subclasses.
4. It instantiates the class matching the URI host: `custom://RandomUserSource` → `RandomUserSource`.
5. It calls `nilus_source(uri, table, **kwargs)` and loads its `@nilus.resource` objects.

The URI host is the **Python class name**, case-sensitive. Nested packages are not scanned. Keep helper modules beside the top-level files.

#### Python runtime

The Nilus runtime runs on **Python 3.13** (from Nilus `2.0.29`; earlier versions ran Python 3.11). Your custom source code, and every package pinned in `requirements.txt`, must install and run on Python 3.13.

{% hint style="warning" %}
If you built a custom source on an earlier Nilus version, re-validate it after upgrading: run the pipeline once and confirm that `requirements.txt` installs cleanly and the source loads. Packages pinned to old versions are the most common cause of failures.
{% endhint %}

### Implementation contract

Every custom source subclasses `CustomSource` from the `nilus` package:

```python
from nilus import CustomSource

class MyCustomSource(CustomSource):
    def handles_incrementality(self) -> bool:
        return False

    def nilus_source(self, uri: str, table: str, **kwargs):
        return my_source_function(uri, table, **kwargs)
```

| Method                               | Required | Role                                                                                                                                                          |
| ------------------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `nilus_source(uri, table, **kwargs)` | Yes      | Return one `@nilus.resource` or a tuple of resources. This is the entrypoint Nilus executes.                                                                  |
| `handles_incrementality()`           | Yes      | Return `True` only when your code owns the incremental cursor through `nilus.current.resource_state()`. Nilus then skips `sink.options.incremental_strategy`. |

{% hint style="info" %}
`dlt_source()` exists only as a backward-compatible alias. Implement `nilus_source()`.
{% endhint %}

### **Define resources and source functions**

Resources are generator functions decorated with `@nilus.resource()`. Register them from a function decorated with `@nilus.source`:

```python
import nilus

@nilus.resource()
def fetch_data():
    for item in data:
        yield item

@nilus.source
def my_source_function(uri, table, **kwargs):
    return fetch_data()
```

* Yield **one row or document at a time**, with a stable shape.
* Return a **tuple of resources** when the source creates multiple destination tables.
* Use per-resource `write_disposition` when `handles_incrementality()` returns `True`.

```python
@nilus.resource(write_disposition="replace")
def users():
    yield from fetch_users()

@nilus.resource(write_disposition="append")
def activities():
    yield from fetch_activities()

@nilus.source
def multi_resource_source(uri, table, **kwargs):
    return users(), activities()
```

{% hint style="info" %}
Each resource becomes its own table in the destination **schema** named by `sink.options.dest_table`.
{% endhint %}

#### URI format

```
custom://<SourceClassName>?<option>=<value>
```

| Input                       | Where it comes from                          | How to read it                                                                                 |
| --------------------------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| Class to load               | URI host (`custom://MyCustomSource`)         | Must match the Python class name exactly.                                                      |
| `uri`                       | Full `source.address`                        | Parse query parameters with `urllib.parse`.                                                    |
| `table`                     | `source.options.source_table`                | Logical resource name for this run. Keep it stable.                                            |
| `**kwargs`                  | Pipeline knobs Nilus already understands     | `incremental_key`, `interval_start`, `interval_end`, `page_size`, and related extract options. |
| Extra `source.options` keys | Forwarded as uppercase environment variables | For example, `source.options.api_key` becomes `API_KEY`.                                       |

{% hint style="info" %}
Use the URI for connection-level or source-class parameters, and `source.options` for the resource-level options the custom source expects.
{% endhint %}

Parse connector-specific settings from the URI:

```python
from urllib.parse import parse_qs, urlparse

def nilus_source(self, uri: str, table: str, **kwargs):
    params = parse_qs(urlparse(uri).query)
    api_url = params.get("api_url", [None])[0]
    return my_source_function(uri=uri, table=table, api_url=api_url, **kwargs)
```

Project secrets into the URI with `{ENV_VAR}` placeholders and `spec.use.projection`. Do **not** hardcode credentials. See [Secrets and projections](https://v2.dataos.info/references/resources/nilus/concepts/secrets-and-projections.md).

```yaml
source:
  address: custom://MyCustomSource?api_key={API_KEY}&endpoint=events
```

#### Incremental loading

Return `True` from `handles_incrementality()` and persist a cursor on the resource state. Nilus stores that state between runs.

```python
import nilus
from nilus import CustomSource

class MyIncrementalSource(CustomSource):
    def handles_incrementality(self) -> bool:
        return True

    def nilus_source(self, uri: str, table: str, **kwargs):
        return fetch_incremental_data()

@nilus.resource()
def fetch_incremental_data():
    state = nilus.current.resource_state()
    last_id = state.get("last_id")
    data = get_data_after_id(last_id)
    if data:
        state["last_id"] = data[-1]["id"]
    for item in data:
        yield item
```

Store only the minimum cursor needed to resume safely. Leave `handles_incrementality()` as `False` when the sink strategy controls the load.

#### Pagination and errors

Yield pages as you fetch them. Close connections in `finally`. Re-raise after logging.

```python
@nilus.resource()
def fetch_large_dataset(batch_size=1000):
    page = 1
    has_more = True
    while has_more:
        data, has_more = get_paginated_data(page=page, size=batch_size)
        for item in data:
            yield item
        page += 1
```

### **Add Python dependencies**

Add a `requirements.txt` beside the `*.py` files in `baseDir` for packages not already in the Nilus image. Nilus runs `pip install -r requirements.txt` at startup.

{% hint style="warning" %}
List **only** extra packages your connector needs. Do **not** copy the Nilus image requirements. Reinstalling bundled packages can conflict with the runtime.
{% endhint %}

`requests` is already available as `nilus.sources.helpers.requests` or the image's `requests` package.

### Repository layout

```
my-custom-sources/          # spec.repo.baseDir
├── random_users.py         # resources + @nilus.source
├── nilus_custom_source.py  # CustomSource subclass
└── requirements.txt        # optional extra deps only
```

Import siblings by module name:

```python
from random_users import random_user_source
from nilus import CustomSource
```

### **Configure repository sync and credentials**

| Field                 | Required           | Description                                                                   |
| --------------------- | ------------------ | ----------------------------------------------------------------------------- |
| `spec.repo.url`       | Yes                | Git URL of the repository that contains your custom source code.              |
| `spec.repo.baseDir`   | Yes                | Directory holding the top-level `*.py` files and optional `requirements.txt`. |
| `spec.repo.syncFlags` | No                 | Extra git-sync flags. Set `--ref=` to pin a branch, tag, or commit.           |
| `spec.repo.secretId`  | Private repos only | DataOS secret as `<workspace>:<secret-name>`.                                 |

#### Pinning a branch, tag, or commit (`syncFlags`)

Without `syncFlags`, git-sync clones the default branch. Pin an explicit ref so every run uses the same code:

```yaml
spec:
  repo:
    url: https://github.com/your-org/custom-connectors
    baseDir: connectors/custom-source
    syncFlags:
      - --ref=main           # branch
      # - --ref=v1.2.0       # tag
      # - --ref=<commit-sha> # commit
```

#### Authenticating a private repo (`secretId`) <a href="#authenticating-a-private-repo-secretid" id="authenticating-a-private-repo-secretid"></a>

For a private repository, store the git credentials in a DataOS secret and reference it from `spec.repo.secretId`. Nilus projects that secret into the git-sync container, which reads exactly two keys:

| Key                | Description                                                          |
| ------------------ | -------------------------------------------------------------------- |
| `GITSYNC_USERNAME` | Git username, or token username such as `x-token-auth` on Bitbucket. |
| `GITSYNC_PASSWORD` | Password, personal access token, or app password.                    |

1. Create the secret (`type: secret`, `key-value`):

```yaml
name: custom-source-repo-secret
version: v2alpha
type: secret
description: Git read credentials for custom source repo sync
spec:
  type: key-value
  data:
    GITSYNC_USERNAME: <git-username>
    GITSYNC_PASSWORD: <personal-access-token>
```

2. Reference it from the pipeline as `<workspace>:<secret-name>` (the workspace the secret was created in):

```yaml
spec:
  repo:
    url: https://bitbucket.org/your-org/custom-connectors
    baseDir: packages/custom-source
    syncFlags:
      - --ref=main
    secretId: public:custom-source-repo-secret
```

A public repository needs `url` and `baseDir`, plus optional `syncFlags`.

{% hint style="info" %}
`spec.repo.secretId` authenticates **repo sync only**. Source and sink credentials still come from the `custom://` URI, `source.options`, a depot, or `spec.use.projection`. See [Secrets and projections](https://v2.dataos.info/references/resources/nilus/concepts/secrets-and-projections.md).
{% endhint %}

### Sample Nilus config

```yaml
name: custom-source-pipeline
version: v1alpha
type: nilus
spec:
  type: batch
  compute: universe-compute
  repo:
    url: https://github.com/your-org/custom-connectors
    baseDir: connectors/custom-source
    syncFlags:
      - --ref=main
    # secretId: public:custom-source-repo-secret  # private repo only
  source:
    address: custom://RandomUserSource?account_id=acme
    options:
      source_table: users
  sink:
    address: dataos://lakehouse?purpose=rw
    options:
      dest_table: raw      # Specify only destination schema
      incremental_strategy: append
```

{% hint style="warning" %}
For custom sources, `sink.options.dest_table` is the destination **schema** only. Resource functions define the actual table names. `raw.orders` is misleading because `orders` has no effect.
{% endhint %}

### Example in practice

Two files live in `baseDir`. `random_users.py` yields rows. `nilus_custom_source.py` is the class Nilus imports.

`random_users.py`:

```python
import nilus

dummy_data = [
    {"id": 1, "email": "aisha.patel@example.com", "city": "Bengaluru"},
    {"id": 2, "email": "rahul.sharma@example.com", "city": "Mumbai"},
    {"id": 3, "email": "neha.reddy@example.com", "city": "Chennai"},
]

@nilus.resource()
def fetch_random_users():
    for row in dummy_data:
        yield row

@nilus.source
def random_user_source(uri, table, **kwargs):
    return fetch_random_users()
```

`nilus_custom_source.py`:

```python
from random_users import random_user_source
from nilus import CustomSource

class RandomUserSource(CustomSource):
    def handles_incrementality(self) -> bool:
        return False

    def nilus_source(self, uri: str, table: str, **kwargs):
        return random_user_source(uri, table, **kwargs)
```

Pipeline address: `custom://RandomUserSource`. Destination tables land in schema `raw`. The resource name becomes the table name.

### Behavior and capabilities

* **Pipeline mode**: `spec.type: batch` only.
* **Code loading**: top-level `*.py` in `spec.repo.baseDir`; class name matches the URI host.
* **Object model**: resources own table names and row shape.
* **Destination naming**: `dest_table` is the schema; resource names are the tables.
* **Incrementality**: source state wins when `handles_incrementality()` returns `True`.

### Troubleshooting

| Symptom                                     | Likely cause                                                       | Resolution                                                                      |
| ------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------- |
| `custom baseDir not set in repo`            | Manifest has no `spec.repo` / `baseDir`.                           | Add `spec.repo.url` and `spec.repo.baseDir`.                                    |
| `Custom source 'X' not found. Available: …` | URI host does not match a subclass in `baseDir`.                   | Match the class name exactly. Keep the class in a top-level `*.py` file.        |
| Runtime cannot import the module            | `baseDir` is wrong, or a sibling import uses a laptop-only path.   | Import siblings as `from random_users import …`.                                |
| Repository clone fails                      | Runtime cannot reach or authenticate to Git.                       | Set `spec.repo.secretId` with `GITSYNC_USERNAME` / `GITSYNC_PASSWORD`.          |
| Pipeline runs against stale code            | No ref pinned.                                                     | Set `spec.repo.syncFlags: ["--ref=main"]`.                                      |
| `pip` warning on `requirements.txt`         | File lists bundled packages or a bad pin.                          | Ship only extra dependencies.                                                   |
| Output schema changes unexpectedly          | Yielded dictionaries lack a stable shape.                          | Normalize rows before `yield`.                                                  |
| Expected table name missing / extra table   | `dest_table` included a table segment, or a resource name changed. | Use schema-only `dest_table`; keep resource names stable.                       |
| Pipeline restarts from the beginning        | No cursor, or source-owned state is disabled.                      | Implement `resource_state()` and return `True` from `handles_incrementality()`. |

### Best practices

* Keep resources, the `CustomSource` wrapper, and helpers in separate files.
* Validate parameters before opening connections.
* Make retries and pagination explicit.
* Never hardcode credentials. Use secret projection in the URI.
* Test a bounded sample before scheduling production runs.
* Document every URI query parameter beside the class.

### Related docs

* [Custom query (SQL)](https://v2.dataos.info/references/resources/nilus/batch/custom-sources/custom-query-sql-sources.md)
* [Secrets and projections](https://v2.dataos.info/references/resources/nilus/concepts/secrets-and-projections.md)
* [Batch pipeline config](https://v2.dataos.info/references/resources/nilus/batch/pipeline-config.md)
* [Batch sources](https://v2.dataos.info/references/resources/nilus/batch/batch-sources.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://v2.dataos.info/references/resources/nilus/batch/custom-sources/creating-custom-source.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
