Skip to main content

Python SDK and Tools for Poland's KSeF (Krajowy System e-Faktur) API

Project description

KSeF Toolkit

Python SDK for Poland's KSeF (Krajowy System e-Faktur) v2 API.

API Coverage Python Version Integration Tests
beartype pre-commit Ruff License: MIT

Installation

pip install ksef2

Or with uv:

uv add ksef2

Requires Python 3.12+.

Supported OpenAPI Version

The SDK currently supports KSeF OpenAPI version 2.2.1.

Quick Start

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.py and scripts/examples/invoices/send_query_export_download.py

Features

  • Typed public API for authentication, sessions, invoices, tokens, permissions, limits, certificates, and PEPPOL
  • XAdES and KSeF token authentication through a single Client.authentication entry 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

Root Client

Client exposes both authenticated and public entry points:

  • client.authentication for XAdES and KSeF-token authentication
  • client.encryption for public KSeF encryption certificates
  • client.peppol for public PEPPOL provider queries
  • client.testdata for TEST-only data setup and cleanup helpers

Logging

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.

XAdES on DEMO / PRODUCTION (MCU certificate)

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")

Token Authentication

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)

Authenticated Client

After with_xades() or with_token(), you get an AuthenticatedClient. Its main entry points are:

  • auth.online_session() and auth.batch_session() for invoice sessions
  • auth.batch for end-to-end batch package preparation, upload, and status polling
  • auth.invoices for metadata queries, exports, downloads, and package fetches
  • auth.tokens for KSeF authorization token lifecycle management
  • auth.permissions for grant, revoke, and query operations
  • auth.certificates for certificate enrollment, retrieval, query, and revocation
  • auth.sessions for active authentication session management
  • auth.invoice_sessions for historical online and batch invoice sessions
  • auth.limits for 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.

Examples

Run examples as modules with uv run -m ...; direct execution by file path is not supported.

Development

just sync          # Install all dependencies (including dev)
just test          # Run unit tests
just release-check # Run the pre-release verification suite and build artifacts
just regenerate-models  # Regenerate OpenAPI models

Other commands

just 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 KSeF

API Coverage

The 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

Stability And Releases

The SDK is still in the pre-1.0.0 stabilization phase.

  • Track release notes in CHANGELOG.md
  • Run just release-check before publishing a release
  • Expect 0.x minor releases to contain public API cleanup when needed

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ksef2-0.9.0.tar.gz (1.9 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ksef2-0.9.0-py3-none-any.whl (258.7 kB view details)

Uploaded Python 3

File details

Details for the file ksef2-0.9.0.tar.gz.

File metadata

  • Download URL: ksef2-0.9.0.tar.gz
  • Upload date:
  • Size: 1.9 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for ksef2-0.9.0.tar.gz
Algorithm Hash digest
SHA256 53f9b56f7f06eff4241934fa6f6ed9ce437c474601920d3709ec045e7c15c35e
MD5 eb04aa024fc6311593bc8aa74434c962
BLAKE2b-256 fe017154d357fe3e7b16574bfbac29301f6967555bbbd30e2d6dc114cf95f1e8

See more details on using hashes here.

Provenance

The following attestation bundles were made for ksef2-0.9.0.tar.gz:

Publisher: publish.yml on artpods56/ksef2

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ksef2-0.9.0-py3-none-any.whl.

File metadata

  • Download URL: ksef2-0.9.0-py3-none-any.whl
  • Upload date:
  • Size: 258.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for ksef2-0.9.0-py3-none-any.whl
Algorithm Hash digest
SHA256 50f8b4bd18fdb8e9556d89f9cbfd018f6b10fdf0e84ce2bb7878f1335371afe4
MD5 79da8c5c342e85944a2e9b4a215c8591
BLAKE2b-256 f7f9a5492340d776fff6ca4a9fff676f916e20622340454e571a3dec3e835b3c

See more details on using hashes here.

Provenance

The following attestation bundles were made for ksef2-0.9.0-py3-none-any.whl:

Publisher: publish.yml on artpods56/ksef2

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page