pip install ksef2Or with uv:
uv add ksef2Requires Python 3.12+.
The SDK currently supports KSeF OpenAPI version 2.3.0.
from datetime import datetime, timedelta, timezone
from pathlib import Path
from ksef2 import Client, Environment, FormSchema
from ksef2.domain.models import InvoicesFilter
NIP = "5261040828"
client = Client(Environment.TEST)
# Authenticate (XAdES — TEST environment)
auth = client.authentication.with_test_certificate(nip=NIP)
with auth.online_session(form_code=FormSchema.FA3) as session:
# Send an invoice
result = session.send_invoice(invoice_xml=Path("invoice.xml").read_bytes())
print(result.reference_number)
# Wait until KSeF finishes processing it
status = session.wait_for_invoice_ready(
invoice_reference_number=result.reference_number
)
print(status.status.description)
# Export invoices (no session required)
export = auth.invoices.schedule_export(
filters=InvoicesFilter(
role="seller",
date_type="issue_date",
date_from=datetime.now(tz=timezone.utc) - timedelta(days=1),
date_to=datetime.now(tz=timezone.utc),
amount_type="brutto",
),
)
# Download the exported package
package = auth.invoices.wait_for_export_package(reference_number=export.reference_number)
for path in auth.invoices.fetch_package(
package=package,
export=export,
target_directory="downloads",
):
print(f"Downloaded: {path}")Runnable TEST examples:
scripts/examples/quickstart.pyandscripts/examples/invoices/send_query_export_download.py
- Typed public API for authentication, sessions, invoices, tokens, permissions, limits, certificates, and PEPPOL
- XAdES and KSeF token authentication through a single
Client.authenticationentry point - Online and batch sessions with resumable session state for long-running jobs
- Built-in encryption helpers for invoice sending and export package decryption
- TEST environment tooling including self-signed certificates and disposable test data contexts
- Runnable examples and guide docs for the common KSeF workflows
Client exposes both authenticated and public entry points:
client.authenticationfor XAdES and KSeF-token authenticationclient.encryptionfor public KSeF encryption certificatesclient.peppolfor public PEPPOL provider queriesclient.testdatafor TEST-only data setup and cleanup helpers
The SDK exposes structlog loggers via ksef2.logging, but it does not configure
global logging on import. Applications can either configure structlog
themselves or use the provided helper:
from ksef2.logging import configure_logging, get_logger
configure_logging(level="INFO")
logger = get_logger("my_app")
logger.info("Starting KSeF sync", environment="test")SDK internals use the same logger factory, so once the application configures
structlog, events emitted by ksef2 follow the same handlers and rendering.
The TEST environment accepts self-signed certificates generated by the SDK. DEMO and PRODUCTION require a certificate issued by MCU — use the provided helpers to load it:
from ksef2 import Client, Environment
from ksef2.core.xades import (
load_certificate_and_key_from_p12,
load_certificate_from_pem,
load_private_key_from_pem,
)
cert = load_certificate_from_pem("cert.pem") # downloaded from MCU
key = load_private_key_from_pem("key.pem")
auth = Client(Environment.DEMO).authentication.with_xades(
nip="5261040828",
cert=cert,
private_key=key,
)
cert, key = load_certificate_and_key_from_p12("cert.p12", password=b"secret")Use this when you already have a KSeF token issued for the target context:
from ksef2 import Client
client = Client() # uses production environment by default
auth = client.authentication.with_token(
ksef_token="your-ksef-token",
nip="5261040828",
)
print(auth.access_token)After with_xades() or with_token(), you get an AuthenticatedClient. Its main entry points are:
auth.online_session()andauth.batch_session()for invoice sessionsauth.batchfor end-to-end batch package preparation, upload, and status pollingauth.invoicesfor metadata queries, exports, downloads, and package fetchesauth.tokensfor KSeF authorization token lifecycle managementauth.permissionsfor grant, revoke, and query operationsauth.certificatesfor certificate enrollment, retrieval, query, and revocationauth.sessionsfor active authentication session managementauth.invoice_sessionsfor historical online and batch invoice sessionsauth.limitsfor TEST-environment limit inspection and overrides
Invoice sending stays on auth.online_session() because it depends on an opened KSeF session and its session-specific encryption keys. Batch ZIP preparation and upload live on auth.batch, while metadata queries, exports, and downloads live on auth.invoices because they only require the authenticated bearer context.
Common examples:
from datetime import datetime, timedelta, timezone
from ksef2.domain.models import InvoicesFilter
token = auth.tokens.generate(
permissions=["invoice_read", "invoice_write"],
description="API integration token",
)
print(token.reference_number, token.token)
limits = auth.limits.get_context_limits()
print(limits.online_session.max_invoices)
sessions = auth.sessions.query(page_size=10)
print(len(sessions.items))
metadata = auth.invoices.query_metadata(
filters=InvoicesFilter(
role="seller",
date_type="issue_date",
date_from=datetime.now(tz=timezone.utc) - timedelta(days=7),
date_to=datetime.now(tz=timezone.utc),
amount_type="brutto",
)
)
print(len(metadata.invoices))For the full API surface, see the guide docs below.
Run examples as modules with uv run -m ...; direct execution by file path is not supported.
scripts/examples/quickstart.py- minimal TEST-environment invoice sendscripts/examples/auth/auth_xades.py- XAdES authenticationscripts/examples/auth/auth_token.py- KSeF token authenticationscripts/examples/invoices/send_batch.py- staged batch upload with explicit session lifecyclescripts/examples/invoices/submit_batch.py- one-shot batch submission flowscripts/examples/invoices/send_query_export_download.py- send, inspect, export, and download invoicesscripts/examples/peppol/query_providers.py- query public PEPPOL providersscripts/examples/scenarios/download_purchase_invoices.py- multi-buyer purchase-invoice export scenarioscripts/examples/session/session_resume.py- persist and resume an online session
just sync # Install all dependencies (including dev)
just test # Run unit tests
just test-coverage # Run unit tests with coverage and update test-coverage.json
just release-check # Run the pre-release verification suite and build artifacts
just regenerate-models # Regenerate OpenAPI modelsjust integration # Run integration tests (requires KSEF credentials in .env)
just coverage # Calculate API coverage (updates coverage.json)
just fetch-spec # Fetch latest OpenAPI spec from KSeFThe SDK covers 73 of 73 KSeF API endpoints (100%). See feature docs for details:
- Authentication — XAdES, token auth, session management
- Encryption — public KSeF encryption certificates
- Invoices — send, download, query, export
- Sessions — online/batch sessions, resume support
- Tokens — generate and manage KSeF authorization tokens
- Permissions — grant/query permissions for persons and entities
- Certificates — enroll, query, revoke KSeF certificates
- Limits — query and modify API rate limits
- PEPPOL — query registered PEPPOL providers
- Test Data — create test subjects, manage test environment
The SDK is still in the pre-1.0.0 stabilization phase.
- Track release notes in CHANGELOG.md
- Run
just release-checkbefore publishing a release - Expect
0.xminor releases to contain public API cleanup when needed