Skip to main content

Client SDK for KSeF API v2

Project description

KSeF Client Python

CI PyPI - License PyPI - Version

ksef-client-python to produkcyjne SDK do integracji z KSeF API, publikowane na PyPI jako ksef-client.

Projekt odwzorowuje oficjalne przepływy KSeF i zapewnia spójny model pracy w dwóch warstwach:

  • SDK Python API do integracji aplikacyjnych,
  • CLI do diagnostyki i operacji bez pisania kodu.

🔄 Kompatybilność

Aktualna kompatybilność: KSeF API v2.3.0 (api-changelog.md).

🧭 Spis treści

✅ Zakres funkcjonalny

  • Klienci API: KsefClient, AsyncKsefClient, mapujące endpointy KSeF.
  • Uwierzytelnianie: token KSeF i podpis XAdES, w tym XadesKeyPair dla PKCS#12 lub PEM.
  • Workflows wysyłki: sesje online i batch z ZIP, partiami i pre-signed URL.
  • Eksport/pobieranie: obsługa paczek i narzędzi do odszyfrowania/rozpakowania.
  • Latarnia: publiczne endpointy dostępności KSeF (client.lighthouse, ksef lighthouse ...).
  • Narzędzia pomocnicze: AES/ZIP/Base64Url, linki weryfikacyjne, QR.
  • CLI ksef: szybka ścieżka od konfiguracji do pierwszych operacji: init -> auth -> invoice/send/upo.

📦 Instalacja

Wymagania: Python >= 3.10.

Podstawowe SDK:

pip install ksef-client

SDK + CLI:

pip install "ksef-client[cli]"

Dodatki opcjonalne:

pip install "ksef-client[xml,qr,cli]"
  • xml - podpis XAdES z lxml i xmlsec
  • qr - generowanie PNG z kodami QR przez qrcode i pillow
  • cli - interfejs wiersza poleceń oparty o typer, rich, keyring

🚀 Szybki start: CLI

CLI ksef zostało zaprojektowane tak, aby skrócić wejście w SDK do minimum.

  1. Utwórz i aktywuj profil:
ksef init --non-interactive --name demo --env DEMO --context-type nip --context-value <NIP> --set-active
  1. Zaloguj się tokenem i sprawdź sesję:
ksef auth login-token --ksef-token <KSEF_TOKEN>
ksef auth status
ksef profile show

Alternatywnie, logowanie certyfikatem XAdES:

ksef auth login-xades --pkcs12-path ./cert.p12 --pkcs12-password <HASLO_CERTYFIKATU>
ksef auth status
  1. Wykonaj pierwsze operacje:
ksef invoice list --from 2026-01-01 --to 2026-01-31
ksef send online --invoice ./fa.xml --wait-upo --save-upo ./out/upo-online.xml
ksef invoice download --ksef-number <KSEF_NUMBER> --out ./out/

Najważniejsze grupy komend:

  • onboarding/profiles: init, profile ...
  • auth: auth login-token, auth login-xades, auth status, auth refresh, auth logout
  • operacje: invoice ..., send ..., upo ..., export ...
  • diagnostyka: health check
  • latarnia: lighthouse status, lighthouse messages
    • komendy Latarni sa publiczne (dzialaja bez logowania; bez profilu domyslnie uzywana jest latarnia test)

Pełna specyfikacja CLI: docs/cli/README.md

🧩 Szybki start: SDK

Minimalny przebieg integracji:

  • uzyskanie access_token przez token KSeF lub XAdES,
  • wykonanie pierwszego wywołania API, np. listowania metadanych faktur.
from ksef_client import KsefClient, KsefClientOptions, KsefEnvironment
from ksef_client.services.workflows import AuthCoordinator

with KsefClient(KsefClientOptions(base_url=KsefEnvironment.DEMO.value)) as client:
    token_cert_pem = ...  # usage: KsefTokenEncryption, client.security.get_public_key_certificates

    access_token = AuthCoordinator(client.auth).authenticate_with_ksef_token(
        token=KSEF_TOKEN,
        public_certificate=token_cert_pem,
        context_identifier_type="nip",
        context_identifier_value="5265877635",
    ).tokens.access_token.token

    metadata = client.invoices.query_invoice_metadata(
        {...},
        access_token=access_token,
        page_offset=0,
        page_size=10,
        sort_order="Desc",
    )

🔐 Najważniejsze scenariusze SDK

Autoryzacja tokenem KSeF

tokens = AuthCoordinator(client.auth).authenticate_with_ksef_token(
    token=KSEF_TOKEN,
    public_certificate=token_cert_pem,
    context_identifier_type="nip",
    context_identifier_value="5265877635",
).tokens

Autoryzacja certyfikatem XAdES

Wymaga dodatku xml: pip install "ksef-client[xml]".

from ksef_client.services import XadesKeyPair

key_pair = XadesKeyPair.from_pkcs12_file(pkcs12_path="cert.p12", pkcs12_password="***")
tokens = AuthCoordinator(client.auth).authenticate_with_xades_key_pair(
    key_pair=key_pair,
    context_identifier_type="nip",
    context_identifier_value="5265877635",
    subject_identifier_type="certificateSubject",
    enforce_xades_compliance=False,
).tokens

Wysyłka faktury w sesji online

from ksef_client.services.workflows import OnlineSessionWorkflow

send_result = OnlineSessionWorkflow(client.sessions).send_invoice(
    session_reference_number=session_reference_number,
    invoice_xml=invoice_xml_fa3_bytes,
    encryption_data=encryption_data,
    access_token=access_token,
)

Wysyłka wsadowa batch ZIP

from ksef_client.services.workflows import BatchSessionWorkflow

session_reference_number = BatchSessionWorkflow(client.sessions, client.http_client).open_upload_and_close(
    form_code={"systemCode": "FA (3)", "schemaVersion": "1-0E", "value": "FA"},
    zip_bytes=zip_bytes,
    public_certificate=symmetric_cert_pem,
    access_token=access_token,
    parallelism=4,
)

Odczyt statusu Latarni

status = client.lighthouse.get_status()
messages = client.lighthouse.get_messages()

📚 Dokumentacja

Dokumentacja SDK znajduje się w docs/:

🧪 Testy i jakość

Python E2E TEST token Python E2E TEST cert Python E2E DEMO token Python E2E DEMO cert

Instalacja zależności developerskich:

pip install -r requirements-dev.txt

Uruchomienie testów:

pytest

Uruchomienie testów z kontrolą pokrycia:

pytest --cov=ksef_client --cov-report=term-missing --cov-fail-under=100

Testy E2E w tests/test_e2e_token_flows.py wymagają osobnej konfiguracji środowiska i danych dostępowych.

🤝 Kontrybucja

Wkład w rozwój projektu przyjmowany jest w formie pull requestów i zgłoszeń Issues.

Rekomendowany przebieg:

  • opisz problem lub propozycję zmiany w Issue,
  • pracuj w osobnej gałęzi,
  • dołącz testy dla zmian zachowania,
  • utrzymaj jakość: pytest, pytest --cov=ksef_client --cov-fail-under=100,
  • opisz zakres i uzasadnienie zmian w PR.

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

ksef_client-0.8.0.tar.gz (102.7 kB view details)

Uploaded Source

Built Distribution

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

ksef_client-0.8.0-py3-none-any.whl (97.7 kB view details)

Uploaded Python 3

File details

Details for the file ksef_client-0.8.0.tar.gz.

File metadata

  • Download URL: ksef_client-0.8.0.tar.gz
  • Upload date:
  • Size: 102.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for ksef_client-0.8.0.tar.gz
Algorithm Hash digest
SHA256 c8e95a6c2a91a7f2bf85e148faba5cdbdba2f228697369eb0e8be2e1e9e5f294
MD5 7f6dc14ea22a3a9ead1301a880b358bc
BLAKE2b-256 3a221249135540d2ffe5fcc933009f4e2ab48986b4f2495d09d647b9d4b63e0b

See more details on using hashes here.

Provenance

The following attestation bundles were made for ksef_client-0.8.0.tar.gz:

Publisher: publish-pypi.yml on smekcio/ksef-client-python

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

File details

Details for the file ksef_client-0.8.0-py3-none-any.whl.

File metadata

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

File hashes

Hashes for ksef_client-0.8.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fedf30d4f3a694f766071b56adc209b729ef354942e50606de6069bf215c6c0a
MD5 b8398fe1c0da9c6f33b1565020425c3f
BLAKE2b-256 d1ce8c430d124a003888aee9490c5eb408b8fdd6c6d3d5d67d20429b0097700a

See more details on using hashes here.

Provenance

The following attestation bundles were made for ksef_client-0.8.0-py3-none-any.whl:

Publisher: publish-pypi.yml on smekcio/ksef-client-python

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