Load KSEF API data to DuckDB
Build a KSEF API to DuckDB pipeline with your coding agent. One prompt scaffolds it with the dltHub AI harness, plus the KSEF API API base URL, auth, endpoints, and incremental loading.
The National System of e-Invoices (KSeF) API allows taxpayers to issue, receive, and store structured invoices programmatically. Everything needed to build a working KSEF API → DuckDB pipeline is on this page: the API's base URL, authentication, endpoints, pagination and incremental field — plus a prompt that hands the whole job to your coding agent.
Build your KSEF API to DuckDB pipeline
Paste this prompt into Claude, Codex, or Cursor. The agent does the rest.
PromptRunuvx dlthub-init@latestto build a pipeline from KSEF API to DuckDB and run it on dltHub
That scaffolds a dltHub workspace and installs the dltHub AI harness — the project rules, the secrets-management skill, and the dlt MCP server your agent needs to work safely. From there it reads the KSEF API API, proposes the endpoints to load, then writes, runs and validates the pipeline while you review rather than type. Credentials are inspected through MCP tools, so your agent never reads secrets.toml itself. How the LLM-native workflow works →
Prefer to write it yourself? Every fact the agent uses is below.
KSEF API API at a glance
| Base URL | https://api.ksef.mf.gov.pl/v2 |
| Example endpoint | GET api/v2/auth/sessions |
| Records found at | invoices |
| Authentication | requests require a Bearer token in the Authorization header — sent in the Authorization header, prefixed Bearer |
| Pagination | Cursor-based via x-continuation-token, page size via pageSize |
| Incremental field | x-continuation-token |
| API reference | https://api-demo.ksef.mf.gov.pl/docs/v2/index.html |
These values come from the KSEF API API reference — the authoritative source if anything here looks out of date.
How do I authenticate with the KSEF API API?
Authentication is a multi-step process involving a challenge, encryption, and token redemption. After obtaining a session token, include it in the 'Authorization' header as a 'Bearer' token.
1. Get your credentials
- Navigate to the official KSeF Taxpayer Application portal at https://ksef.mf.gov.pl/. 2. Log in using a qualified electronic signature (kwalifikowany podpis elektroniczny) or a Trusted Profile (Profil Zaufany). 3. Ensure the login is performed by a person authorized to represent the company (e.g., a management board member listed in the KRS register). 4. Navigate to the 'Zarządzanie tokenami' (Token Management) section within the portal. 5. Click 'Generuj token' (Generate token). 6. Provide a descriptive name for the token, select the required permissions (e.g., 'invoicing' for sending/receiving invoices), and set the validity period (up to 365 days). 7. Copy and securely store the generated KSeF token, as it will be required for configuring your integration.
2. Add them to .dlt/secrets.toml
[sources.ksef_api_source] token = "REPLACE_ME"
dlt reads this file automatically at runtime. With the harness, the setup-secrets skill prompts you for the values and never handles the raw credential in chat. For production, see setting up credentials with dlt.
What KSEF API data can I load into DuckDB?
These are the KSEF API endpoints dlt can load into DuckDB:
| Resource | Endpoint | Method | Data selector | Description |
|---|---|---|---|---|
| active_sessions | /api/v2/auth/sessions | GET | Get list of active sessions | |
| sessions | /api/v2/sessions | GET | Get list of sessions matching criteria | |
| session_invoices | /api/v2/sessions/{referenceNumber}/invoices | GET | Get invoices for a session | |
| session_details | /api/v2/sessions/{referenceNumber} | GET | Get details of a session | |
| invoice_metadata | /api/v2/invoices/query/metadata | POST | Query metadata of invoices |
How do I load only new KSEF API records?
KSEF API exposes x-continuation-token on api/v2/auth/sessions, so dlt can request only the records that changed since the last run. Set it as the cursor_path and dlt tracks the high-water mark for you between runs.
{"name": "active_sessions", "endpoint": { "path": "api/v2/auth/sessions", "data_selector": "invoices", "incremental": {"cursor_path": "x-continuation-token", "initial_value": "2024-01-01T00:00:00Z"}, }}
On the first run dlt loads everything from initial_value; on every run after that it requests only what changed and appends with write_disposition="merge" if you set a primary key. See incremental loading.
What does the generated KSEF API pipeline look like?
A standard dlt REST API pipeline — the same code you would write by hand, loading auth/challenge and auth/ksef-token from the KSEF API API into DuckDB:
import dlt from dlt.sources.rest_api import RESTAPIConfig, rest_api_resources @dlt.source def ksef_api_source(token=dlt.secrets.value): config: RESTAPIConfig = { "client": { "base_url": "https://api.ksef.mf.gov.pl/v2", "auth": {"type": "bearer", "token": token}, }, "resources": [ {"name": "active_sessions", "endpoint": {"path": "api/v2/auth/sessions", "data_selector": "invoices"}}, {"name": "sessions", "endpoint": {"path": "api/v2/sessions", "data_selector": "invoices"}} ], } yield from rest_api_resources(config) def load_ksef_api_to_duckdb() -> None: pipeline = dlt.pipeline( pipeline_name="ksef_api_pipeline", destination="duckdb", dataset_name="ksef_api_data", ) load_info = pipeline.run(ksef_api_source()) print(load_info) if __name__ == "__main__": load_ksef_api_to_duckdb()
Run it with python ksef_api_pipeline.py. The agent iterates on this until it loads cleanly — you review and approve, rather than write it from scratch.
How do I query KSEF API data in DuckDB?
dlt creates one table per resource. Query the loaded data with Python or SQL — or ask your agent to, through the MCP server's execute_sql_query tool.
Python (pandas DataFrame):
import dlt data = dlt.pipeline("ksef_api_pipeline").dataset() df = data.sessions.df() print(df.head())
SQL:
SELECT * FROM ksef_api_data.sessions LIMIT 10;
See querying your data with dataset and exploring it in marimo notebooks.
How do I deploy the KSEF API to DuckDB pipeline in production?
The pipeline runs locally, which is ideal for prototyping and one-off analysis. When you need it on a schedule, monitored on every load, and shared with your team, deploy the same dlt code on the dltHub platform — no infrastructure to maintain. The prompt above already ends with "run it on dltHub", so your agent can take it there directly.
- Deploy & schedule — run the pipeline as a managed job with automatic retries.
- Monitor — observable job queues, alerting, and load metrics for every run.
- Transform — promote raw KSEF API loads into governed, documented models.
- Visualize & share — explore data in notebooks and publish live dashboards instead of static screenshots.
What other destinations can I load KSEF API data to?
dlt loads into any of these — only the destination argument changes:
| Destination | Example value |
|---|---|
| PostgreSQL | "postgres" |
| BigQuery | "bigquery" |
| Snowflake | "snowflake" |
| Redshift | "redshift" |
| Databricks | "databricks" |
| Filesystem (S3, GCS, Azure) | "filesystem" |
Set dlt.pipeline(destination="snowflake") and add credentials in .dlt/secrets.toml. On the dltHub platform the same pipeline runs against a managed Iceberg lakehouse. See the full destinations list.
Next steps
Was this page helpful?
Community Hub
Need more dlt context for KSEF API to DuckDB?
Request dlt skills, commands, AGENT.md files, and AI-native context.