Public sync and async client entry points.
Classes
AsyncAuthClient
Import: from ksef2.clients import AsyncAuthClient
class AsyncAuthClientAsyncAuthClient(
transport: AsyncMiddleware,
certificate_store: CertificateStoreProtocol,
environment: Environment = Environment.PRODUCTION,
transfer_transport: AsyncMiddleware | None = None,
auto_refresh_tokens: bool = True,
)Async entry point for creating authenticated SDK clients.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncAuthClient.resume
def resume(state: AuthenticationResumeState | str) -> AsyncAuthenticatedClientRehydrate an authenticated client from saved authentication state.
The client refreshes its access token automatically unless
TransportConfig.auto_refresh_tokens is False, so a state whose
access token has expired still works while its refresh token is valid.
Parameters
state(AuthenticationResumeState | str) — State previously exported from an authenticated client, or its JSON string.
Returns
AsyncAuthenticatedClient— An authenticated client bound to the saved tokens.
AsyncAuthClient.with_token
async def with_token(
*,
ksef_token: str,
nip: str,
context_type: ContextIdentifierType = 'nip',
timeout: float = 60.0,
poll_interval: float = 1.0,
) -> AsyncAuthenticatedClientAuthenticate with a KSeF token and return an authenticated client.
Parameters
ksef_token(str) — Token generated in KSeF for the target context.nip(str) — Context identifier value used for authentication.context_type(ContextIdentifierType) — Type of identifier represented bynip.timeout(float) — Maximum number of seconds to wait for authentication.poll_interval(float) — Delay in seconds between authentication status checks.
Returns
AsyncAuthenticatedClient— An authenticated client with redeemed access and refresh tokens.
Raises
NoCertificateAvailableError— If no valid token-encryption certificate is available.KSeFEncryptionError— If token encryption fails.KSeFAuthError— If authentication fails.KSeFAuthPollingTimeoutError— If polling exceedstimeout.
Example
client = AsyncClient(Environment.TEST)
auth = await client.authentication.with_token(
ksef_token="your-ksef-token",
nip="5261040828",
)AsyncAuthClient.with_xades
async def with_xades(
*,
nip: str,
cert: Certificate,
private_key: XAdESPrivateKey,
verify_chain: bool = False,
timeout: float = 60.0,
poll_interval: float = 1.0,
) -> AsyncAuthenticatedClientAuthenticate with an XAdES-signed challenge response.
Parameters
nip(str) — Taxpayer identifier embedded in the authentication request.cert(Certificate) — Signing certificate accepted by the target environment.private_key(XAdESPrivateKey) — RSA or EC private key used to sign the XAdES payload.verify_chain(bool) — Whether KSeF should verify the certificate chain.timeout(float) — Maximum number of seconds to wait for authentication.poll_interval(float) — Delay in seconds between authentication status checks.
Returns
AsyncAuthenticatedClient— An authenticated client with redeemed access and refresh tokens.
Raises
KSeFAuthError— If authentication fails.KSeFAuthPollingTimeoutError— If polling exceedstimeout.
Example
from ksef2.xades import load_certificate_from_pem, load_private_key_from_pem
client = AsyncClient(Environment.DEMO)
auth = await client.authentication.with_xades(
nip="5261040828",
cert=load_certificate_from_pem("company.pem"),
private_key=load_private_key_from_pem("company.key"),
)AsyncAuthClient.with_test_certificate
async def with_test_certificate(
*,
nip: str,
verify_chain: bool = False,
timeout: float = 60.0,
poll_interval: float = 1.0,
) -> AsyncAuthenticatedClientAuthenticate in the TEST environment using an SDK-generated certificate.
Parameters
nip(str) — NIP to authenticate as; the generated certificate is issued for it.verify_chain(bool) — Whether KSeF should verify the certificate chain.timeout(float) — Maximum number of seconds to wait for authentication.poll_interval(float) — Delay in seconds between authentication status checks.
Returns
AsyncAuthenticatedClient— An authenticated client for the NIP's context.
Raises
KSeFUnsupportedEnvironmentError— If the client is not configured for TEST.KSeFAuthError— If authentication fails.KSeFAuthPollingTimeoutError— If polling exceedstimeout.
Example
client = AsyncClient(Environment.TEST)
auth = await client.authentication.with_test_certificate(nip="5261040828")AsyncAuthClient.with_profile
async def with_profile(
name: str | None = None,
*,
config_path: str | Path | None = None,
timeout: float | None = None,
poll_interval: float | None = None,
verify_chain: bool = False,
) -> AsyncAuthenticatedClientAuthenticate with a local ksef2-cli profile.
Profile selection follows the CLI order: explicit name,
KSEF2_PROFILE, then active_profile from the local CLI config.
The profile environment must match the root client environment.
Parameters
name(str | None) — Profile name; whenNone,KSEF2_PROFILEand then the CLI's active profile are used.config_path(str | Path | None) — Path of theksef2-cliconfig file; the default location is used whenNone.timeout(float | None) — Maximum number of seconds to wait for authentication; defaults to the profile's polling settings, else 60.poll_interval(float | None) — Delay in seconds between authentication status checks; defaults to the profile's value, else 1.verify_chain(bool) — Whether KSeF should verify the certificate chain, for certificate-based profiles.
Returns
AsyncAuthenticatedClient— An authenticated client for the profile's context.
Raises
KSeFValidationError— If the profile's environment differs from the client's, or the profile is missing a required secret.KSeFAuthError— If authentication fails.KSeFAuthPollingTimeoutError— If polling exceedstimeout.
Example
client = AsyncClient(Environment.TEST)
auth = await client.authentication.with_profile("test-company")AsyncAuthClient.refresh
async def refresh(*, refresh_token: str) -> RefreshedTokenExchange a refresh token for a new access token.
Parameters
refresh_token(str) — Refresh token obtained during authentication.
Returns
RefreshedToken— A new access token with its expiry time.
AsyncAuthenticatedClient
Import: from ksef2.clients import AsyncAuthenticatedClient
class AsyncAuthenticatedClientAsyncAuthenticatedClient(
transport: AsyncMiddleware,
auth_tokens: AuthTokens,
certificate_store: CertificateStoreProtocol,
environment: Environment = Environment.PRODUCTION,
transfer_transport: AsyncMiddleware | None = None,
refresh_access_token: AsyncRefresh | None = None,
)Authenticated async entry point for KSeF operations.
Catch KSeFException for SDK-classified failures raised by authenticated
branches, and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncAuthenticatedClient.auth_tokens (property)
auth_tokens: AuthTokensReturn the authenticated token pair used by this client branch.
Reflects automatic refreshes: after the access token is renewed, this holds the new access token alongside the original refresh token.
Returns
AuthTokens— The current authenticated token pair of this client branch.
AsyncAuthenticatedClient.access_token (property)
access_token: strReturn the bearer access token string used for authenticated calls.
Returns
str— The bearer access token string used for authenticated calls.
AsyncAuthenticatedClient.refresh_token (property)
refresh_token: strReturn the refresh token string paired with the access token.
Returns
str— The refresh token string paired with the access token.
AsyncAuthenticatedClient.resume_state
def resume_state() -> AuthenticationResumeStateReturn the authentication state needed to rehydrate this branch later.
The state holds the current tokens, so it includes any access token obtained through automatic refresh.
Returns
AuthenticationResumeState— The authentication state needed to rehydrate this branch later.
AsyncAuthenticatedClient.get_encryption_key
async def get_encryption_key() -> tuple[bytes, bytes, bytes]Generate a session AES key, IV, and encrypted symmetric key payload.
Returns
tuple[bytes, bytes, bytes]— A tuple of the raw AES key, the initialization vector and the AES key encrypted with the KSeF public key.
Raises
NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If symmetric-key encryption fails.
AsyncAuthenticatedClient.online_session
def online_session(
*,
form_code: FormSchema | None = None,
state: OnlineSessionResumeState | str | None = None,
) -> _AwaitableSession[AsyncOnlineSessionClient]Open a new online invoice session, or resume one from saved state.
Pass exactly one of form_code (open a new session) or state
(resume). When resuming, the form code, keys and expiry all come from the
state. Leaving the with block closes the session in both cases;
closing an already-closed session is a no-op.
Parameters
form_code(FormSchema | None) — Invoice schema the new session accepts, for exampleFormSchema.FA3.state(OnlineSessionResumeState | str | None) — State fromsession.resume_state(), or its JSON string, to resume an open session.
Returns
_AwaitableSession[AsyncOnlineSessionClient]— A session client that can be used as a context manager and closes the session on exit.
Raises
KSeFArgumentError— If neither or both ofform_codeandstateare given.NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If symmetric-key encryption fails.KSeFValidationError— Ifstateis not valid online session state.
Example
from ksef2.models import FormSchema
async with auth.online_session(form_code=FormSchema.FA3) as session:
submission = await session.send_invoice(xml_bytes)
saved = session.resume_state().to_json()
async with auth.online_session(state=saved) as session:
result = await session.submission(reference_number).wait()AsyncAuthenticatedClient.resume_online_session
def resume_online_session(state: OnlineSessionResumeState) -> AsyncOnlineSessionClientDeprecated: rebind an existing serialized online session state to this client.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use online_session(state=...) instead.
Parameters
state(OnlineSessionResumeState) — State previously exported from an online session client.
Returns
AsyncOnlineSessionClient— An online session client bound to the saved state.
AsyncAuthenticatedClient.batch_session
def batch_session(
*,
prepared_batch: PreparedBatch | None = None,
batch_file: BatchFileInfo | None = None,
form_code: FormSchema | None = None,
offline_mode: bool | None = None,
state: BatchSessionResumeState | str | None = None,
) -> _AwaitableSession[AsyncBatchSessionClient]Open a batch session for upload work, or resume one from saved state.
Pass exactly one of prepared_batch, batch_file (open a new
session) or state (resume). When resuming, everything comes from the
state, including the form code, keys and part upload requests. Leaving the
with block closes the session in every case; closing an already-closed
session is a no-op.
Parameters
prepared_batch(PreparedBatch | None) — Prepared batch payload created byauth.batch.prepare().batch_file(BatchFileInfo | None) — Declared ZIP package metadata and encrypted part metadata.form_code(FormSchema | None) — Invoice schema declared for the batch session whenbatch_fileis provided directly; defaults toFormSchema.FA3.offline_mode(bool | None) — Whether to declare offline invoicing mode for the batch whenbatch_fileis provided directly; defaults toFalse.state(BatchSessionResumeState | str | None) — State fromsession.resume_state(), or its JSON string, to resume a batch session.
Returns
_AwaitableSession[AsyncBatchSessionClient]— A bound batch session client exposing presigned upload instructions.
Raises
KSeFArgumentError— If not exactly one ofprepared_batch,batch_fileandstateis given, orform_codeoroffline_modeis combined withprepared_batchorstate.NoCertificateAvailableError— If certificate-backed encryption material is needed but no valid certificate is available.KSeFEncryptionError— If symmetric-key encryption fails.KSeFValidationError— Ifstateis not valid batch session state.
Example
from ksef2.models import BatchInvoice
prepared = await auth.batch.prepare(
[BatchInvoice(file_name="invoice-1.xml", content=xml_bytes)],
)
async with auth.batch_session(prepared_batch=prepared) as session:
await session.upload_parts()
saved = session.resume_state().to_json()
async with auth.batch_session(state=saved) as session:
final = await session.wait()AsyncAuthenticatedClient.open_batch_session
def open_batch_session(
*,
batch_file: BatchFileInfo,
aes_key: bytes,
iv: bytes,
encrypted_key: bytes,
public_key_id: str | None = None,
form_code: FormSchema = FormSchema.FA3,
offline_mode: bool = False,
prepared_batch: PreparedBatch | None = None,
) -> _AwaitableSession[AsyncBatchSessionClient]Deprecated: open a batch session using caller-prepared encryption metadata.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use auth.batch_session() for the standard flow, or raw for caller-supplied encryption material.
Parameters
batch_file(BatchFileInfo) — Declared ZIP package metadata and encrypted part metadata.aes_key(bytes) — Raw symmetric key used for part encryption.iv(bytes) — Initialization vector paired withaes_key.encrypted_key(bytes) — RSA-encrypted symmetric key sent to KSeF.public_key_id(str | None) — Identifier of the KSeF public key used for encryption.form_code(FormSchema) — Invoice schema declared for the batch session.offline_mode(bool) — Whether to declare offline invoicing mode for the batch.prepared_batch(PreparedBatch | None) — Optional prepared batch payload to attach to the returned session sosession.upload_parts()can operate without extra args.
Returns
_AwaitableSession[AsyncBatchSessionClient]— A bound batch session client exposing presigned upload instructions.
Raises
KSeFValidationError— If the batch session request is invalid.
AsyncAuthenticatedClient.resume_batch_session
def resume_batch_session(state: BatchSessionResumeState) -> AsyncBatchSessionClientDeprecated: rebind an existing serialized batch session state to this client.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use batch_session(state=...) instead.
Parameters
state(BatchSessionResumeState) — State previously exported from a batch session client.
Returns
AsyncBatchSessionClient— A batch session client bound to the saved state.
AsyncAuthenticatedClient.invoices (property)
invoices: AsyncInvoicesServiceReturn the invoices service with encryption support configured.
Returns
AsyncInvoicesService— The invoices service with encryption support configured.
AsyncAuthenticatedClient.batch (property)
batch: AsyncBatchServiceReturn the high-level batch upload workflow service.
The service orchestrates package preparation, session opening, presigned part uploads, session closing, and status polling.
Returns
AsyncBatchService— The batch upload service.
AsyncAuthenticatedClient.limits (property)
limits: AsyncLimitsClientReturn the authenticated rate-limit branch.
Returns
AsyncLimitsClient— The authenticated rate-limit branch.
AsyncAuthenticatedClient.collective_identifiers (property)
collective_identifiers: AsyncCollectiveIdentifiersClientReturn the collective invoice identifier branch.
Returns
AsyncCollectiveIdentifiersClient— The collective invoice identifier branch.
AsyncAuthenticatedClient.tokens (property)
tokens: AsyncTokensClientReturn the authenticated token lifecycle branch.
Returns
AsyncTokensClient— The authenticated token lifecycle branch.
AsyncAuthenticatedClient.certificates (property)
certificates: AsyncCertificatesClientReturn the authenticated certificate enrollment branch.
Returns
AsyncCertificatesClient— The authenticated certificate enrollment branch.
AsyncAuthenticatedClient.sessions (property)
sessions: AsyncSessionManagementClientReturn the authenticated session-management branch.
Returns
AsyncSessionManagementClient— The authenticated session-management branch.
AsyncAuthenticatedClient.invoice_sessions (property)
invoice_sessions: AsyncInvoiceSessionsClientReturn the authenticated invoice-session history branch.
Returns
AsyncInvoiceSessionsClient— The authenticated invoice-session history branch.
AsyncAuthenticatedClient.permissions (property)
permissions: AsyncPermissionsClientReturn the authenticated permissions branch.
Returns
AsyncPermissionsClient— The authenticated permissions branch.
AsyncAuthenticatedClient.testdata (property)
testdata: AsyncTestDataClientReturn authenticated TEST-only data mutation helpers.
Returns
AsyncTestDataClient— Authenticated TEST-only data mutation helpers.
AsyncAuthenticatedClient.raw (property)
raw: AsyncRawAuthenticatedClientReturn raw authenticated endpoints for advanced async integrations.
Returns
AsyncRawAuthenticatedClient— Raw authenticated endpoints for advanced async integrations.
AsyncBatchService
Import: from ksef2.clients import AsyncBatchService
class AsyncBatchServiceAsyncBatchService(
*,
authed_transport: AsyncMiddleware,
upload_transport: AsyncMiddleware,
get_encryption_key: Callable[[], Awaitable[SessionEncryptionMaterial]],
open_batch_session: AsyncBatchSessionOpener,
)Async high-level workflow for preparing and sending invoice batches.
Catch KSeFException for SDK-classified failures raised by this service,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncBatchService.prepare
async def prepare(
invoices: Iterable[bytes | str | Path | BatchInvoice],
*,
form_code: FormSchema = FormSchema.FA3,
offline_mode: bool = False,
max_part_size: int = MAX_BATCH_PART_SIZE,
) -> PreparedBatchBuild a ZIP package, split it, and encrypt each upload part.
Parameters
invoices(Iterable[bytes | str | Path | BatchInvoice]) — Invoices to include. Each item is invoice XML asbytesorstr(namedinvoice-<position>.xml), aPathto an XML file (keeps its file name) or aBatchInvoicewith an explicit file name.form_code(FormSchema) — Invoice schema declared for the batch session.offline_mode(bool) — Whether to declare offline invoicing mode for the batch.max_part_size(int) — Maximum size of each ZIP part before encryption.
Returns
PreparedBatch— A prepared batch with encrypted part payloads and the metadata requiredPreparedBatch— to open a batch session.
Raises
FileNotFoundError— If an invoice XML path does not exist.NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If key or part encryption fails.KSeFValidationError— If the invoice list or part size is invalid.
Example
batch = await auth.batch.prepare([xml_1, xml_2])
session = await auth.batch.submit(batch)AsyncBatchService.submit
async def submit(
batch: PreparedBatch | Iterable[bytes | str | Path | BatchInvoice],
*,
form_code: FormSchema = FormSchema.FA3,
offline_mode: bool = False,
max_part_size: int = MAX_BATCH_PART_SIZE,
) -> AsyncBatchSessionClientOpen a batch session, upload the parts and close the session.
Parameters
batch(PreparedBatch | Iterable[bytes | str | Path | BatchInvoice]) — A prepared batch fromprepare(), or the invoices themselves, which are prepared first (same item types asprepare()).form_code(FormSchema) — Invoice schema declared for the batch session. Ignored for a prepared batch, which carries its own.offline_mode(bool) — Whether to declare offline invoicing mode for the batch. Ignored for a prepared batch.max_part_size(int) — Maximum size of each ZIP part before encryption. Ignored for a prepared batch.
Returns
AsyncBatchSessionClient— The closed batch session client. Call itswait()for the terminal status,list_failed_invoices()for rejected invoices anddownload_upo()for the UPO pages.
Raises
NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If key or part encryption fails.KSeFValidationError— If preparation, session opening, or upload validation fails.KSeFBatchUploadError— If external storage rejects an upload or its outcome cannot be determined. Callrecovery_state()on the error to deliberately recover the sensitive batch state.
Example
session = await auth.batch.submit([xml_1, xml_2])
final = await session.wait()
upos = await session.download_upo()AsyncBatchService.prepare_batch
def prepare_batch(
*,
invoices: Iterable[BatchInvoice],
form_code: FormSchema = FormSchema.FA3,
offline_mode: bool = False,
max_part_size: int = MAX_BATCH_PART_SIZE,
) -> Coroutine[None, None, PreparedBatch]Deprecated: build a ZIP package, split it, and encrypt each upload part.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use prepare() instead.
Parameters
invoices(Iterable[BatchInvoice]) — Invoice XML payloads to include in the batch package.form_code(FormSchema) — Invoice schema declared for the batch session.offline_mode(bool) — Whether to declare offline invoicing mode for the batch.max_part_size(int) — Maximum size of each ZIP part before encryption.
Returns
Coroutine[None, None, PreparedBatch]— A prepared batch with encrypted part payloads and the metadata requiredCoroutine[None, None, PreparedBatch]— to open a batch session.
Raises
NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If key or part encryption fails.KSeFValidationError— If the invoice list or part size is invalid.
AsyncBatchService.prepare_batch_from_paths
def prepare_batch_from_paths(
*,
invoice_paths: Iterable[Path | str],
form_code: FormSchema = FormSchema.FA3,
offline_mode: bool = False,
max_part_size: int = MAX_BATCH_PART_SIZE,
) -> Coroutine[None, None, PreparedBatch]Deprecated: load invoice XML files from disk and prepare a batch package.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use prepare() with Path items instead.
Parameters
invoice_paths(Iterable[Path | str]) — Paths to XML files that should be added to the batch.form_code(FormSchema) — Invoice schema declared for the batch session.offline_mode(bool) — Whether to declare offline invoicing mode for the batch.max_part_size(int) — Maximum size of each ZIP part before encryption.
Returns
Coroutine[None, None, PreparedBatch]— A prepared batch with encrypted parts ready to be uploaded.
Raises
FileNotFoundError— If an invoice XML path does not exist.NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If key or part encryption fails.KSeFValidationError— If the invoice list or part size is invalid.
AsyncBatchService.open_session
def open_session(
*,
prepared_batch: PreparedBatch,
) -> _AwaitableSession[AsyncBatchSessionClient]Deprecated: open a batch session for an already prepared package.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use auth.batch_session(prepared_batch=...) instead.
Parameters
prepared_batch(PreparedBatch) — Prepared batch payload returned byprepare().
Returns
_AwaitableSession[AsyncBatchSessionClient]— A session client exposing the upload instructions returned by KSeF.
Raises
KSeFValidationError— If the prepared batch cannot be opened.
AsyncBatchService.upload_parts
async def upload_parts(
*,
session: AsyncBatchSessionClient,
prepared_batch: PreparedBatch,
) -> NoneUpload all prepared batch parts using the session's presigned URLs.
Parameters
session(AsyncBatchSessionClient) — Open batch session that already contains upload instructions.prepared_batch(PreparedBatch) — Prepared batch whose part ordinals match the session.
Raises
KSeFClientClosedError— If the session client is closed.KSeFValidationError— If prepared part ordinals do not match session upload instructions.KSeFBatchUploadError— If external storage rejects an upload or its outcome cannot be determined. Callrecovery_state()on the error to deliberately recover the sensitive batch state.
AsyncBatchService.submit_prepared_batch
def submit_prepared_batch(
*,
prepared_batch: PreparedBatch,
) -> Coroutine[None, None, BatchSessionResumeState]Deprecated: open, upload, and close a batch session for a prepared package.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use submit() instead.
Parameters
prepared_batch(PreparedBatch) — Prepared batch payload returned byprepare().
Returns
Coroutine[None, None, BatchSessionResumeState]— Serializable state of the submitted batch session.
Raises
KSeFClientClosedError— If the session client closes before upload.KSeFValidationError— If the prepared batch cannot be opened or uploaded.KSeFBatchUploadError— If external storage rejects an upload or its outcome cannot be determined. Callrecovery_state()on the error to deliberately recover the sensitive batch state.
AsyncBatchService.submit_batch
def submit_batch(
*,
invoices: Iterable[BatchInvoice],
form_code: FormSchema = FormSchema.FA3,
offline_mode: bool = False,
max_part_size: int = MAX_BATCH_PART_SIZE,
) -> Coroutine[None, None, BatchSessionResumeState]Deprecated: prepare and submit a batch in one call.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use submit() instead.
Parameters
invoices(Iterable[BatchInvoice]) — Invoice XML payloads to include in the batch package.form_code(FormSchema) — Invoice schema declared for the batch session.offline_mode(bool) — Whether to declare offline invoicing mode for the batch.max_part_size(int) — Maximum size of each ZIP part before encryption.
Returns
Coroutine[None, None, BatchSessionResumeState]— Serializable state of the submitted batch session.
Raises
NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If key or part encryption fails.KSeFValidationError— If preparation, session opening, or upload validation fails.KSeFBatchUploadError— If external storage rejects an upload or its outcome cannot be determined. Callrecovery_state()on the error to deliberately recover the sensitive batch state.
AsyncBatchService.get_status
def get_status(
*,
session: str | BatchSessionResumeState | AsyncBatchSessionClient,
) -> Coroutine[None, None, SessionStatusResponse]Deprecated: fetch the current status of a batch session.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use BatchSessionClient.get_status() instead.
Parameters
session(str | BatchSessionResumeState | AsyncBatchSessionClient) — Session reference number, persisted state, or open session client.
Returns
Coroutine[None, None, SessionStatusResponse]— Current batch session status as reported by KSeF.
AsyncBatchService.list_invoices
def list_invoices(
*,
session: str | BatchSessionResumeState | AsyncBatchSessionClient,
page_size: int = 10,
continuation_token: str | None = None,
) -> Coroutine[None, None, SessionInvoicesResponse]Deprecated: fetch one page of accepted invoices from a batch session.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use BatchSessionClient.list_invoices() instead.
Parameters
session(str | BatchSessionResumeState | AsyncBatchSessionClient) — Session reference number, persisted state, or open session client.page_size(int) — Number of invoices per page (10–1000).continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.
Returns
Coroutine[None, None, SessionInvoicesResponse]— One page of invoices accepted in the session, with a continuation token when more exist.
AsyncBatchService.list_failed_invoices
def list_failed_invoices(
*,
session: str | BatchSessionResumeState | AsyncBatchSessionClient,
page_size: int = 10,
continuation_token: str | None = None,
) -> Coroutine[None, None, SessionInvoicesResponse]Deprecated: fetch one page of failed invoices from a batch session.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use BatchSessionClient.list_failed_invoices() instead.
Parameters
session(str | BatchSessionResumeState | AsyncBatchSessionClient) — Session reference number, persisted state, or open session client.page_size(int) — Number of invoices per page (10–1000).continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.
Returns
Coroutine[None, None, SessionInvoicesResponse]— One page of invoices that failed processing, with a continuation token when more exist.
AsyncBatchService.get_upo
def get_upo(
*,
session: str | BatchSessionResumeState | AsyncBatchSessionClient,
upo_reference_number: str,
) -> Coroutine[None, None, bytes]Deprecated: download the collective UPO for a batch session.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use BatchSessionClient.download_upo() instead.
Parameters
session(str | BatchSessionResumeState | AsyncBatchSessionClient) — Session reference number, persisted state, or open session client.upo_reference_number(str) — UPO page reference returned in the session status.
Returns
Coroutine[None, None, bytes]— Raw XML bytes of the requested UPO page.
AsyncBatchService.wait_for_completion
def wait_for_completion(
*,
session: str | BatchSessionResumeState | AsyncBatchSessionClient,
timeout: float = 120.0,
poll_interval: float = 2.0,
) -> Coroutine[None, None, SessionStatusResponse]Deprecated: poll a batch session until KSeF reports a terminal status.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use BatchSessionClient.wait() instead.
Parameters
session(str | BatchSessionResumeState | AsyncBatchSessionClient) — Session reference number, persisted state, or open session client.timeout(float) — Maximum number of seconds to wait for completion.poll_interval(float) — Delay between status checks.
Returns
Coroutine[None, None, SessionStatusResponse]— Final successful batch session status.
Raises
KSeFSessionError— If batch processing reaches a failed terminal status.KSeFBatchSessionTimeoutError— If polling exceedstimeout.
AsyncBatchSessionClient
Import: from ksef2.clients import AsyncBatchSessionClient
class AsyncBatchSessionClientAsyncBatchSessionClient(
transport: AsyncMiddleware,
state: BatchSessionResumeState,
*,
upload_transport: AsyncMiddleware | None = None,
prepared_batch: PreparedBatch | None = None,
access_token: str | None = None,
resumed: bool = False,
)Async client for managing an active batch session.
Catch KSeFException for SDK-classified failures raised by this session
branch, and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.KSeFClientClosedError— If an operation is attempted after closing the session.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncBatchSessionClient.reference_number (property)
reference_number: strGet the batch session reference number.
Returns
str— The KSeF reference number of the session.
AsyncBatchSessionClient.access_token (property)
access_token: strDeprecated compatibility accessor for the current bearer token.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use AuthenticatedClient.access_token instead.
Returns
str— The bearer access token the session was opened with.
Raises
KSeFValidationError— If the session state carries no bearer token.
AsyncBatchSessionClient.aes_key (property)
aes_key: bytesGet the AES key for encrypting batch files.
Returns
bytes— The raw AES key.
AsyncBatchSessionClient.iv (property)
iv: bytesGet the initialization vector for AES encryption.
Returns
bytes— The raw initialization vector.
AsyncBatchSessionClient.part_upload_requests (property)
part_upload_requests: list[PartUploadRequest]Get the upload instructions for each file part.
Returns
list[PartUploadRequest]— One upload request, with presigned URL and headers, per part.
AsyncBatchSessionClient.resume_state
def resume_state() -> BatchSessionResumeStateReturn the sensitive session state needed to resume later.
Returns
BatchSessionResumeState— The sensitive session state needed to resume later.
AsyncBatchSessionClient.get_state
def get_state() -> BatchSessionResumeStateDeprecated compatibility wrapper for resume_state().
Deprecated
May be removed no earlier than ksef2 2.0.0. Use resume_state() instead.
Returns
BatchSessionResumeState— The same state asresume_state().
AsyncBatchSessionClient.get_status
async def get_status() -> SessionStatusResponseFetch the current processing state of the batch session.
Returns
SessionStatusResponse— The session status, including invoice counters.
AsyncBatchSessionClient.list_invoices
async def list_invoices(
*,
page_size: int = 10,
continuation_token: str | None = None,
) -> SessionInvoicesResponseFetch one page of invoices submitted in this batch session.
Parameters
page_size(int) — Number of invoices per page (10–1000).continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.
Returns
SessionInvoicesResponse— One page of invoices submitted in the session, with a continuation token when more exist.
AsyncBatchSessionClient.list_failed_invoices
async def list_failed_invoices(
*,
page_size: int = 10,
continuation_token: str | None = None,
) -> SessionInvoicesResponseFetch one page of failed invoices from this batch session.
Parameters
page_size(int) — Number of invoices per page (10–1000).continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.
Returns
SessionInvoicesResponse— One page of invoices that failed processing, with a continuation token when more exist.
AsyncBatchSessionClient.get_upo
def get_upo(*, upo_reference_number: str) -> Coroutine[None, None, bytes]Deprecated: download one page of the collective UPO for the batch session.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use download_upo() instead.
Parameters
upo_reference_number(str) — Reference number of the UPO, taken from the session status.
Returns
Coroutine[None, None, bytes]— The UPO as XML bytes.
AsyncBatchSessionClient.wait
async def wait(
*,
timeout: float = 120.0,
poll_interval: float = 2.0,
) -> SessionStatusResponsePoll until KSeF reports a terminal status for the closed batch session.
KSeF processes the batch after the session is closed, so call this after
auth.batch.submit() or after leaving the with block of a batch session.
Parameters
timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between session status checks.
Returns
SessionStatusResponse— The final successful session status, including the session UPO references.
Raises
KSeFSessionError— If the session is still open, or if batch processing reaches a failed terminal status.KSeFBatchSessionTimeoutError— If polling exceedstimeout.
AsyncBatchSessionClient.download_upo
async def download_upo() -> list[bytes]Download every page of the collective UPO in one pass.
Reads the session status once, resolves the UPO page references from it
and downloads each page. It never waits or polls: call wait() first.
Returns
list[bytes]— The XML bytes of each UPO page, in order; empty if KSeF issued no UPO because no invoice was accepted.
Raises
KSeFSessionError— If the session is still open.KSeFNotReadyError— If KSeF has not finished processing the closed batch. Callwait()on the session, then ask again.
AsyncBatchSessionClient.upload_parts
async def upload_parts() -> NoneUpload the prepared batch parts using the session's presigned URLs.
Raises
KSeFClientClosedError— If the upload window has already been closed.KSeFValidationError— If the session has no prepared batch payload attached.KSeFBatchUploadError— If external storage rejects an upload or its outcome cannot be determined. Callrecovery_state()on the error to deliberately recover the sensitive batch state.
AsyncBatchSessionClient.aclose
async def aclose() -> NoneClose the batch session and start processing.
This triggers processing of the invoice batch and generation of UPO for valid invoices and a collective UPO for the session. Closing an already-closed session is a no-op; a client rebuilt from saved state first asks KSeF whether the session was already closed.
AsyncCertificateEnrollment
Import: from ksef2.clients import AsyncCertificateEnrollment
class AsyncCertificateEnrollment(AsyncOperationHandle[CertificateEnrollmentStatusResponse, CertificateEnrollmentStatusResponse])AsyncCertificateEnrollment(
client: AsyncCertificatesClient,
response: CertificateEnrollmentResponse,
)Handle to a certificate enrollment that KSeF issues asynchronously.
Returned by auth.certificates.enroll(). It exposes every field of the
enrollment response, for example reference_number and timestamp, and
wait() polls until KSeF has issued the certificate.
get_enrollment_status() on the certificates client reads the same status
for a reference number you stored earlier.
Raises
KSeFApiError— If KSeF returns an API error response.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncCertificateEnrollment.timestamp (property)
timestamp: datetimeGet when KSeF accepted the enrollment request.
Returns
datetime— The acceptance time reported by KSeF.
AsyncCertificateEnrollment.response (property)
response: CertificateEnrollmentResponseGet the plain enrollment response.
Returns
CertificateEnrollmentResponse— The data model KSeF returned when it accepted the enrollment.
AsyncCertificateEnrollment.get_status
async def get_status() -> CertificateEnrollmentStatusResponseFetch the enrollment's current status without waiting.
Returns
CertificateEnrollmentStatusResponse— The enrollment status, including the certificate serial number once issued.
AsyncCertificateEnrollment.wait
async def wait(
*,
timeout: float = 60.0,
poll_interval: float = 2.0,
) -> CertificateEnrollmentStatusResponsePoll until KSeF has issued the certificate.
Parameters
timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between status checks.
Returns
CertificateEnrollmentStatusResponse— The final status, with the issued certificate's serial number.
Raises
KSeFCertificateEnrollmentFailedError— If KSeF rejects, cancels or fails the enrollment.KSeFCertificateEnrollmentTimeoutError— If polling exceedstimeout.
AsyncCertificatesClient
Import: from ksef2.clients import AsyncCertificatesClient
class AsyncCertificatesClientAsyncCertificatesClient(transport: AsyncMiddleware)Async high-level API for certificate enrollment, retrieval, and search.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncCertificatesClient.get_limits
async def get_limits() -> CertificateLimitsResponseReturn the effective certificate enrollment and issuance quotas.
Returns
CertificateLimitsResponse— The effective certificate enrollment and issuance quotas.
AsyncCertificatesClient.get_enrollment_data
async def get_enrollment_data() -> CertificateEnrollmentDataReturn subject data needed to prepare a CSR for enrollment.
Returns
CertificateEnrollmentData— Subject data needed to prepare a CSR for enrollment.
AsyncCertificatesClient.enroll
async def enroll(
*,
certificate_name: str,
certificate_type: CertificateTypeValue,
csr: str,
valid_from: datetime | str | None = None,
) -> AsyncCertificateEnrollmentRequest issuance of a certificate from a CSR.
Parameters
certificate_name(str) — Name to give the certificate.certificate_type(CertificateTypeValue) — Certificate type to request,authenticationoroffline.csr(str) — PKCS#10 certificate signing request, DER-encoded and Base64-encoded.valid_from(datetime | str | None) — Requested start of validity as a datetime or ISO 8601 string;Nonefor immediately.
Returns
AsyncCertificateEnrollment— A handle to the enrollment; callwait()to wait until KSeF has issued the certificate.
Example
enrollment = await auth.certificates.enroll(
certificate_name="signing", certificate_type="offline", csr=csr
)
status = await enrollment.wait()
print(status.certificate_serial_number)AsyncCertificatesClient.get_enrollment_status
async def get_enrollment_status(
*,
reference_number: str,
) -> CertificateEnrollmentStatusResponseFetch the current status of a certificate enrollment request.
Parameters
reference_number(str) — Reference number returned byenroll().
Returns
CertificateEnrollmentStatusResponse— The enrollment status, including the certificate serial number once issued.
AsyncCertificatesClient.retrieve
async def retrieve(
*,
certificate_serial_numbers: builtins.list[CertificateSerialNumber],
) -> RetrievedCertificatesListDownload issued certificates by serial number.
Parameters
certificate_serial_numbers(builtins.list[CertificateSerialNumber]) — Serial numbers of the certificates to download.
Returns
RetrievedCertificatesList— The requested certificates with their DER data.
AsyncCertificatesClient.revoke
async def revoke(
*,
certificate_serial_number: CertificateSerialNumber,
reason: RevocationReason | None = None,
) -> NoneRevoke a certificate, optionally providing a revocation reason.
Parameters
certificate_serial_number(CertificateSerialNumber) — Serial number of the certificate to revoke.reason(RevocationReason | None) — Reason for the revocation;Noneto omit it.
AsyncCertificatesClient.query
def query(
*,
name: str | None = None,
certificate_serial_number: CertificateSerialNumber | None = None,
certificate_type: CertificateTypeValue | None = None,
status: CertificateStatusValue | None = None,
expires_after: datetime | str | None = None,
params: OffsetPaginationParams | None = None,
) -> Coroutine[None, None, CertificatesInfoList]Deprecated: fetch one page of certificate search results.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead; first_page() fetches one page.
Parameters
name(str | None) — Match this certificate name.certificate_serial_number(CertificateSerialNumber | None) — Match this certificate serial number.certificate_type(CertificateTypeValue | None) — Match this certificate type.status(CertificateStatusValue | None) — Match this lifecycle status.expires_after(datetime | str | None) — Match certificates that expire after this datetime or ISO 8601 string.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
Coroutine[None, None, CertificatesInfoList]— One page of certificate metadata.
AsyncCertificatesClient.all
async def all(
*,
certificate_serial_number: CertificateSerialNumber | None = None,
name: str | None = None,
certificate_type: CertificateTypeValue | None = None,
status: CertificateStatusValue | None = None,
expires_after: datetime | str | None = None,
params: OffsetPaginationParams | None = None,
) -> AsyncIterator[CertificateInfo]Deprecated: iterate over all certificates matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead.
Parameters
certificate_serial_number(CertificateSerialNumber | None) — Match this certificate serial number.name(str | None) — Match this certificate name.certificate_type(CertificateTypeValue | None) — Match this certificate type.status(CertificateStatusValue | None) — Match this lifecycle status.expires_after(datetime | str | None) — Match certificates that expire after this datetime or ISO 8601 string.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Yields
AsyncIterator[CertificateInfo]— Each matching certificate, across all pages.
AsyncCertificatesClient.list
def list(
*,
name: str | None = None,
certificate_serial_number: CertificateSerialNumber | None = None,
certificate_type: CertificateTypeValue | None = None,
status: CertificateStatusValue | None = None,
expires_after: datetime | str | None = None,
params: OffsetPaginationParams | None = None,
) -> AsyncPager[CertificateInfo]List the certificates of the authenticated context.
Nothing is requested until the result is consumed. Iterate it for every
matching certificate, call pages() for page-sized lists or
first_page() for one request only.
Parameters
name(str | None) — Match this certificate name.certificate_serial_number(CertificateSerialNumber | None) — Match this certificate serial number.certificate_type(CertificateTypeValue | None) — Match this certificate type.status(CertificateStatusValue | None) — Match this lifecycle status.expires_after(datetime | str | None) — Match certificates that expire after this datetime or ISO 8601 string.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
AsyncPager[CertificateInfo]— A paging object over the matching certificates.
Example
async for certificate in auth.certificates.list(status="active"):
print(certificate.certificate_serial_number)AsyncClient
Import: from ksef2.clients import AsyncClient
class AsyncClientAsyncClient(
environment: Environment = Environment.PRODUCTION,
*,
transport_config: TransportConfig | None = None,
http_client: httpx.AsyncClient | None = None,
certificate_store: stores.CertificateStoreProtocol | None = None,
)Root async KSeF SDK client responsible for transport and lifecycle management.
Branch properties only create child clients. Branch operations document their own API, validation, and transport failures.
Raises
KSeFClientClosedError— If a branch is accessed after the client is closed.KSeFUnsupportedEnvironmentError— If a TEST-only branch is accessed outsideEnvironment.TEST.
Example
from ksef2 import AsyncClient, Environment
async with AsyncClient(Environment.TEST) as client:
auth = await client.authentication.with_test_certificate(nip="5261040828")
async for invoice in auth.invoices.all_metadata(filters=filters):
print(invoice.ksef_number)Methods
AsyncClient.authentication (property)
authentication: AsyncAuthClientReturn the authentication entry point.
Returns
AsyncAuthClient— The authentication branch, used to log in and obtain an authenticated client.
Raises
KSeFClientClosedError— If the root client has been closed.
AsyncClient.encryption (property)
encryption: AsyncEncryptionClientReturn the public encryption-certificate client.
Returns
AsyncEncryptionClient— The client for downloading KSeF public-key certificates.
Raises
KSeFClientClosedError— If the root client has been closed.
AsyncClient.peppol (property)
peppol: AsyncPeppolClientReturn the public Peppol provider client.
Returns
AsyncPeppolClient— The client for listing registered Peppol providers.
Raises
KSeFClientClosedError— If the root client has been closed.
AsyncClient.testdata (property)
testdata: AsyncTestDataClientReturn the TEST-only data seeding client.
Returns
AsyncTestDataClient— The client for creating and removing TEST-environment data.
Raises
KSeFClientClosedError— If the root client has been closed.KSeFUnsupportedEnvironmentError— If the client environment is not TEST.
AsyncClient.raw (property)
raw: AsyncRawClientReturn raw unauthenticated endpoints for advanced async integrations.
Returns
AsyncRawClient— Raw unauthenticated endpoints for advanced async integrations.
AsyncClient.authenticated
def authenticated(auth_tokens: AuthTokens) -> AsyncAuthenticatedClientDeprecated compatibility wrapper for authentication.resume().
Deprecated
May be removed no earlier than ksef2 2.0.0. Use authentication.resume() with AuthenticationResumeState.from_tokens() instead.
Parameters
auth_tokens(AuthTokens) — Access and refresh tokens from a previous authentication.
Returns
AsyncAuthenticatedClient— An authenticated client bound to the tokens.
AsyncClient.aclose
async def aclose() -> NoneClose owned resources and invalidate cached child clients.
AsyncCollectiveIdentifiersClient
Import: from ksef2.clients import AsyncCollectiveIdentifiersClient
class AsyncCollectiveIdentifiersClientAsyncCollectiveIdentifiersClient(transport: AsyncMiddleware)API for generating and querying collective invoice identifiers.
Methods
AsyncCollectiveIdentifiersClient.generate
async def generate(
*,
invoices: builtins.list[CollectiveIdentifierInvoice],
) -> GenerateCollectiveIdentifierResponseGenerate a collective identifier for the supplied invoices.
Parameters
invoices(builtins.list[CollectiveIdentifierInvoice]) — Invoices to group, with optional payment details.
Returns
GenerateCollectiveIdentifierResponse— The generated collective identifier number.
AsyncCollectiveIdentifiersClient.query
def query(
*,
filters: CollectiveIdentifiersQuery,
continuation_token: str | None = None,
params: CollectiveIdentifierParams | None = None,
) -> Coroutine[None, None, CollectiveIdentifiersPage]Deprecated: fetch one page of collective identifiers visible in the context.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead; first_page() fetches one page.
Parameters
filters(CollectiveIdentifiersQuery) — Criteria selecting collective identifiers.continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Returns
Coroutine[None, None, CollectiveIdentifiersPage]— One page of matching collective identifiers.
AsyncCollectiveIdentifiersClient.query_all
async def query_all(
*,
filters: CollectiveIdentifiersQuery,
params: CollectiveIdentifierParams | None = None,
) -> AsyncIterator[CollectiveIdentifiersPage]Deprecated: iterate through every page matching a collective identifier query.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list().pages() instead.
Parameters
filters(CollectiveIdentifiersQuery) — Criteria selecting collective identifiers.params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Yields
AsyncIterator[CollectiveIdentifiersPage]— Each page of matching collective identifiers, following continuation tokens.
AsyncCollectiveIdentifiersClient.query_by_ksef_number
def query_by_ksef_number(
*,
ksef_number: str,
continuation_token: str | None = None,
params: CollectiveIdentifierParams | None = None,
) -> Coroutine[None, None, CollectiveIdentifierReferencesPage]Deprecated: fetch one page of identifiers associated with a KSeF invoice.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_for_invoice() instead; first_page() fetches one page.
Parameters
ksef_number(str) — KSeF number of the invoice.continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Returns
Coroutine[None, None, CollectiveIdentifierReferencesPage]— One page of collective identifiers that reference the invoice.
AsyncCollectiveIdentifiersClient.query_all_by_ksef_number
async def query_all_by_ksef_number(
*,
ksef_number: str,
params: CollectiveIdentifierParams | None = None,
) -> AsyncIterator[CollectiveIdentifierReferencesPage]Deprecated: iterate through identifiers associated with one KSeF invoice.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_for_invoice().pages() instead.
Parameters
ksef_number(str) — KSeF number of the invoice.params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Yields
AsyncIterator[CollectiveIdentifierReferencesPage]— Each page of identifiers that reference the invoice, following continuation tokens.
AsyncCollectiveIdentifiersClient.list_all_invoices
async def list_all_invoices(
*,
collective_identifier_numbers: builtins.list[str],
params: CollectiveIdentifierParams | None = None,
) -> AsyncIterator[CollectiveIdentifierInvoicesPage]Deprecated: iterate through every invoice page for the supplied collective identifiers.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_invoices().pages() instead.
Parameters
collective_identifier_numbers(builtins.list[str]) — Collective identifier numbers to expand (1–10).params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Yields
AsyncIterator[CollectiveIdentifierInvoicesPage]— Each page of invoices, following continuation tokens.
AsyncCollectiveIdentifiersClient.list_for_invoice
def list_for_invoice(
ksef_number: str,
*,
params: CollectiveIdentifierParams | None = None,
) -> AsyncPager[CollectiveIdentifierReference]List the collective identifiers that reference one KSeF invoice.
Nothing is requested until the result is consumed.
Parameters
ksef_number(str) — KSeF number of the invoice.params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Returns
AsyncPager[CollectiveIdentifierReference]— A paging object over the collective identifiers referencing the invoice.
Example
async for reference in auth.collective_identifiers.list_for_invoice(ksef_number):
print(reference.collective_identifier_number)AsyncCollectiveIdentifiersClient.list_invoices
def list_invoices(
collective_identifier_numbers: builtins.list[str],
*,
params: CollectiveIdentifierParams | None = None,
) -> AsyncPager[CollectiveIdentifierInvoiceDetails]List the invoices inside the supplied collective identifiers.
Nothing is requested until the result is consumed. Unlike the former
list_invoices(), which fetched one page, this returns a paging object.
Parameters
collective_identifier_numbers(builtins.list[str]) — Collective identifier numbers to expand (1–10).params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Returns
AsyncPager[CollectiveIdentifierInvoiceDetails]— A paging object over the invoices belonging to the identifiers.
Example
async for invoice in auth.collective_identifiers.list_invoices([number]):
print(invoice.ksef_number)AsyncCollectiveIdentifiersClient.list
def list(
filters: CollectiveIdentifiersQuery,
*,
params: CollectiveIdentifierParams | None = None,
) -> AsyncPager[CollectiveIdentifierSummary]List the collective identifiers visible in the context.
Nothing is requested until the result is consumed. Iterate it for every
identifier, call pages() for page-sized lists or first_page() for
one request only.
Parameters
filters(CollectiveIdentifiersQuery) — Criteria selecting collective identifiers.params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Returns
AsyncPager[CollectiveIdentifierSummary]— A paging object over the matching collective identifiers.
Example
async for identifier in auth.collective_identifiers.list(filters):
print(identifier.collective_identifier_number)AsyncEncryptionClient
Import: from ksef2.clients import AsyncEncryptionClient
class AsyncEncryptionClientAsyncEncryptionClient(transport: AsyncMiddleware)Async access to public encryption certificates published by KSeF.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncEncryptionClient.get_certificates
async def get_certificates(
*,
usage: list[CertUsage] | None = None,
) -> list[PublicKeyCertificate]Return public certificates, optionally filtered by supported usage.
Parameters
usage(list[CertUsage] | None) — Return only certificates valid for these usages;Nonefor all.
Returns
list[PublicKeyCertificate]— The public-key certificates published by KSeF.
AsyncExportJob
Import: from ksef2.clients import AsyncExportJob
class AsyncExportJob(AsyncOperationHandle[InvoiceExportStatusResponse, ExportedInvoices])AsyncExportJob(
state: ExportResumeState,
*,
get_status: Callable[[], Awaitable[InvoiceExportStatusResponse]],
download_parts: Callable[[InvoicePackage], Awaitable[list[bytes]]],
)Handle to a scheduled invoice export.
Returned by auth.invoices.export(). wait() polls until KSeF has built
the package, then downloads, decrypts and joins its parts into an
ExportedInvoices result. The handle holds the keys needed to decrypt the
package, so keep it in memory only.
Raises
KSeFApiError— If KSeF returns an API error response.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncExportJob.resume_state
def resume_state() -> ExportResumeStateReturn the sensitive state needed to resume the export later.
Persist it with to_json() before waiting, and pass it to
auth.invoices.export(state=...) after a restart to get the job back.
It holds the key that decrypts the package, so store it as a credential.
Returns
ExportResumeState— The export's reference number and AES key material.
AsyncExportJob.get_status
async def get_status() -> InvoiceExportStatusResponseFetch the export's current status without waiting.
Returns
InvoiceExportStatusResponse— The export status, with package metadata once the export is ready.
AsyncExportJob.wait
async def wait(
*,
timeout: float = 120.0,
poll_interval: float = 2.0,
) -> ExportedInvoicesPoll until the export is ready, then download and decrypt the package.
Parameters
timeout(float) — Maximum number of seconds to wait for the export to become ready.poll_interval(float) — Delay in seconds between export status checks.
Returns
ExportedInvoices— The decrypted package: iterateinvoices(), readmetadataorsave()it to disk.
Raises
KSeFExportFailedError— If KSeF reports that the export failed, was cancelled or expired.KSeFExportTimeoutError— If polling exceedstimeout.KSeFEncryptionError— If a downloaded package part cannot be decrypted.KSeFExternalTransferError— If external storage rejects a part download or its outcome cannot be determined.
AsyncGeneratedToken
Import: from ksef2.clients import AsyncGeneratedToken
class AsyncGeneratedToken(AsyncOperationHandle[TokenStatusResponse, TokenStatusResponse])AsyncGeneratedToken(client: AsyncTokensClient, response: GenerateTokenResponse)Handle to a token KSeF is still activating.
Returned by auth.tokens.generate(). The one-time token is readable
immediately, so persist it before calling wait(): a polling failure does
not contain or recover that secret. The handle exposes every field of the
generation response, for example token and reference_number, and never
includes the token in its repr.
Raises
KSeFApiError— If KSeF returns an API error response.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncGeneratedToken.token (property)
token: strGet the one-time token value.
Returns
str— The secret KSeF returned once at generation; store it securely.
AsyncGeneratedToken.response (property)
response: GenerateTokenResponseGet the plain generation response.
Returns
GenerateTokenResponse— The data model KSeF returned when the token was generated.
AsyncGeneratedToken.to_sensitive_dict
def to_sensitive_dict() -> dict[str, str]Export the one-time token for deliberately protected persistence.
Returns
dict[str, str]— A dictionary with the reference number and the plain token.
AsyncGeneratedToken.get_status
async def get_status() -> TokenStatusResponseFetch the token's current status without waiting.
Returns
TokenStatusResponse— The token's current lifecycle status.
AsyncGeneratedToken.wait
async def wait(
*,
timeout: float = 60.0,
poll_interval: float = 1.0,
) -> TokenStatusResponsePoll until the token becomes active or reaches a terminal state.
Parameters
timeout(float) — Maximum number of seconds to wait for activation.poll_interval(float) — Delay in seconds between status checks.
Returns
TokenStatusResponse— The first status response that reports the token as active.
Raises
KSeFApiError— If activation ends in a terminal failure state.KSeFTokenStatusTimeoutError— If polling exceedstimeout.
AsyncInvoiceSessionsClient
Import: from ksef2.clients import AsyncInvoiceSessionsClient
class AsyncInvoiceSessionsClientAsyncInvoiceSessionsClient(transport: AsyncMiddleware)Async browse historical invoice sessions and download their UPO documents.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncInvoiceSessionsClient.download_upo
async def download_upo(
session_reference_number: str,
*,
invoice_reference_number: str | None = None,
ksef_number: str | None = None,
upo_reference_number: str | None = None,
) -> bytesDownload one UPO from stored references without opening a session.
Works for online and batch invoice sessions, including after a process restart. Uses the authenticated client's bearer token and makes one request. It never waits or polls, and needs no session crypto state.
Parameters
session_reference_number(str) — Reference number of the invoice session.invoice_reference_number(str | None) — Invoice reference within that session. Pass exactly one of this,ksef_numberorupo_reference_number.ksef_number(str | None) — KSeF number of an accepted invoice in that session.upo_reference_number(str | None) — Reference number of one session UPO page.
Returns
bytes— The invoice UPO or session UPO page as XML bytes.
Raises
KSeFValidationError— If no selector or multiple selectors are given.KSeFNotReadyError— If KSeF has not issued the requested UPO yet. Check processing status before retrying. Rejected invoices may never receive a UPO.
AsyncInvoiceSessionsClient.query
def query(
*,
session_type: str,
continuation_token: str | None = None,
params: ListSessionsQuery | None = None,
statuses: builtins.list[SessionStatus | SessionStatusEnum] | None = None,
) -> Coroutine[None, None, ListSessionsResponse]Deprecated: fetch one page of invoice session history for the chosen session type.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead; first_page() fetches one page.
Parameters
session_type(str) — Invoice session family to browse, such as"online"or"batch".continuation_token(str | None) — Cursor returned by a previous page.params(ListSessionsQuery | None) — Optional query object with pagination and filter settings.statuses(builtins.list[SessionStatus | SessionStatusEnum] | None) — Optional list of status filters applied on top ofparams.
Returns
Coroutine[None, None, ListSessionsResponse]— One page of historical invoice sessions.
AsyncInvoiceSessionsClient.all
async def all(
*,
session_type: str,
params: ListSessionsQuery | None = None,
) -> AsyncIterator[ListSessionsResponse]Deprecated: iterate through all pages of invoice session history.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list().pages() instead.
Parameters
session_type(str) — Invoice session family to browse, such as"online"or"batch".params(ListSessionsQuery | None) — Optional query object with pagination and filter settings.
Yields
AsyncIterator[ListSessionsResponse]— Successive pages of historical invoice sessions until KSeF stopsAsyncIterator[ListSessionsResponse]— returning a continuation token.
AsyncInvoiceSessionsClient.list
def list(
session_type: str,
*,
params: ListSessionsQuery | None = None,
statuses: builtins.list[SessionStatus | SessionStatusEnum] | None = None,
) -> AsyncPager[SessionSummary]List the invoice sessions of the chosen type, newest history first as KSeF returns it.
Nothing is requested until the result is consumed. Iterate it for every
session, call pages() for page-sized lists or first_page() for one
request only.
Parameters
session_type(str) — Invoice session family to browse, such as"online"or"batch".params(ListSessionsQuery | None) — Optional query object with page size and filter settings.statuses(builtins.list[SessionStatus | SessionStatusEnum] | None) — Optional list of status filters applied on top ofparams.
Returns
AsyncPager[SessionSummary]— A paging object over the matching invoice sessions.
Example
async for session in auth.invoice_sessions.list("online"):
print(session.reference_number, session.status)AsyncInvoicesService
Import: from ksef2.clients import AsyncInvoicesService
class AsyncInvoicesServiceAsyncInvoicesService(
transport: AsyncMiddleware,
download_transport: AsyncMiddleware,
certificate_store: CertificateStoreProtocol,
*,
client: AsyncInvoicesClient | None = None,
ensure_encryption_certificates_loaded: Callable[[], Awaitable[None]] | None = None,
)Async invoice workflows with encryption, polling, and export helpers.
Catch KSeFException for SDK-classified failures raised by this service,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncInvoicesService.search
def search(
filters: InvoicesFilter,
params: InvoiceMetadataParams | None = None,
) -> AsyncPager[InvoiceMetadata]Search invoice metadata, following KSeF page and truncation mechanics.
Nothing is requested until the result is consumed. Iterate it for every
matching invoice, call pages() for page-sized lists, first_page()
for one request only, or wait() to poll until KSeF has indexed at
least one matching invoice.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices.params(InvoiceMetadataParams | None) — Page size and sort order; defaults are used whenNone.
Returns
AsyncPager[InvoiceMetadata]— A paging object over the metadata of matching invoices.
Raises
KSeFMetadataPaginationError— If KSeF returns inconsistent pagination boundaries while paging.
Example
from ksef2.models import InvoicesFilter
filters = InvoicesFilter.for_seller(date_from="2026-01-01T00:00:00+01:00")
async for invoice in auth.invoices.search(filters):
print(invoice.ksef_number, invoice.gross_amount)AsyncInvoicesService.download
async def download(
ksef_number: str,
*,
timeout: float | None = None,
poll_interval: float = 2.0,
) -> bytesDownload one processed invoice by KSeF number.
Parameters
ksef_number(str) — KSeF number of the invoice.timeout(float | None) — Seconds to keep polling while KSeF has not made the invoice available yet;Nonetries once.poll_interval(float) — Delay in seconds between download attempts whentimeoutis set.
Returns
bytes— The invoice XML as bytes.
Raises
KSeFApiError— If KSeF rejects the download, for example because the invoice is not processed yet andtimeoutisNone.KSeFInvoiceDownloadTimeoutError— Iftimeoutis set and polling exceeds it.
Example
xml = await auth.invoices.download(ksef_number, timeout=60)AsyncInvoicesService.export
async def export(
filters: InvoicesFilter | None = None,
*,
state: ExportResumeState | str | None = None,
only_metadata: bool = False,
compression_type: CompressionType | str | None = None,
) -> AsyncExportJobSchedule an encrypted invoice export, or resume one scheduled earlier.
Pass exactly one of filters (schedule a new export) or state
(resume the export described by a saved ExportResumeState).
Parameters
filters(InvoicesFilter | None) — Criteria selecting the invoices to export.state(ExportResumeState | str | None) — State fromExportJob.resume_state(), or its JSON string, to resume an export after a restart. Cannot be combined with the other arguments.only_metadata(bool) — Export only invoice metadata instead of full invoice XML.compression_type(CompressionType | str | None) — Compression applied to the package;Nonefor the server default.
Returns
AsyncExportJob— A handle to the export. Call itswait()to download the decrypted package.
Raises
KSeFArgumentError— If neither or both offiltersandstateare given, orstateis combined with scheduling options.NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If export key encryption fails.KSeFValidationError— Ifstateis not valid export resume state.
Example
job = await auth.invoices.export(filters)
saved = job.resume_state().to_json() # persist before waiting
job = await auth.invoices.export(state=saved) # after a restart
package = await job.wait()
package.save("out/")AsyncInvoicesService.query_metadata
def query_metadata(
*,
filters: InvoicesFilter,
params: InvoiceMetadataParams | None = None,
) -> Coroutine[None, None, QueryInvoicesMetadataResponse]Deprecated: fetch one invoice metadata page matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use search() instead; first_page() fetches one page.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices.params(InvoiceMetadataParams | None) — Page size, page offset and sort order; defaults are used whenNone.
Returns
Coroutine[None, None, QueryInvoicesMetadataResponse]— One page of invoice metadata.
AsyncInvoicesService.query_metadata_pages
async def query_metadata_pages(
*,
filters: InvoicesFilter,
params: InvoiceMetadataParams | None = None,
) -> AsyncIterator[QueryInvoicesMetadataResponse]Deprecated: fetch metadata pages, following KSeF page and truncation mechanics.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use search().pages() instead.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices.params(InvoiceMetadataParams | None) — Page size, page offset and sort order; defaults are used whenNone.
Yields
AsyncIterator[QueryInvoicesMetadataResponse]— Each page of invoice metadata in order.
Raises
KSeFMetadataPaginationError— If KSeF returns inconsistent pagination boundaries.
AsyncInvoicesService.all_metadata
async def all_metadata(
*,
filters: InvoicesFilter,
params: InvoiceMetadataParams | None = None,
) -> AsyncIterator[InvoiceMetadata]Deprecated: iterate over all invoice metadata items matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use search() instead.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices.params(InvoiceMetadataParams | None) — Page size and sort order; defaults are used whenNone.
Yields
AsyncIterator[InvoiceMetadata]— Metadata of each matching invoice, across all pages.
Raises
KSeFMetadataPaginationError— If KSeF returns inconsistent pagination boundaries.
AsyncInvoicesService.download_invoice
def download_invoice(*, ksef_number: str) -> Coroutine[None, None, bytes]Deprecated: download one processed invoice by KSeF number.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use download() instead.
Parameters
ksef_number(str) — KSeF number of the invoice.
Returns
Coroutine[None, None, bytes]— The invoice XML as bytes.
AsyncInvoicesService.wait_for_invoice_download
def wait_for_invoice_download(
*,
ksef_number: str,
timeout: float = 120.0,
poll_interval: float = 2.0,
) -> Coroutine[None, None, bytes]Deprecated: poll until KSeF makes a processed invoice available for download.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use download(ksef_number, timeout=...) instead.
Parameters
ksef_number(str) — KSeF number of the invoice.timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between download attempts.
Returns
Coroutine[None, None, bytes]— The invoice XML as bytes.
Raises
KSeFInvoiceDownloadTimeoutError— If polling exceedstimeout.
AsyncInvoicesService.schedule_export
def schedule_export(
*,
filters: InvoicesFilter,
only_metadata: bool = False,
compression_type: CompressionType | str | None = None,
) -> Coroutine[None, None, ExportHandle]Deprecated: schedule an encrypted invoice export.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use export() instead.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices to export.only_metadata(bool) — Export only invoice metadata instead of full invoice XML.compression_type(CompressionType | str | None) — Compression applied to the package;Nonefor the server default.
Returns
Coroutine[None, None, ExportHandle]— A handle holding the export reference number and the keys needed to decrypt the package.
Raises
NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If export key encryption fails.
AsyncInvoicesService.get_export_status
def get_export_status(
*,
reference_number: str,
) -> Coroutine[None, None, InvoiceExportStatusResponse]Deprecated: fetch the current status for a scheduled invoice export.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use export() and ExportJob.get_status() instead.
Parameters
reference_number(str) — Reference number of the export, fromExportHandle.reference_number.
Returns
Coroutine[None, None, InvoiceExportStatusResponse]— The export status, with package metadata once the export is ready.
AsyncInvoicesService.fetch_package
def fetch_package(
*,
package: InvoicePackage,
export: ExportHandle,
target_directory: Path | str = '.',
) -> Coroutine[None, None, list[Path]]Deprecated: download and decrypt all parts of an export package to disk.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use export().wait() and ExportedInvoices.save() instead.
Parameters
package(InvoicePackage) — Package metadata from the export status.export(ExportHandle) — Handle returned when the export was scheduled; supplies the decryption keys.target_directory(Path | str) — Directory to write the decrypted parts to. Defaults to the current directory.
Returns
Coroutine[None, None, list[Path]]— The paths of the written part files.
Raises
KSeFEncryptionError— If a downloaded package part cannot be decrypted.ValueError— If a package part name is unsafe for local filesystem output.OSError— If the target directory or output file cannot be written.KSeFExternalTransferError— If external storage rejects a part download or its outcome cannot be determined.
AsyncInvoicesService.fetch_package_bytes
def fetch_package_bytes(
*,
package: InvoicePackage,
export: ExportHandle,
) -> Coroutine[None, None, list[bytes]]Deprecated: download and decrypt all parts of an export package in memory.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use export().wait() and ExportedInvoices.archive instead.
Parameters
package(InvoicePackage) — Package metadata from the export status.export(ExportHandle) — Handle returned when the export was scheduled; supplies the decryption keys.
Returns
Coroutine[None, None, list[bytes]]— The decrypted package parts, in order.
Raises
KSeFEncryptionError— If a downloaded package part cannot be decrypted.KSeFExternalTransferError— If external storage rejects a part download or its outcome cannot be determined.
AsyncInvoicesService.wait_for_invoices
def wait_for_invoices(
*,
filters: InvoicesFilter,
timeout: float = 120.0,
poll_interval: float = 2.0,
) -> Coroutine[None, None, QueryInvoicesMetadataResponse]Deprecated: poll invoice metadata until at least one invoice matches the filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use search(filters).wait() instead.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices.timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between queries.
Returns
Coroutine[None, None, QueryInvoicesMetadataResponse]— The first metadata page that contains at least one invoice.
Raises
KSeFInvoiceQueryTimeoutError— If polling exceedstimeout.
AsyncInvoicesService.wait_for_export_package
def wait_for_export_package(
*,
reference_number: str,
timeout: float = 120.0,
poll_interval: float = 2.0,
) -> Coroutine[None, None, InvoicePackage]Deprecated: poll export status until KSeF exposes a downloadable package.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use export().wait() instead.
Parameters
reference_number(str) — Reference number of the export, fromExportHandle.reference_number.timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between export status checks.
Returns
Coroutine[None, None, InvoicePackage]— The package metadata once the export is ready.
Raises
KSeFExportTimeoutError— If polling exceedstimeout.
AsyncInvoicesService.export_and_download
def export_and_download(
*,
filters: InvoicesFilter,
only_metadata: bool = False,
compression_type: CompressionType | str | None = None,
timeout: float = 120.0,
poll_interval: float = 2.0,
) -> Coroutine[None, None, list[bytes]]Deprecated: schedule an export, wait for it, and download the decrypted package.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use export().wait() instead; ExportedInvoices.archive is the joined ZIP.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices to export.only_metadata(bool) — Export only invoice metadata instead of full invoice XML.compression_type(CompressionType | str | None) — Compression applied to the package;Nonefor the server default.timeout(float) — Maximum number of seconds to wait for the export to become ready.poll_interval(float) — Delay in seconds between export status checks.
Returns
Coroutine[None, None, list[bytes]]— The decrypted package parts, in order. Concatenate them to obtain the package archive.
Raises
NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If export key encryption or package decryption fails.KSeFExportTimeoutError— If polling exceedstimeout.KSeFExternalTransferError— If external storage rejects a part download or its outcome cannot be determined.
AsyncInvoiceSubmission
Import: from ksef2.clients import AsyncInvoiceSubmission
class AsyncInvoiceSubmission(AsyncOperationHandle[SessionInvoiceStatusResponse, SessionInvoiceStatusResponse])AsyncInvoiceSubmission(
session: AsyncOnlineSessionClient,
response: invoices.SendInvoiceResponse,
)Handle to one invoice sent into an online session.
Returned by session.send_invoice(). It exposes every field of the
submission response, for example reference_number, and polls the invoice's
processing status with wait(). It keeps working after the session is
closed, so a typical flow sends inside the with block and waits after it.
Raises
KSeFApiError— If KSeF returns an API error response.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncInvoiceSubmission.response (property)
response: invoices.SendInvoiceResponseGet the plain submission response.
Returns
invoices.SendInvoiceResponse— The data model KSeF returned when the invoice was accepted for processing.
AsyncInvoiceSubmission.get_status
async def get_status() -> SessionInvoiceStatusResponseFetch the invoice's current processing status without waiting.
Returns
SessionInvoiceStatusResponse— The processing status of the invoice.
AsyncInvoiceSubmission.wait
async def wait(
*,
timeout: float = 60.0,
poll_interval: float = 2.0,
) -> SessionInvoiceStatusResponsePoll until KSeF assigns the invoice a final processing result.
Parameters
timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between invoice status checks.
Returns
SessionInvoiceStatusResponse— The final processing status, including the invoice's KSeF number once accepted.
Raises
KSeFInvoiceRejectedError— If invoice processing reaches a failed terminal status. It subclassesKSeFSessionErrorand keeps the statusdetailsandextensions.KSeFInvoiceProcessingTimeoutError— If polling exceedstimeout.
AsyncInvoiceSubmission.download_upo
async def download_upo() -> bytesDownload the UPO of this invoice with a single request.
KSeF issues the UPO once it has accepted the invoice. Call wait()
first, then this; it never waits or polls.
Returns
bytes— The UPO as XML bytes.
Raises
KSeFNotReadyError— If KSeF has not issued the UPO yet. Callwait()on this submission, then ask again.
AsyncLimitsClient
Import: from ksef2.clients import AsyncLimitsClient
class AsyncLimitsClientAsyncLimitsClient(transport: AsyncMiddleware)Async read and override KSeF context, subject, and API rate limits.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncLimitsClient.get_context_limits
async def get_context_limits() -> ContextLimitsReturn the effective limits for online and batch sessions.
Returns
ContextLimits— The effective limits for online and batch sessions.
AsyncLimitsClient.get_subject_limits
async def get_subject_limits() -> SubjectLimitsReturn the effective limits for certificate enrollments and issuance.
Returns
SubjectLimits— The effective limits for certificate enrollments and issuance.
AsyncLimitsClient.get_api_rate_limits
async def get_api_rate_limits() -> ApiRateLimitsReturn the effective per-endpoint API rate limits.
Returns
ApiRateLimits— The effective per-endpoint API rate limits.
AsyncLimitsClient.set_session_limits
async def set_session_limits(*, limits: ContextLimits) -> NoneOverride session limits for the current subject.
Parameters
limits(ContextLimits) — New session limits.
AsyncLimitsClient.reset_session_limits
async def reset_session_limits() -> NoneReset session limits to their default values.
AsyncLimitsClient.set_subject_limits
async def set_subject_limits(*, limits: SubjectLimits) -> NoneOverride subject-level certificate and enrollment limits.
Parameters
limits(SubjectLimits) — New subject-level limits.
AsyncLimitsClient.reset_subject_limits
async def reset_subject_limits() -> NoneReset subject-level limits to their default values.
AsyncLimitsClient.set_api_rate_limits
async def set_api_rate_limits(*, limits: ApiRateLimits) -> NoneOverride API rate limits for the current subject.
Parameters
limits(ApiRateLimits) — New API rate limits.
AsyncLimitsClient.reset_api_rate_limits
async def reset_api_rate_limits() -> NoneReset API rate limits to their default values.
AsyncLimitsClient.set_production_rate_limits
async def set_production_rate_limits() -> NoneCopy production rate-limit defaults into the current environment.
AsyncOnlineSessionClient
Import: from ksef2.clients import AsyncOnlineSessionClient
class AsyncOnlineSessionClientAsyncOnlineSessionClient(
transport: AsyncMiddleware,
state: OnlineSessionResumeState,
*,
resumed: bool = False,
)Async client bound to a single online invoice session.
Send invoices with send_invoice(), close the session by leaving the
async with block, then call wait() for the terminal session status and
download_upo() for the session UPO.
Catch KSeFException for SDK-classified failures raised by this session
branch, and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.KSeFClientClosedError— If an operation is attempted after closing the session.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncOnlineSessionClient.reference_number (property)
reference_number: strGet the online session reference number.
Returns
str— The KSeF reference number of the session.
AsyncOnlineSessionClient.submission
def submission(reference_number: str) -> AsyncInvoiceSubmissionGet the handle of an invoice sent earlier in this session.
Use it after a restart or on a resumed session to wait() for the
invoice or download_upo(). No request is made until you call one.
Parameters
reference_number(str) — Invoice reference number, as exposed by the handlesend_invoice()returned.
Returns
AsyncInvoiceSubmission— The invoice submission handle.
AsyncOnlineSessionClient.send_invoice
async def send_invoice(invoice_xml: bytes | str) -> AsyncInvoiceSubmissionEncrypt and submit one invoice into the open session.
Parameters
invoice_xml(bytes | str) — Invoice XML, valid against the session's schema. Astris encoded as UTF-8.
Returns
AsyncInvoiceSubmission— A handle exposing the submission'sreference_number. Call itswait()for the processing result anddownload_upo()for the invoice UPO.
Raises
KSeFEncryptionError— If invoice encryption fails.
Example
async with auth.online_session(form_code=FormSchema.FA3) as session:
submission = await session.send_invoice(xml)
result = await submission.wait(timeout=60)
print(result.ksef_number)AsyncOnlineSessionClient.send_invoice_and_wait
def send_invoice_and_wait(
*,
invoice_xml: bytes,
timeout: float = 60.0,
poll_interval: float = 2.0,
) -> Coroutine[None, None, SessionInvoiceStatusResponse]Deprecated: submit an invoice and poll until KSeF assigns a final result.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use send_invoice().wait() instead.
Parameters
invoice_xml(bytes) — Invoice XML bytes, valid against the session's schema.timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between invoice status checks.
Returns
Coroutine[None, None, SessionInvoiceStatusResponse]— The final processing status, including the invoice's KSeF number once accepted.
Raises
KSeFEncryptionError— If invoice encryption fails.KSeFInvoiceRejectedError— If invoice processing reaches a failed terminal status. It subclassesKSeFSessionErrorand keeps the statusdetailsandextensions.KSeFInvoiceProcessingTimeoutError— If polling exceedstimeout.
AsyncOnlineSessionClient.get_status
async def get_status() -> SessionStatusResponseFetch the current state of the online session.
Returns
SessionStatusResponse— The session status, including invoice counters.
AsyncOnlineSessionClient.list_invoices
async def list_invoices(
*,
page_size: int = 10,
continuation_token: str | None = None,
) -> SessionInvoicesResponseFetch one page of invoices submitted in this session.
Parameters
page_size(int) — Number of invoices per page (10–1000).continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.
Returns
SessionInvoicesResponse— One page of invoices submitted in the session, with a continuation token when more exist.
AsyncOnlineSessionClient.get_invoice_status
async def get_invoice_status(
*,
invoice_reference_number: str,
) -> SessionInvoiceStatusResponseFetch processing status for one invoice sent in this session.
Parameters
invoice_reference_number(str) — Reference number of the invoice within the session, as exposed by the handlesend_invoice()returned.
Returns
SessionInvoiceStatusResponse— The processing status of the invoice.
AsyncOnlineSessionClient.wait_for_invoice_ready
def wait_for_invoice_ready(
*,
invoice_reference_number: str,
timeout: float = 60.0,
poll_interval: float = 2.0,
) -> Coroutine[None, None, SessionInvoiceStatusResponse]Deprecated: poll invoice status until it succeeds, fails, or times out.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use send_invoice().wait() instead.
Parameters
invoice_reference_number(str) — Reference number of the invoice within the session.timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between invoice status checks.
Returns
Coroutine[None, None, SessionInvoiceStatusResponse]— The final processing status, including the invoice's KSeF number once accepted.
Raises
KSeFInvoiceRejectedError— If invoice processing reaches a failed terminal status. It subclassesKSeFSessionErrorand keeps the statusdetailsandextensions.KSeFInvoiceProcessingTimeoutError— If polling exceedstimeout.
AsyncOnlineSessionClient.list_failed_invoices
async def list_failed_invoices(
*,
page_size: int = 10,
continuation_token: str | None = None,
) -> SessionInvoicesResponseFetch one page of invoices that failed within this session.
Parameters
page_size(int) — Number of invoices per page (10–1000).continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.
Returns
SessionInvoicesResponse— One page of invoices that failed processing, with a continuation token when more exist.
AsyncOnlineSessionClient.download_invoice_upo
async def download_invoice_upo(
*,
ksef_number: str | None = None,
reference_number: str | None = None,
) -> bytesDownload the UPO of one invoice accepted in this session.
Parameters
ksef_number(str | None) — KSeF number of the invoice. Pass this orreference_number.reference_number(str | None) — Reference number of the invoice within the session, as exposed by the handlesend_invoice()returned. Pass this orksef_number.
Returns
bytes— The UPO as XML bytes.
Raises
KSeFValidationError— If both or neither ofksef_numberandreference_numberare given.
AsyncOnlineSessionClient.get_invoice_upo_by_ksef_number
def get_invoice_upo_by_ksef_number(*, ksef_number: str) -> Coroutine[None, None, bytes]Deprecated: download the invoice UPO by KSeF number.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use download_invoice_upo(ksef_number=...) instead.
Parameters
ksef_number(str) — KSeF number of an invoice accepted in this session.
Returns
Coroutine[None, None, bytes]— The UPO as XML bytes.
AsyncOnlineSessionClient.get_invoice_upo_by_reference
def get_invoice_upo_by_reference(
*,
invoice_reference_number: str,
) -> Coroutine[None, None, bytes]Deprecated: download the invoice UPO by session invoice reference number.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use download_invoice_upo(reference_number=...) instead.
Parameters
invoice_reference_number(str) — Reference number of the invoice within the session.
Returns
Coroutine[None, None, bytes]— The UPO as XML bytes.
AsyncOnlineSessionClient.wait
async def wait(
*,
timeout: float = 120.0,
poll_interval: float = 2.0,
) -> SessionStatusResponsePoll until KSeF reports a terminal status for the closed session.
KSeF processes the session only after it is closed, so call this after
leaving the with block or calling aclose().
Parameters
timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between session status checks.
Returns
SessionStatusResponse— The final successful session status, including the session UPO references.
Raises
KSeFSessionError— If the session is still open, or if KSeF reports a failed terminal status.KSeFOnlineSessionTimeoutError— If polling exceedstimeout.
AsyncOnlineSessionClient.download_upo
async def download_upo() -> list[bytes]Download every page of the session UPO in one pass.
Reads the session status once, resolves the UPO page references from it
and downloads each page. It never waits or polls: call wait() first.
Returns
list[bytes]— The XML bytes of each UPO page, in order; empty if KSeF issued no UPO because no invoice was accepted.
Raises
KSeFSessionError— If the session is still open.KSeFNotReadyError— If KSeF has not finished processing the closed session. Callwait()on the session, then ask again.
AsyncOnlineSessionClient.aclose
async def aclose() -> NoneTerminate the online session if it is still open.
Closing an already-closed session is a no-op. A client rebuilt from saved state first asks KSeF whether the session was already closed.
Raises
KSeFApiError— If KSeF rejects the session termination request.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
AsyncOnlineSessionClient.resume_state
def resume_state() -> OnlineSessionResumeStateReturn the sensitive session state needed to resume later.
Returns
OnlineSessionResumeState— The sensitive session state needed to resume later.
AsyncOnlineSessionClient.get_state
def get_state() -> OnlineSessionResumeStateDeprecated compatibility wrapper for resume_state().
Deprecated
May be removed no earlier than ksef2 2.0.0. Use resume_state() instead.
Returns
OnlineSessionResumeState— The same state asresume_state().
AsyncOperationHandle
Import: from ksef2.clients import AsyncOperationHandle
class AsyncOperationHandle(ABC, Generic[_TStatus, _TResult])AsyncOperationHandle(reference_number: str)Client-side handle to an operation that KSeF finishes asynchronously.
A handle keeps a reference to the client that started the operation and the
operation's reference number. It is not a data model: it cannot be
serialized, and the plain response models stay separate. Subclasses say how
to read the operation's status, when it is still pending and how to turn the
finished status into the result returned by wait().
Catch KSeFException for SDK-classified failures raised while waiting, and
httpx.HTTPError for transport failures.
Methods
AsyncOperationHandle.reference_number (property)
reference_number: strGet the KSeF reference number of the operation.
Returns
str— The reference number KSeF assigned to the operation.
AsyncOperationHandle.get_status
async def get_status() -> _TStatusFetch the current status of the operation without waiting.
Returns
_TStatus— The status as KSeF reports it right now.
AsyncPager
Import: from ksef2.clients import AsyncPager
class AsyncPager(Generic[_T])AsyncPager(
pages: Callable[[], AsyncGenerator[list[_T], None]],
*,
timeout_error: Callable[[float], BaseException] | None = None,
)Lazy view over a paged collection in KSeF.
Iterating the pager yields every item across all pages, requesting pages as
needed. pages() yields one list of items per page, and first_page()
fetches only the first. Nothing is requested until the pager is consumed, and
every iteration starts from the first page again.
Raises
KSeFApiError— If KSeF returns an API error response while a page is fetched.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncPager.pages
def pages() -> AsyncIterator[list[_T]]Iterate over the collection one page at a time.
Returns
AsyncIterator[list[_T]]— An iterator yielding the items of each page as a list, in order.
AsyncPager.first_page
async def first_page() -> list[_T]Fetch only the first page.
Returns
list[_T]— The items of the first page; empty if the collection is empty.
AsyncPager.wait
async def wait(*, timeout: float = 120.0, poll_interval: float = 2.0) -> AsyncPager[_T]Poll until the collection contains at least one item.
Use it when KSeF indexes items with a delay, for example invoices that were accepted a moment ago and are not searchable yet.
Parameters
timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between checks.
Returns
AsyncPager[_T]— This pager, now known to be non-empty. Iterating it requests the pages again.
Raises
KSeFInvoiceQueryTimeoutError— For invoice searches, if no invoice appears withintimeout.TimeoutError— For other collections, if no item appears withintimeout.
AsyncPeppolClient
Import: from ksef2.clients import AsyncPeppolClient
class AsyncPeppolClientAsyncPeppolClient(transport: AsyncMiddleware)Async service for querying Peppol service providers.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncPeppolClient.query
def query(
*,
params: OffsetPaginationParams | None = None,
) -> Coroutine[None, None, ListPeppolProvidersResponse]Deprecated: query one page of Peppol service providers.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead; first_page() fetches one page.
Parameters
params(OffsetPaginationParams | None) — Pagination parameters.
Returns
Coroutine[None, None, ListPeppolProvidersResponse]— One page of providers with pagination info.
AsyncPeppolClient.all
async def all(
*,
params: OffsetPaginationParams | None = None,
) -> AsyncIterator[PeppolProvider]Deprecated: iterate over all Peppol service providers.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead.
Parameters
params(OffsetPaginationParams | None) — Pagination parameters.
Yields
AsyncIterator[PeppolProvider]— Each Peppol service provider, across all pages.
AsyncPeppolClient.list
def list(*, params: OffsetPaginationParams | None = None) -> AsyncPager[PeppolProvider]List the registered Peppol service providers.
Nothing is requested until the result is consumed. Iterate it for every
provider, call pages() for page-sized lists or first_page() for one
request only.
Parameters
params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
AsyncPager[PeppolProvider]— A paging object over the Peppol service providers.
Example
async for provider in auth.peppol.list():
print(provider.id, provider.name)AsyncPermissionOperation
Import: from ksef2.clients import AsyncPermissionOperation
class AsyncPermissionOperation(AsyncOperationHandle[PermissionOperationStatusResponse, PermissionOperationStatusResponse])AsyncPermissionOperation(
client: AsyncPermissionsClient,
response: GrantPermissionsResponse,
)Handle to a permission grant or revoke that KSeF applies asynchronously.
Returned by every grant_*() and revoke*() call of
auth.permissions. It exposes every field of the response, for example
reference_number, and wait() polls the operation until KSeF has
finished it. get_operation_status() on the permissions client reads the
same status for a reference number you stored earlier.
Raises
KSeFApiError— If KSeF returns an API error response.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncPermissionOperation.response (property)
response: GrantPermissionsResponseGet the plain operation response.
Returns
GrantPermissionsResponse— The data model KSeF returned when it accepted the operation.
AsyncPermissionOperation.get_status
async def get_status() -> PermissionOperationStatusResponseFetch the operation's current status without waiting.
Returns
PermissionOperationStatusResponse— The operation status;status.codeis200once it has completed successfully.
AsyncPermissionOperation.wait
async def wait(
*,
timeout: float = 60.0,
poll_interval: float = 1.0,
) -> PermissionOperationStatusResponsePoll until KSeF has finished the operation.
Parameters
timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between status checks.
Returns
PermissionOperationStatusResponse— The final status, withstatus.code200.
Raises
KSeFPermissionOperationFailedError— If KSeF finishes the operation without applying it.KSeFPermissionOperationTimeoutError— If polling exceedstimeout.
AsyncPermissionsClient
Import: from ksef2.clients import AsyncPermissionsClient
class AsyncPermissionsClientAsyncPermissionsClient(transport: AsyncMiddleware)Async high-level API for permission grants, revocations, and queries.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncPermissionsClient.grant_person
async def grant_person(
*,
subject_type: CertificateSubjectIdentifierType,
subject_value: str,
permissions: list[PersonPermissionScope],
description: str,
first_name: str,
last_name: str,
) -> AsyncPermissionOperationGrant person-scoped permissions to a subject identifier.
Parameters
subject_type(CertificateSubjectIdentifierType) — Kind of identifier insubject_value(nip,peselorfingerprint).subject_value(str) — Identifier of the person receiving the permissions.permissions(list[PersonPermissionScope]) — Permission scopes to grant; at least one is required.description(str) — Free-text reason for the grant.first_name(str) — First name of the person receiving the permissions.last_name(str) — Last name of the person receiving the permissions.
Returns
AsyncPermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
AsyncPermissionsClient.grant_entity
async def grant_entity(
*,
subject_value: str,
permissions: list[EntityPermission],
description: str,
entity_name: str,
) -> AsyncPermissionOperationGrant entity permissions to a NIP-identified entity.
Parameters
subject_value(str) — NIP of the entity receiving the permissions.permissions(list[EntityPermission]) — Permissions to grant, each with its delegation flag.description(str) — Free-text reason for the grant.entity_name(str) — Full name of the entity receiving the permissions.
Returns
AsyncPermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
AsyncPermissionsClient.grant_authorization
async def grant_authorization(
*,
subject_type: AuthorizationSubjectIdentifierType,
subject_value: str,
permission: AuthorizationPermissionType,
description: str,
entity_name: str,
) -> AsyncPermissionOperationGrant an authorization permission such as self-invoicing.
Parameters
subject_type(AuthorizationSubjectIdentifierType) — Kind of identifier insubject_value(niporpeppol_id).subject_value(str) — Identifier of the entity being authorized (NIP or Peppol ID).permission(AuthorizationPermissionType) — Authorization scope to grant, for exampleself_invoicing.description(str) — Free-text reason for the grant.entity_name(str) — Full name of the entity being authorized.
Returns
AsyncPermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
AsyncPermissionsClient.grant_indirect
async def grant_indirect(
*,
subject_type: CertificateSubjectIdentifierType,
subject_value: str,
permissions: list[IndirectPermissionType],
description: str,
first_name: str,
last_name: str,
target_type: IndirectTargetIdentifierType | None = None,
target_value: str | None = None,
) -> AsyncPermissionOperationGrant indirect permissions, optionally limited to a target entity.
Parameters
subject_type(CertificateSubjectIdentifierType) — Kind of identifier insubject_value(nip,peselorfingerprint).subject_value(str) — Identifier of the person receiving the indirect permissions.permissions(list[IndirectPermissionType]) — Indirect permission scopes to grant; at least one is required.description(str) — Free-text reason for the grant.first_name(str) — First name of the person receiving the permissions.last_name(str) — Last name of the person receiving the permissions.target_type(IndirectTargetIdentifierType | None) — Kind of identifier intarget_value;Noneorall_partnersscopes the grant to every partner.target_value(str | None) — Identifier of the partner context the grant is limited to;Nonewhen the target is all partners.
Returns
AsyncPermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
AsyncPermissionsClient.grant_subunit
async def grant_subunit(
*,
subject_type: CertificateSubjectIdentifierType,
subject_value: str,
context_type: SubunitIdentifierType,
context_value: str,
description: str,
first_name: str,
last_name: str,
subunit_name: str | None = None,
) -> AsyncPermissionOperationGrant permissions within a subunit context.
Parameters
subject_type(CertificateSubjectIdentifierType) — Kind of identifier insubject_value(nip,peselorfingerprint).subject_value(str) — Identifier of the person receiving the permissions.context_type(SubunitIdentifierType) — Kind of identifier incontext_value(niporinternal_id).context_value(str) — Identifier of the subunit context the permissions apply to.description(str) — Free-text reason for the grant.first_name(str) — First name of the person receiving the permissions.last_name(str) — Last name of the person receiving the permissions.subunit_name(str | None) — Display name of the subunit; optional.
Returns
AsyncPermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
AsyncPermissionsClient.grant_eu_entity
async def grant_eu_entity(
*,
subject_value: str,
permissions: list[EuEntityPermissionType],
description: str,
) -> AsyncPermissionOperationGrant permissions to an EU entity identified by fingerprint data.
Parameters
subject_value(str) — Fingerprint of the certificate of the person receiving the permissions.permissions(list[EuEntityPermissionType]) — EU-entity permission scopes to grant.description(str) — Free-text reason for the grant.
Returns
AsyncPermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
AsyncPermissionsClient.grant_eu_entity_administration
async def grant_eu_entity_administration(
*,
subject_value: str,
context_type: EuEntityAdminContextIdentifierType,
context_value: str,
description: str,
eu_entity_name: str,
) -> AsyncPermissionOperationGrant administration rights for an EU entity in a VAT UE context.
Parameters
subject_value(str) — Fingerprint of the certificate of the person receiving administration rights.context_type(EuEntityAdminContextIdentifierType) — Kind of identifier incontext_value; alwaysnip_vat_ue.context_value(str) — NIP-VAT UE identifier of the EU entity.description(str) — Free-text reason for the grant.eu_entity_name(str) — Full name of the EU entity.
Returns
AsyncPermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
AsyncPermissionsClient.revoke_authorization
async def revoke_authorization(*, permission_id: str) -> AsyncPermissionOperationRevoke an authorization permission by permission id.
Parameters
permission_id(str) — Identifier of the authorization permission, from a query result.
Returns
AsyncPermissionOperation— A handle to the asynchronous revoke operation; callwait()to wait until KSeF has applied it.
AsyncPermissionsClient.revoke
async def revoke(*, permission_id: str) -> AsyncPermissionOperationRevoke a non-authorization permission by permission id.
Use revoke_authorization() for authorization permissions such as self-invoicing.
Parameters
permission_id(str) — Identifier of the permission, from a query result.
Returns
AsyncPermissionOperation— A handle to the asynchronous revoke operation; callwait()to wait until KSeF has applied it.
Example
operation = await auth.permissions.revoke(permission_id=permission.id)
await operation.wait()AsyncPermissionsClient.revoke_common
def revoke_common(
*,
permission_id: str,
) -> Coroutine[None, None, GrantPermissionsResponse]Deprecated: revoke a non-authorization permission by permission id.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use revoke() instead.
Parameters
permission_id(str) — Identifier of the permission, from a query result.
Returns
Coroutine[None, None, GrantPermissionsResponse]— The reference of the asynchronous revoke operation; pollget_operation_status()for the result.
AsyncPermissionsClient.get_attachment_permission_status
async def get_attachment_permission_status() -> AttachmentPermissionStatusReturn whether attachments are currently allowed for the subject.
Returns
AttachmentPermissionStatus— Whether attachments are currently allowed for the subject.
AsyncPermissionsClient.get_operation_status
async def get_operation_status(
*,
reference_number: str,
) -> PermissionOperationStatusResponseFetch the status of an asynchronous permission operation.
Parameters
reference_number(str) — Reference number returned by a grant or revoke call.
Returns
PermissionOperationStatusResponse— The operation status;status.codeis200once it has completed successfully.
AsyncPermissionsClient.get_entity_roles
def get_entity_roles(
*,
params: OffsetPaginationParams | None = None,
) -> Coroutine[None, None, EntityRolesResponse]Deprecated: fetch one page of roles assigned to the authenticated entity.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_entity_roles() instead; first_page() fetches one page.
Parameters
params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
Coroutine[None, None, EntityRolesResponse]— One page of roles assigned to the authenticated entity.
AsyncPermissionsClient.query_authorizations
def query_authorizations(
*,
query: AuthorizationPermissionsQuery,
params: OffsetPaginationParams | None = None,
) -> Coroutine[None, None, AuthorizationPermissionsQueryResponse]Deprecated: fetch one page of authorization grants matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_authorizations() instead; first_page() fetches one page.
Parameters
query(AuthorizationPermissionsQuery) — Filters for the authorization grants.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
Coroutine[None, None, AuthorizationPermissionsQueryResponse]— One page of authorization grants.
AsyncPermissionsClient.query_entities
def query_entities(
*,
query: EntityPermissionsQuery,
params: OffsetPaginationParams | None = None,
) -> Coroutine[None, None, EntityPermissionsQueryResponse]Deprecated: fetch one page of entity permission grants matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_entities() instead; first_page() fetches one page.
Parameters
query(EntityPermissionsQuery) — Filters for the entity permissions.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
Coroutine[None, None, EntityPermissionsQueryResponse]— One page of entity permissions.
AsyncPermissionsClient.query_eu_entities
def query_eu_entities(
*,
query: EuEntityPermissionsQuery,
params: OffsetPaginationParams | None = None,
) -> Coroutine[None, None, EuEntityPermissionsQueryResponse]Deprecated: fetch one page of EU-entity permissions matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_eu_entities() instead; first_page() fetches one page.
Parameters
query(EuEntityPermissionsQuery) — Filters for the EU-entity permissions.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
Coroutine[None, None, EuEntityPermissionsQueryResponse]— One page of EU-entity permissions.
AsyncPermissionsClient.query_personal
def query_personal(
*,
query: PersonalPermissionsQuery,
params: OffsetPaginationParams | None = None,
) -> Coroutine[None, None, PersonalPermissionsQueryResponse]Deprecated: fetch one page of permissions held by the authenticated subject.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_personal() instead; first_page() fetches one page.
Parameters
query(PersonalPermissionsQuery) — Filters for the permissions.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
Coroutine[None, None, PersonalPermissionsQueryResponse]— One page of permissions held by the authenticated subject.
AsyncPermissionsClient.query_persons
def query_persons(
*,
query: PersonPermissionsQuery,
params: OffsetPaginationParams | None = None,
) -> Coroutine[None, None, PersonPermissionsQueryResponse]Deprecated: fetch one page of person permission grants matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_persons() instead; first_page() fetches one page.
Parameters
query(PersonPermissionsQuery) — Filters for the person permissions.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
Coroutine[None, None, PersonPermissionsQueryResponse]— One page of person permissions.
AsyncPermissionsClient.query_subordinate_entities
def query_subordinate_entities(
*,
query: SubordinateEntityRolesQuery,
params: OffsetPaginationParams | None = None,
) -> Coroutine[None, None, SubordinateEntityRolesQueryResponse]Deprecated: fetch one page of subordinate entity roles.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_subordinate_entities() instead; first_page() fetches one page.
Parameters
query(SubordinateEntityRolesQuery) — Filters for the subordinate entity roles.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
Coroutine[None, None, SubordinateEntityRolesQueryResponse]— One page of subordinate entity roles.
AsyncPermissionsClient.query_subunits
def query_subunits(
*,
query: SubunitPermissionsQuery,
params: OffsetPaginationParams | None = None,
) -> Coroutine[None, None, SubunitPermissionsQueryResponse]Deprecated: fetch one page of subunit permission grants.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_subunits() instead; first_page() fetches one page.
Parameters
query(SubunitPermissionsQuery) — Filters for the subunit permissions.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
Coroutine[None, None, SubunitPermissionsQueryResponse]— One page of subunit permissions.
AsyncPermissionsClient.list_entity_roles
def list_entity_roles(
*,
params: OffsetPaginationParams | None = None,
) -> AsyncPager[EntityRole]List the roles assigned to the authenticated entity.
Nothing is requested until the result is consumed. Iterate it for every
role, call pages() for page-sized lists or first_page() for one
request only.
Parameters
params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
AsyncPager[EntityRole]— A paging object over the roles assigned to the authenticated entity.
Example
async for role in auth.permissions.list_entity_roles():
print(role.role)AsyncPermissionsClient.list_authorizations
def list_authorizations(
query: AuthorizationPermissionsQuery,
*,
params: OffsetPaginationParams | None = None,
) -> AsyncPager[AuthorizationGrantDetail]List the authorization grants matching the provided filters.
Nothing is requested until the result is consumed. Iterate it for every
grant, call pages() for page-sized lists or first_page() for one
request only.
Parameters
query(AuthorizationPermissionsQuery) — Filters for the authorization grants.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
AsyncPager[AuthorizationGrantDetail]— A paging object over the authorization grants.
Example
async for grant in auth.permissions.list_authorizations(query):
print(grant.id)AsyncPermissionsClient.list_entities
def list_entities(
query: EntityPermissionsQuery,
*,
params: OffsetPaginationParams | None = None,
) -> AsyncPager[EntityPermissionDetail]List the entity permission grants matching the provided filters.
Nothing is requested until the result is consumed. Iterate it for every
grant, call pages() for page-sized lists or first_page() for one
request only.
Parameters
query(EntityPermissionsQuery) — Filters for the entity permissions.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
AsyncPager[EntityPermissionDetail]— A paging object over the entity permissions.
Example
async for permission in auth.permissions.list_entities(query):
print(permission.id)AsyncPermissionsClient.list_eu_entities
def list_eu_entities(
query: EuEntityPermissionsQuery,
*,
params: OffsetPaginationParams | None = None,
) -> AsyncPager[EuEntityPermission]List the EU-entity permissions matching the provided filters.
Nothing is requested until the result is consumed. Iterate it for every
permission, call pages() for page-sized lists or first_page() for
one request only.
Parameters
query(EuEntityPermissionsQuery) — Filters for the EU-entity permissions.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
AsyncPager[EuEntityPermission]— A paging object over the EU-entity permissions.
Example
async for permission in auth.permissions.list_eu_entities(query):
print(permission.id)AsyncPermissionsClient.list_personal
def list_personal(
query: PersonalPermissionsQuery,
*,
params: OffsetPaginationParams | None = None,
) -> AsyncPager[PersonalPermissionDetail]List the permissions held by the authenticated subject.
Nothing is requested until the result is consumed. Iterate it for every
permission, call pages() for page-sized lists or first_page() for
one request only.
Parameters
query(PersonalPermissionsQuery) — Filters for the permissions.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
AsyncPager[PersonalPermissionDetail]— A paging object over the permissions held by the authenticated subject.
Example
async for permission in auth.permissions.list_personal(query):
print(permission.id)AsyncPermissionsClient.list_persons
def list_persons(
query: PersonPermissionsQuery,
*,
params: OffsetPaginationParams | None = None,
) -> AsyncPager[PersonPermissionDetail]List the person permission grants matching the provided filters.
Nothing is requested until the result is consumed. Iterate it for every
grant, call pages() for page-sized lists or first_page() for one
request only.
Parameters
query(PersonPermissionsQuery) — Filters for the person permissions.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
AsyncPager[PersonPermissionDetail]— A paging object over the person permissions.
Example
async for permission in auth.permissions.list_persons(query):
print(permission.id)AsyncPermissionsClient.list_subordinate_entities
def list_subordinate_entities(
query: SubordinateEntityRolesQuery,
*,
params: OffsetPaginationParams | None = None,
) -> AsyncPager[SubordinateEntityRoleDetail]List the subordinate entity roles matching the provided filters.
Nothing is requested until the result is consumed. Iterate it for every
role, call pages() for page-sized lists or first_page() for one
request only.
Parameters
query(SubordinateEntityRolesQuery) — Filters for the subordinate entity roles.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
AsyncPager[SubordinateEntityRoleDetail]— A paging object over the subordinate entity roles.
Example
async for role in auth.permissions.list_subordinate_entities(query):
print(role.role)AsyncPermissionsClient.list_subunits
def list_subunits(
query: SubunitPermissionsQuery,
*,
params: OffsetPaginationParams | None = None,
) -> AsyncPager[SubunitPermission]List the subunit permission grants matching the provided filters.
Nothing is requested until the result is consumed. Iterate it for every
grant, call pages() for page-sized lists or first_page() for one
request only.
Parameters
query(SubunitPermissionsQuery) — Filters for the subunit permissions.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
AsyncPager[SubunitPermission]— A paging object over the subunit permissions.
Example
async for permission in auth.permissions.list_subunits(query):
print(permission.id)AsyncSessionManagementClient
Import: from ksef2.clients import AsyncSessionManagementClient
class AsyncSessionManagementClientAsyncSessionManagementClient(transport: AsyncMiddleware)Async manage authentication sessions opened through the auth API.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncSessionManagementClient.query
def query(
*,
page_size: int | None = None,
continuation_token: str | None = None,
) -> Coroutine[None, None, AuthenticationSessionsResponse]Deprecated: fetch one page of authentication sessions.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead; first_page() fetches one page.
Parameters
page_size(int | None) — Maximum number of sessions to request from KSeF.continuation_token(str | None) — Cursor returned by a previous page.
Returns
Coroutine[None, None, AuthenticationSessionsResponse]— One page of authentication sessions for the current subject.
AsyncSessionManagementClient.all
async def all(
*,
page_size: int | None = None,
) -> AsyncIterator[AuthenticationSessionsResponse]Deprecated: iterate through all authentication session pages.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list().pages() instead.
Parameters
page_size(int | None) — Maximum number of sessions to request per page.
Yields
AsyncIterator[AuthenticationSessionsResponse]— Successive pages of authentication sessions until KSeF stopsAsyncIterator[AuthenticationSessionsResponse]— returning a continuation token.
AsyncSessionManagementClient.terminate_current
async def terminate_current() -> NoneTerminate the authentication session backing the current bearer token.
AsyncSessionManagementClient.terminate
async def terminate(reference_number: str) -> NoneTerminate an authentication session by reference number.
Parameters
reference_number(str) — Reference number of the authentication session to terminate.
AsyncSessionManagementClient.close
def close(*, reference_number: str) -> Coroutine[None, None, None]Deprecated: terminate an authentication session by reference number.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use terminate() instead.
Parameters
reference_number(str) — Reference number of the authentication session to terminate.
Returns
Coroutine[None, None, None]—Noneonce the session is terminated.
AsyncSessionManagementClient.list
def list(*, page_size: int | None = None) -> AsyncPager[AuthenticationSession]List the authentication sessions of the current subject.
Nothing is requested until the result is consumed. Iterate it for every
session, call pages() for page-sized lists or first_page() for one
request only.
Parameters
page_size(int | None) — Maximum number of sessions to request per page; the KSeF default whenNone.
Returns
AsyncPager[AuthenticationSession]— A paging object over the authentication sessions.
Example
async for session in auth.sessions.list():
print(session.reference_number)AsyncTemporalTestData
Import: from ksef2.clients import AsyncTemporalTestData
class AsyncTemporalTestDataAsyncTemporalTestData(client: AsyncTestDataClient)Async context manager that records testdata mutations and reverts them on exit.
Cleanup failures are logged and suppressed. Direct mutation methods expose the same catch contract as the parent test-data branch.
Raises
KSeFApiError— If KSeF returns an API error response during direct mutations.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncTemporalTestData.create_subject
async def create_subject(
*,
nip: str,
subject_type: SubjectType,
description: str,
subunits: list[SubUnit] | None = None,
created_date: datetime | None = None,
) -> NoneCreate a TEST subject and register it for context-manager cleanup.
Parameters
nip(str) — NIP of the subject to create.subject_type(SubjectType) — Kind of subject, such as an enforcement authority or a VAT group.description(str) — Description of the subject.subunits(list[SubUnit] | None) — Subunits to create with the subject;Nonefor none.created_date(datetime | None) — Creation date to record for the subject;Nonefor now.
AsyncTemporalTestData.delete_subject
async def delete_subject(*, nip: str) -> NoneDelete a TEST subject and remove it from cleanup tracking.
Parameters
nip(str) — NIP of the subject to delete.
AsyncTemporalTestData.create_person
async def create_person(
*,
nip: str,
pesel: str,
description: str,
is_bailiff: bool = False,
is_deceased: bool = False,
created_date: datetime | None = None,
) -> NoneCreate a TEST person and register it for context-manager cleanup.
Parameters
nip(str) — NIP of the person.pesel(str) — PESEL of the person.description(str) — Description of the person.is_bailiff(bool) — Whether the person is a bailiff.is_deceased(bool) — Whether the person is marked as deceased.created_date(datetime | None) — Creation date to record for the person;Nonefor now.
AsyncTemporalTestData.delete_person
async def delete_person(*, nip: str) -> NoneDelete a TEST person and remove it from cleanup tracking.
Parameters
nip(str) — NIP of the person to delete.
AsyncTemporalTestData.grant_permissions
async def grant_permissions(
*,
permissions: list[Permission],
grant_to: Identifier,
in_context_of: Identifier,
) -> NoneGrant TEST permissions and register them for cleanup.
Parameters
permissions(list[Permission]) — Permissions to grant.grant_to(Identifier) — Identifier of the subject receiving the permissions.in_context_of(Identifier) — Identifier of the context in which the permissions apply.
AsyncTemporalTestData.revoke_permissions
async def revoke_permissions(
*,
revoke_from: Identifier,
in_context_of: Identifier,
) -> NoneRevoke TEST permissions and remove them from cleanup tracking.
Parameters
revoke_from(Identifier) — Identifier of the subject losing the permissions.in_context_of(Identifier) — Identifier of the context from which the permissions are revoked.
AsyncTemporalTestData.enable_attachments
async def enable_attachments(*, nip: str) -> NoneEnable TEST attachments and register the context for cleanup.
Parameters
nip(str) — NIP of the subject to enable attachments for.
AsyncTemporalTestData.revoke_attachments
async def revoke_attachments(*, nip: str, expected_end_date: date | None = None) -> NoneRevoke TEST attachment access and remove it from cleanup tracking.
Parameters
nip(str) — NIP of the subject to revoke attachments for.expected_end_date(date | None) — Date on which attachment permission should end;Noneto revoke immediately.
AsyncTemporalTestData.block_context
async def block_context(*, context: AuthContextIdentifier) -> NoneBlock a TEST context and register it for cleanup.
Parameters
context(AuthContextIdentifier) — Authentication context to block.
AsyncTemporalTestData.unblock_context
async def unblock_context(*, context: AuthContextIdentifier) -> NoneUnblock a TEST context and remove it from cleanup tracking.
Parameters
context(AuthContextIdentifier) — Authentication context to unblock.
AsyncTestDataClient
Import: from ksef2.clients import AsyncTestDataClient
class AsyncTestDataClientAsyncTestDataClient(transport: AsyncMiddleware)Async helper for TEST-only endpoints that seed and mutate sandbox data.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncTestDataClient.create_subject
async def create_subject(
*,
nip: str,
subject_type: SubjectType,
description: str,
subunits: list[SubUnit] | None = None,
created_date: datetime | None = None,
) -> NoneCreate a test subject with optional subunits.
Parameters
nip(str) — NIP of the subject to create.subject_type(SubjectType) — Kind of subject, such as an enforcement authority or a VAT group.description(str) — Description of the subject.subunits(list[SubUnit] | None) — Subunits to create with the subject;Nonefor none.created_date(datetime | None) — Creation date to record for the subject;Nonefor now.
AsyncTestDataClient.delete_subject
async def delete_subject(*, nip: str) -> NoneDelete a test subject by NIP.
Parameters
nip(str) — NIP of the subject to delete.
AsyncTestDataClient.create_person
async def create_person(
*,
nip: str,
pesel: str,
description: str,
is_bailiff: bool = False,
is_deceased: bool = False,
created_date: datetime | None = None,
) -> NoneCreate a test person in the chosen subject.
Parameters
nip(str) — NIP of the person.pesel(str) — PESEL of the person.description(str) — Description of the person.is_bailiff(bool) — Whether the person is a bailiff.is_deceased(bool) — Whether the person is marked as deceased.created_date(datetime | None) — Creation date to record for the person;Nonefor now.
AsyncTestDataClient.delete_person
async def delete_person(*, nip: str) -> NoneDelete a test person by subject NIP.
Parameters
nip(str) — NIP of the person to delete.
AsyncTestDataClient.grant_permissions
async def grant_permissions(
*,
permissions: list[Permission],
grant_to: Identifier,
in_context_of: Identifier,
) -> NoneGrant test permissions in a chosen context.
Parameters
permissions(list[Permission]) — Permissions to grant.grant_to(Identifier) — Identifier of the subject receiving the permissions.in_context_of(Identifier) — Identifier of the context in which the permissions apply.
AsyncTestDataClient.revoke_permissions
async def revoke_permissions(
*,
revoke_from: Identifier,
in_context_of: Identifier,
) -> NoneRevoke test permissions in a chosen context.
Parameters
revoke_from(Identifier) — Identifier of the subject losing the permissions.in_context_of(Identifier) — Identifier of the context from which the permissions are revoked.
AsyncTestDataClient.enable_attachments
async def enable_attachments(*, nip: str) -> NoneEnable invoice attachments for a test subject.
Parameters
nip(str) — NIP of the subject to enable attachments for.
AsyncTestDataClient.revoke_attachments
async def revoke_attachments(*, nip: str, expected_end_date: date | None = None) -> NoneRevoke attachment permissions, optionally effective on a given date.
Parameters
nip(str) — NIP of the subject to revoke attachments for.expected_end_date(date | None) — Date on which attachment permission should end;Noneto revoke immediately.
AsyncTestDataClient.block_context
async def block_context(*, context: AuthContextIdentifier) -> NoneBlock authentication for a specific test context.
Parameters
context(AuthContextIdentifier) — Authentication context to block.
AsyncTestDataClient.unblock_context
async def unblock_context(*, context: AuthContextIdentifier) -> NoneUnblock authentication for a specific test context.
Parameters
context(AuthContextIdentifier) — Authentication context to unblock.
AsyncTestDataClient.update_certificate_valid_to
async def update_certificate_valid_to(*, serial_number: str, valid_to: datetime) -> NoneShorten the validity of a certificate in the TEST environment.
Parameters
serial_number(str) — Serial number of the certificate to shorten.valid_to(datetime) — New, earlier end of the certificate validity period.
AsyncTestDataClient.temporal
def temporal() -> AsyncTemporalTestDataReturn a context manager that automatically cleans up created test data.
Returns
AsyncTemporalTestData— A context manager that automatically cleans up created test data.
AsyncTokensClient
Import: from ksef2.clients import AsyncTokensClient
class AsyncTokensClientAsyncTokensClient(transport: AsyncMiddleware)Async high-level API for the KSeF token lifecycle.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AsyncTokensClient.wait_for_activation
def wait_for_activation(
*,
reference_number: str,
timeout: float = 60.0,
poll_interval: float = 1.0,
) -> Coroutine[None, None, TokenStatusResponse]Deprecated: wait until a generated token becomes active or reaches a terminal state.
Deprecated
May be removed no earlier than ksef2 2.0.0. Call wait() on the handle returned by generate() instead.
Parameters
reference_number(str) — Reference returned bygenerate.timeout(float) — Maximum number of seconds to wait for activation.poll_interval(float) — Delay in seconds between status checks.
Returns
Coroutine[None, None, TokenStatusResponse]— The first status response that reports the token as active.
Raises
KSeFApiError— If activation ends in a terminal failure state.KSeFTokenStatusTimeoutError— If polling exceedstimeout.httpx.HTTPError— If a status request fails at the transport boundary.
AsyncTokensClient.generate
async def generate(
*,
permissions: builtins.list[TokenPermission],
description: str,
) -> AsyncGeneratedTokenCreate a token and return a handle exposing its one-time credential.
Parameters
permissions(builtins.list[TokenPermission]) — Permissions to include in the generated token.description(str) — Human-readable label shown in KSeF token listings.
Returns
AsyncGeneratedToken— A handle whosetokenis the one-time secret KSeF returns only once;AsyncGeneratedToken— persist it before calling the handle'swait()for activation.
Example
token = await auth.tokens.generate(
permissions=["invoice_read"], description="reporting"
)
secret = token.token # store it now, KSeF will not show it again
await token.wait()AsyncTokensClient.list_page
def list_page(
*,
continuation_token: str | None = None,
params: TokenListParams | None = None,
) -> Coroutine[None, None, QueryTokensResponse]Deprecated: fetch one page of tokens using optional filters and continuation state.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead; first_page() fetches one page.
Parameters
continuation_token(str | None) — Token identifying the next page to fetch.params(TokenListParams | None) — Optional filters and page size for the request.
Returns
Coroutine[None, None, QueryTokensResponse]— A single page of token results.
AsyncTokensClient.list_all
async def list_all(
*,
params: TokenListParams | None = None,
) -> AsyncIterator[QueryTokensResponse]Deprecated: iterate through all token pages until KSeF stops returning a continuation token.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list().pages() instead.
Parameters
params(TokenListParams | None) — Optional filters and page size applied to every request.
Yields
AsyncIterator[QueryTokensResponse]— Each page returned by the token listing endpoint.
AsyncTokensClient.get_status
async def get_status(*, reference_number: str) -> TokenStatusResponseReturn the current status of a token.
Parameters
reference_number(str) — Reference number of the token.
Returns
TokenStatusResponse— The token's current lifecycle status.
AsyncTokensClient.status
def status(*, reference_number: str) -> Coroutine[None, None, TokenStatusResponse]Deprecated: return the current status of a token.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use get_status() instead.
Parameters
reference_number(str) — Reference number of the token.
Returns
Coroutine[None, None, TokenStatusResponse]— The token's current lifecycle status.
AsyncTokensClient.revoke
async def revoke(*, reference_number: str) -> NoneRevoke a token.
Parameters
reference_number(str) — Reference number of the token to revoke.
AsyncTokensClient.list
def list(*, params: TokenListParams | None = None) -> AsyncPager[TokenInfo]List the tokens of the authenticated context.
Nothing is requested until the result is consumed. Iterate it for every
token, call pages() for page-sized lists or first_page() for one
request only.
Parameters
params(TokenListParams | None) — Optional filters and page size applied to every request.
Returns
AsyncPager[TokenInfo]— A paging object over the tokens matchingparams.
Example
async for token in auth.tokens.list():
print(token.reference_number, token.status)AuthClient
Import: from ksef2.clients import AuthClient
class AuthClientAuthClient(
transport: Middleware,
certificate_store: CertificateStoreProtocol,
environment: Environment = Environment.PRODUCTION,
transfer_transport: Middleware | None = None,
auto_refresh_tokens: bool = True,
)Entry point for creating authenticated SDK clients.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AuthClient.resume
def resume(state: AuthenticationResumeState | str) -> AuthenticatedClientRehydrate an authenticated client from saved authentication state.
The client refreshes its access token automatically unless
TransportConfig.auto_refresh_tokens is False, so a state whose
access token has expired still works while its refresh token is valid.
Parameters
state(AuthenticationResumeState | str) — State previously exported from an authenticated client, or its JSON string.
Returns
AuthenticatedClient— An authenticated client bound to the saved tokens.
AuthClient.with_token
def with_token(
*,
ksef_token: str,
nip: str,
context_type: ContextIdentifierType = 'nip',
timeout: float = 60.0,
poll_interval: float = 1.0,
) -> AuthenticatedClientAuthenticate with a KSeF token and return an authenticated client.
Parameters
ksef_token(str) — Token generated in KSeF for the target context.nip(str) — Context identifier value used for authentication.context_type(ContextIdentifierType) — Type of identifier represented bynip.timeout(float) — Maximum number of seconds to wait for authentication.poll_interval(float) — Delay in seconds between authentication status checks.
Returns
AuthenticatedClient— An authenticated client with redeemed access and refresh tokens.
Raises
NoCertificateAvailableError— If no valid token-encryption certificate is available.KSeFEncryptionError— If token encryption fails.KSeFAuthError— If authentication fails.KSeFAuthPollingTimeoutError— If polling exceedstimeout.
Example
client = Client(Environment.TEST)
auth = client.authentication.with_token(
ksef_token="your-ksef-token",
nip="5261040828",
)AuthClient.with_xades
def with_xades(
*,
nip: str,
cert: Certificate,
private_key: XAdESPrivateKey,
verify_chain: bool = False,
timeout: float = 60.0,
poll_interval: float = 1.0,
) -> AuthenticatedClientAuthenticate with an XAdES-signed challenge response.
Parameters
nip(str) — Taxpayer identifier embedded in the authentication request.cert(Certificate) — Signing certificate accepted by the target environment.private_key(XAdESPrivateKey) — RSA or EC private key used to sign the XAdES payload.verify_chain(bool) — Whether KSeF should verify the certificate chain.timeout(float) — Maximum number of seconds to wait for authentication.poll_interval(float) — Delay in seconds between authentication status checks.
Returns
AuthenticatedClient— An authenticated client with redeemed access and refresh tokens.
Raises
KSeFAuthError— If authentication fails.KSeFAuthPollingTimeoutError— If polling exceedstimeout.
Example
from ksef2.xades import load_certificate_from_pem, load_private_key_from_pem
client = Client(Environment.DEMO)
auth = client.authentication.with_xades(
nip="5261040828",
cert=load_certificate_from_pem("company.pem"),
private_key=load_private_key_from_pem("company.key"),
)AuthClient.with_test_certificate
def with_test_certificate(
*,
nip: str,
verify_chain: bool = False,
timeout: float = 60.0,
poll_interval: float = 1.0,
) -> AuthenticatedClientAuthenticate in the TEST environment using an SDK-generated certificate.
Parameters
nip(str) — NIP to authenticate as; the generated certificate is issued for it.verify_chain(bool) — Whether KSeF should verify the certificate chain.timeout(float) — Maximum number of seconds to wait for authentication.poll_interval(float) — Delay in seconds between authentication status checks.
Returns
AuthenticatedClient— An authenticated client for the NIP's context.
Raises
KSeFUnsupportedEnvironmentError— If the client is not configured for TEST.KSeFAuthError— If authentication fails.KSeFAuthPollingTimeoutError— If polling exceedstimeout.
Example
client = Client(Environment.TEST)
auth = client.authentication.with_test_certificate(nip="5261040828")AuthClient.with_profile
def with_profile(
name: str | None = None,
*,
config_path: str | Path | None = None,
timeout: float | None = None,
poll_interval: float | None = None,
verify_chain: bool = False,
) -> AuthenticatedClientAuthenticate with a local ksef2-cli profile.
Profile selection follows the CLI order: explicit name,
KSEF2_PROFILE, then active_profile from the local CLI config.
The profile environment must match the root client environment.
Parameters
name(str | None) — Profile name; whenNone,KSEF2_PROFILEand then the CLI's active profile are used.config_path(str | Path | None) — Path of theksef2-cliconfig file; the default location is used whenNone.timeout(float | None) — Maximum number of seconds to wait for authentication; defaults to the profile's polling settings, else 60.poll_interval(float | None) — Delay in seconds between authentication status checks; defaults to the profile's value, else 1.verify_chain(bool) — Whether KSeF should verify the certificate chain, for certificate-based profiles.
Returns
AuthenticatedClient— An authenticated client for the profile's context.
Raises
KSeFValidationError— If the profile's environment differs from the client's, or the profile is missing a required secret.KSeFAuthError— If authentication fails.KSeFAuthPollingTimeoutError— If polling exceedstimeout.
Example
client = Client(Environment.TEST)
auth = client.authentication.with_profile("test-company")AuthClient.refresh
def refresh(*, refresh_token: str) -> RefreshedTokenExchange a refresh token for a new access token.
Parameters
refresh_token(str) — Refresh token obtained during authentication.
Returns
RefreshedToken— A new access token with its expiry time.
AuthenticatedClient
Import: from ksef2.clients import AuthenticatedClient
class AuthenticatedClientAuthenticatedClient(
transport: Middleware,
auth_tokens: AuthTokens,
certificate_store: CertificateStoreProtocol,
environment: Environment = Environment.PRODUCTION,
transfer_transport: Middleware | None = None,
refresh_access_token: Refresh | None = None,
)Authenticated entry point for KSeF operations.
Catch KSeFException for SDK-classified failures raised by authenticated
branches, and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
AuthenticatedClient.auth_tokens (property)
auth_tokens: AuthTokensReturn the authenticated token pair used by this client branch.
Reflects automatic refreshes: after the access token is renewed, this holds the new access token alongside the original refresh token.
Returns
AuthTokens— The current authenticated token pair of this client branch.
AuthenticatedClient.access_token (property)
access_token: strReturn the bearer access token string used for authenticated calls.
Returns
str— The bearer access token string used for authenticated calls.
AuthenticatedClient.refresh_token (property)
refresh_token: strReturn the refresh token string paired with the access token.
Returns
str— The refresh token string paired with the access token.
AuthenticatedClient.resume_state
def resume_state() -> AuthenticationResumeStateReturn the authentication state needed to rehydrate this branch later.
The state holds the current tokens, so it includes any access token obtained through automatic refresh.
Returns
AuthenticationResumeState— The authentication state needed to rehydrate this branch later.
AuthenticatedClient.get_encryption_key
def get_encryption_key() -> tuple[bytes, bytes, bytes]Generate a session AES key, IV, and encrypted symmetric key payload.
Returns
tuple[bytes, bytes, bytes]— A tuple of the raw AES key, the initialization vector and the AES key encrypted with the KSeF public key.
Raises
NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If symmetric-key encryption fails.
AuthenticatedClient.online_session
def online_session(
*,
form_code: FormSchema | None = None,
state: OnlineSessionResumeState | str | None = None,
) -> OnlineSessionClientOpen a new online invoice session, or resume one from saved state.
Pass exactly one of form_code (open a new session) or state
(resume). When resuming, the form code, keys and expiry all come from the
state. Leaving the with block closes the session in both cases;
closing an already-closed session is a no-op.
Parameters
form_code(FormSchema | None) — Invoice schema the new session accepts, for exampleFormSchema.FA3.state(OnlineSessionResumeState | str | None) — State fromsession.resume_state(), or its JSON string, to resume an open session.
Returns
OnlineSessionClient— A session client that can be used as a context manager and closes the session on exit.
Raises
KSeFArgumentError— If neither or both ofform_codeandstateare given.NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If symmetric-key encryption fails.KSeFValidationError— Ifstateis not valid online session state.
Example
from ksef2.models import FormSchema
with auth.online_session(form_code=FormSchema.FA3) as session:
submission = session.send_invoice(xml_bytes)
saved = session.resume_state().to_json()
with auth.online_session(state=saved) as session:
result = session.submission(reference_number).wait()AuthenticatedClient.resume_online_session
def resume_online_session(state: OnlineSessionResumeState) -> OnlineSessionClientDeprecated: rebind an existing serialized online session state to this client.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use online_session(state=...) instead.
Parameters
state(OnlineSessionResumeState) — State previously exported from an online session client.
Returns
OnlineSessionClient— An online session client bound to the saved state.
AuthenticatedClient.batch_session
def batch_session(
*,
prepared_batch: PreparedBatch | None = None,
batch_file: BatchFileInfo | None = None,
form_code: FormSchema | None = None,
offline_mode: bool | None = None,
state: BatchSessionResumeState | str | None = None,
) -> BatchSessionClientOpen a batch session for upload work, or resume one from saved state.
Pass exactly one of prepared_batch, batch_file (open a new
session) or state (resume). When resuming, everything comes from the
state, including the form code, keys and part upload requests. Leaving the
with block closes the session in every case; closing an already-closed
session is a no-op.
Parameters
prepared_batch(PreparedBatch | None) — Prepared batch payload created byauth.batch.prepare().batch_file(BatchFileInfo | None) — Declared ZIP package metadata and encrypted part metadata.form_code(FormSchema | None) — Invoice schema declared for the batch session whenbatch_fileis provided directly; defaults toFormSchema.FA3.offline_mode(bool | None) — Whether to declare offline invoicing mode for the batch whenbatch_fileis provided directly; defaults toFalse.state(BatchSessionResumeState | str | None) — State fromsession.resume_state(), or its JSON string, to resume a batch session.
Returns
BatchSessionClient— A bound batch session client exposing presigned upload instructions.
Raises
KSeFArgumentError— If not exactly one ofprepared_batch,batch_fileandstateis given, orform_codeoroffline_modeis combined withprepared_batchorstate.NoCertificateAvailableError— If certificate-backed encryption material is needed but no valid certificate is available.KSeFEncryptionError— If symmetric-key encryption fails.KSeFValidationError— Ifstateis not valid batch session state.
Example
from ksef2.models import BatchInvoice
prepared = auth.batch.prepare(
[BatchInvoice(file_name="invoice-1.xml", content=xml_bytes)],
)
with auth.batch_session(prepared_batch=prepared) as session:
session.upload_parts()
saved = session.resume_state().to_json()
with auth.batch_session(state=saved) as session:
final = session.wait()AuthenticatedClient.open_batch_session
def open_batch_session(
*,
batch_file: BatchFileInfo,
aes_key: bytes,
iv: bytes,
encrypted_key: bytes,
public_key_id: str | None = None,
form_code: FormSchema = FormSchema.FA3,
offline_mode: bool = False,
prepared_batch: PreparedBatch | None = None,
) -> BatchSessionClientDeprecated: open a batch session using caller-prepared encryption metadata.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use auth.batch_session() for the standard flow, or raw for caller-supplied encryption material.
Parameters
batch_file(BatchFileInfo) — Declared ZIP package metadata and encrypted part metadata.aes_key(bytes) — Raw symmetric key used for part encryption.iv(bytes) — Initialization vector paired withaes_key.encrypted_key(bytes) — RSA-encrypted symmetric key sent to KSeF.public_key_id(str | None) — Identifier of the KSeF public key used for encryption.form_code(FormSchema) — Invoice schema declared for the batch session.offline_mode(bool) — Whether to declare offline invoicing mode for the batch.prepared_batch(PreparedBatch | None) — Optional prepared batch payload to attach to the returned session sosession.upload_parts()can operate without extra args.
Returns
BatchSessionClient— A bound batch session client exposing presigned upload instructions.
Raises
KSeFValidationError— If the batch session request is invalid.
AuthenticatedClient.resume_batch_session
def resume_batch_session(state: BatchSessionResumeState) -> BatchSessionClientDeprecated: rebind an existing serialized batch session state to this client.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use batch_session(state=...) instead.
Parameters
state(BatchSessionResumeState) — State previously exported from a batch session client.
Returns
BatchSessionClient— A batch session client bound to the saved state.
AuthenticatedClient.invoices (property)
invoices: InvoicesServiceReturn the invoices service with encryption support configured.
Returns
InvoicesService— The invoices service with encryption support configured.
AuthenticatedClient.batch (property)
batch: BatchServiceReturn the high-level batch upload workflow service.
The service orchestrates package preparation, session opening, presigned part uploads, session closing, and status polling.
Returns
BatchService— The batch upload service.
AuthenticatedClient.limits (property)
limits: LimitsClientReturn the authenticated rate-limit branch.
Returns
LimitsClient— The authenticated rate-limit branch.
AuthenticatedClient.collective_identifiers (property)
collective_identifiers: CollectiveIdentifiersClientReturn the collective invoice identifier branch.
Returns
CollectiveIdentifiersClient— The collective invoice identifier branch.
AuthenticatedClient.tokens (property)
tokens: TokensClientReturn the authenticated token lifecycle branch.
Returns
TokensClient— The authenticated token lifecycle branch.
AuthenticatedClient.certificates (property)
certificates: CertificatesClientReturn the authenticated certificate enrollment branch.
Returns
CertificatesClient— The authenticated certificate enrollment branch.
AuthenticatedClient.sessions (property)
sessions: SessionManagementClientReturn the authenticated session-management branch.
Returns
SessionManagementClient— The authenticated session-management branch.
AuthenticatedClient.invoice_sessions (property)
invoice_sessions: InvoiceSessionsClientReturn the authenticated invoice-session history branch.
Returns
InvoiceSessionsClient— The authenticated invoice-session history branch.
AuthenticatedClient.permissions (property)
permissions: PermissionsClientReturn the authenticated permissions branch.
Returns
PermissionsClient— The authenticated permissions branch.
AuthenticatedClient.testdata (property)
testdata: TestDataClientReturn authenticated TEST-only data mutation helpers.
Returns
TestDataClient— Authenticated TEST-only data mutation helpers.
AuthenticatedClient.raw (property)
raw: RawAuthenticatedClientReturn raw authenticated endpoints for advanced integrations.
Returns
RawAuthenticatedClient— Raw authenticated endpoints for advanced integrations.
BatchService
Import: from ksef2.clients import BatchService
class BatchServiceBatchService(
*,
authed_transport: Middleware,
upload_transport: Middleware,
get_encryption_key: Callable[[], SessionEncryptionMaterial],
open_batch_session: BatchSessionOpener,
)High-level workflow for preparing and sending invoice batches.
Catch KSeFException for SDK-classified failures raised by this service,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
BatchService.prepare
def prepare(
invoices: Iterable[bytes | str | Path | BatchInvoice],
*,
form_code: FormSchema = FormSchema.FA3,
offline_mode: bool = False,
max_part_size: int = MAX_BATCH_PART_SIZE,
) -> PreparedBatchBuild a ZIP package, split it, and encrypt each upload part.
Parameters
invoices(Iterable[bytes | str | Path | BatchInvoice]) — Invoices to include. Each item is invoice XML asbytesorstr(namedinvoice-<position>.xml), aPathto an XML file (keeps its file name) or aBatchInvoicewith an explicit file name.form_code(FormSchema) — Invoice schema declared for the batch session.offline_mode(bool) — Whether to declare offline invoicing mode for the batch.max_part_size(int) — Maximum size of each ZIP part before encryption.
Returns
PreparedBatch— A prepared batch with encrypted part payloads and the metadata requiredPreparedBatch— to open a batch session.
Raises
FileNotFoundError— If an invoice XML path does not exist.NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If key or part encryption fails.KSeFValidationError— If the invoice list or part size is invalid.
Example
batch = auth.batch.prepare([xml_1, xml_2])
session = auth.batch.submit(batch)BatchService.submit
def submit(
batch: PreparedBatch | Iterable[bytes | str | Path | BatchInvoice],
*,
form_code: FormSchema = FormSchema.FA3,
offline_mode: bool = False,
max_part_size: int = MAX_BATCH_PART_SIZE,
) -> BatchSessionClientOpen a batch session, upload the parts and close the session.
Parameters
batch(PreparedBatch | Iterable[bytes | str | Path | BatchInvoice]) — A prepared batch fromprepare(), or the invoices themselves, which are prepared first (same item types asprepare()).form_code(FormSchema) — Invoice schema declared for the batch session. Ignored for a prepared batch, which carries its own.offline_mode(bool) — Whether to declare offline invoicing mode for the batch. Ignored for a prepared batch.max_part_size(int) — Maximum size of each ZIP part before encryption. Ignored for a prepared batch.
Returns
BatchSessionClient— The closed batch session client. Call itswait()for the terminal status,list_failed_invoices()for rejected invoices anddownload_upo()for the UPO pages.
Raises
NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If key or part encryption fails.KSeFValidationError— If preparation, session opening, or upload validation fails.KSeFBatchUploadError— If external storage rejects an upload or its outcome cannot be determined. Callrecovery_state()on the error to deliberately recover the sensitive batch state.
Example
session = auth.batch.submit([xml_1, xml_2])
final = session.wait()
upos = session.download_upo()BatchService.prepare_batch
def prepare_batch(
*,
invoices: Iterable[BatchInvoice],
form_code: FormSchema = FormSchema.FA3,
offline_mode: bool = False,
max_part_size: int = MAX_BATCH_PART_SIZE,
) -> PreparedBatchDeprecated: build a ZIP package, split it, and encrypt each upload part.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use prepare() instead.
Parameters
invoices(Iterable[BatchInvoice]) — Invoice XML payloads to include in the batch package.form_code(FormSchema) — Invoice schema declared for the batch session.offline_mode(bool) — Whether to declare offline invoicing mode for the batch.max_part_size(int) — Maximum size of each ZIP part before encryption.
Returns
PreparedBatch— A prepared batch with encrypted part payloads and the metadata requiredPreparedBatch— to open a batch session.
Raises
NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If key or part encryption fails.KSeFValidationError— If the invoice list or part size is invalid.
BatchService.prepare_batch_from_paths
def prepare_batch_from_paths(
*,
invoice_paths: Iterable[Path | str],
form_code: FormSchema = FormSchema.FA3,
offline_mode: bool = False,
max_part_size: int = MAX_BATCH_PART_SIZE,
) -> PreparedBatchDeprecated: load invoice XML files from disk and prepare a batch package.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use prepare() with Path items instead.
Parameters
invoice_paths(Iterable[Path | str]) — Paths to XML files that should be added to the batch.form_code(FormSchema) — Invoice schema declared for the batch session.offline_mode(bool) — Whether to declare offline invoicing mode for the batch.max_part_size(int) — Maximum size of each ZIP part before encryption.
Returns
PreparedBatch— A prepared batch with encrypted parts ready to be uploaded.
Raises
FileNotFoundError— If an invoice XML path does not exist.NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If key or part encryption fails.KSeFValidationError— If the invoice list or part size is invalid.
BatchService.open_session
def open_session(*, prepared_batch: PreparedBatch) -> BatchSessionClientDeprecated: open a batch session for an already prepared package.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use auth.batch_session(prepared_batch=...) instead.
Parameters
prepared_batch(PreparedBatch) — Prepared batch payload returned byprepare().
Returns
BatchSessionClient— A session client exposing the upload instructions returned by KSeF.
Raises
KSeFValidationError— If the prepared batch cannot be opened.
BatchService.upload_parts
def upload_parts(*, session: BatchSessionClient, prepared_batch: PreparedBatch) -> NoneUpload all prepared batch parts using the session's presigned URLs.
Parameters
session(BatchSessionClient) — Open batch session that already contains upload instructions.prepared_batch(PreparedBatch) — Prepared batch whose part ordinals match the session.
Raises
KSeFClientClosedError— If the session client is closed.KSeFValidationError— If prepared part ordinals do not match session upload instructions.KSeFBatchUploadError— If external storage rejects an upload or its outcome cannot be determined. Callrecovery_state()on the error to deliberately recover the sensitive batch state.
BatchService.submit_prepared_batch
def submit_prepared_batch(*, prepared_batch: PreparedBatch) -> BatchSessionResumeStateDeprecated: open, upload, and close a batch session for a prepared package.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use submit() instead.
Parameters
prepared_batch(PreparedBatch) — Prepared batch payload returned byprepare().
Returns
BatchSessionResumeState— Serializable state of the submitted batch session.
Raises
KSeFClientClosedError— If the session client closes before upload.KSeFValidationError— If the prepared batch cannot be opened or uploaded.KSeFBatchUploadError— If external storage rejects an upload or its outcome cannot be determined. Callrecovery_state()on the error to deliberately recover the sensitive batch state.
BatchService.submit_batch
def submit_batch(
*,
invoices: Iterable[BatchInvoice],
form_code: FormSchema = FormSchema.FA3,
offline_mode: bool = False,
max_part_size: int = MAX_BATCH_PART_SIZE,
) -> BatchSessionResumeStateDeprecated: prepare and submit a batch in one call.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use submit() instead.
Parameters
invoices(Iterable[BatchInvoice]) — Invoice XML payloads to include in the batch package.form_code(FormSchema) — Invoice schema declared for the batch session.offline_mode(bool) — Whether to declare offline invoicing mode for the batch.max_part_size(int) — Maximum size of each ZIP part before encryption.
Returns
BatchSessionResumeState— Serializable state of the submitted batch session.
Raises
NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If key or part encryption fails.KSeFValidationError— If preparation, session opening, or upload validation fails.KSeFBatchUploadError— If external storage rejects an upload or its outcome cannot be determined. Callrecovery_state()on the error to deliberately recover the sensitive batch state.
BatchService.get_status
def get_status(
*,
session: str | BatchSessionResumeState | BatchSessionClient,
) -> SessionStatusResponseDeprecated: fetch the current status of a batch session.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use BatchSessionClient.get_status() instead.
Parameters
session(str | BatchSessionResumeState | BatchSessionClient) — Session reference number, persisted state, or open session client.
Returns
SessionStatusResponse— Current batch session status as reported by KSeF.
BatchService.list_invoices
def list_invoices(
*,
session: str | BatchSessionResumeState | BatchSessionClient,
page_size: int = 10,
continuation_token: str | None = None,
) -> SessionInvoicesResponseDeprecated: fetch one page of accepted invoices from a batch session.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use BatchSessionClient.list_invoices() instead.
Parameters
session(str | BatchSessionResumeState | BatchSessionClient) — Session reference number, persisted state, or open session client.page_size(int) — Number of invoices per page (10–1000).continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.
Returns
SessionInvoicesResponse— One page of invoices accepted in the session, with a continuation token when more exist.
BatchService.list_failed_invoices
def list_failed_invoices(
*,
session: str | BatchSessionResumeState | BatchSessionClient,
page_size: int = 10,
continuation_token: str | None = None,
) -> SessionInvoicesResponseDeprecated: fetch one page of failed invoices from a batch session.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use BatchSessionClient.list_failed_invoices() instead.
Parameters
session(str | BatchSessionResumeState | BatchSessionClient) — Session reference number, persisted state, or open session client.page_size(int) — Number of invoices per page (10–1000).continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.
Returns
SessionInvoicesResponse— One page of invoices that failed processing, with a continuation token when more exist.
BatchService.get_upo
def get_upo(
*,
session: str | BatchSessionResumeState | BatchSessionClient,
upo_reference_number: str,
) -> bytesDeprecated: download the collective UPO for a batch session.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use BatchSessionClient.download_upo() instead.
Parameters
session(str | BatchSessionResumeState | BatchSessionClient) — Session reference number, persisted state, or open session client.upo_reference_number(str) — UPO page reference returned in the session status.
Returns
bytes— Raw XML bytes of the requested UPO page.
BatchService.wait_for_completion
def wait_for_completion(
*,
session: str | BatchSessionResumeState | BatchSessionClient,
timeout: float = 120.0,
poll_interval: float = 2.0,
) -> SessionStatusResponseDeprecated: poll a batch session until KSeF reports a terminal status.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use BatchSessionClient.wait() instead.
Parameters
session(str | BatchSessionResumeState | BatchSessionClient) — Session reference number, persisted state, or open session client.timeout(float) — Maximum number of seconds to wait for completion.poll_interval(float) — Delay between status checks.
Returns
SessionStatusResponse— Final successful batch session status.
Raises
KSeFSessionError— If batch processing reaches a failed terminal status.KSeFBatchSessionTimeoutError— If polling exceedstimeout.
BatchSessionClient
Import: from ksef2.clients import BatchSessionClient
class BatchSessionClientBatchSessionClient(
transport: Middleware,
state: BatchSessionResumeState,
*,
upload_transport: Middleware | None = None,
prepared_batch: PreparedBatch | None = None,
access_token: str | None = None,
resumed: bool = False,
)Client for managing an active batch session.
Catch KSeFException for SDK-classified failures raised by this session
branch, and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.KSeFClientClosedError— If an operation is attempted after closing the session.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
BatchSessionClient.reference_number (property)
reference_number: strGet the batch session reference number.
Returns
str— The KSeF reference number of the session.
BatchSessionClient.access_token (property)
access_token: strDeprecated compatibility accessor for the current bearer token.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use AuthenticatedClient.access_token instead.
Returns
str— The bearer access token the session was opened with.
Raises
KSeFValidationError— If the session state carries no bearer token.
BatchSessionClient.aes_key (property)
aes_key: bytesGet the AES key for encrypting batch files.
Returns
bytes— The raw AES key.
BatchSessionClient.iv (property)
iv: bytesGet the initialization vector for AES encryption.
Returns
bytes— The raw initialization vector.
BatchSessionClient.part_upload_requests (property)
part_upload_requests: list[PartUploadRequest]Get the upload instructions for each file part.
Returns
list[PartUploadRequest]— One upload request, with presigned URL and headers, per part.
BatchSessionClient.resume_state
def resume_state() -> BatchSessionResumeStateReturn the sensitive session state needed to resume later.
Returns
BatchSessionResumeState— The sensitive session state needed to resume later.
BatchSessionClient.get_state
def get_state() -> BatchSessionResumeStateDeprecated compatibility wrapper for resume_state().
Deprecated
May be removed no earlier than ksef2 2.0.0. Use resume_state() instead.
Returns
BatchSessionResumeState— The same state asresume_state().
BatchSessionClient.get_status
def get_status() -> SessionStatusResponseFetch the current processing state of the batch session.
Returns
SessionStatusResponse— The session status, including invoice counters.
BatchSessionClient.list_invoices
def list_invoices(
*,
page_size: int = 10,
continuation_token: str | None = None,
) -> SessionInvoicesResponseFetch one page of invoices submitted in this batch session.
Parameters
page_size(int) — Number of invoices per page (10–1000).continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.
Returns
SessionInvoicesResponse— One page of invoices submitted in the session, with a continuation token when more exist.
BatchSessionClient.list_failed_invoices
def list_failed_invoices(
*,
page_size: int = 10,
continuation_token: str | None = None,
) -> SessionInvoicesResponseFetch one page of failed invoices from this batch session.
Parameters
page_size(int) — Number of invoices per page (10–1000).continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.
Returns
SessionInvoicesResponse— One page of invoices that failed processing, with a continuation token when more exist.
BatchSessionClient.get_upo
def get_upo(*, upo_reference_number: str) -> bytesDeprecated: download one page of the collective UPO for the batch session.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use download_upo() instead.
Parameters
upo_reference_number(str) — Reference number of the UPO, taken from the session status.
Returns
bytes— The UPO as XML bytes.
BatchSessionClient.wait
def wait(*, timeout: float = 120.0, poll_interval: float = 2.0) -> SessionStatusResponsePoll until KSeF reports a terminal status for the closed batch session.
KSeF processes the batch after the session is closed, so call this after
auth.batch.submit() or after leaving the with block of a batch session.
Parameters
timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between session status checks.
Returns
SessionStatusResponse— The final successful session status, including the session UPO references.
Raises
KSeFSessionError— If the session is still open, or if batch processing reaches a failed terminal status.KSeFBatchSessionTimeoutError— If polling exceedstimeout.
BatchSessionClient.download_upo
def download_upo() -> list[bytes]Download every page of the collective UPO in one pass.
Reads the session status once, resolves the UPO page references from it
and downloads each page. It never waits or polls: call wait() first.
Returns
list[bytes]— The XML bytes of each UPO page, in order; empty if KSeF issued no UPO because no invoice was accepted.
Raises
KSeFSessionError— If the session is still open.KSeFNotReadyError— If KSeF has not finished processing the closed batch. Callwait()on the session, then ask again.
BatchSessionClient.upload_parts
def upload_parts() -> NoneUpload the prepared batch parts using the session's presigned URLs.
Raises
KSeFClientClosedError— If the upload window has already been closed.KSeFValidationError— If the session has no prepared batch payload attached.KSeFBatchUploadError— If external storage rejects an upload or its outcome cannot be determined. Callrecovery_state()on the error to deliberately recover the sensitive batch state.
BatchSessionClient.close
def close() -> NoneClose the batch session and start processing.
This triggers processing of the invoice batch and generation of UPO for valid invoices and a collective UPO for the session. Closing an already-closed session is a no-op; a client rebuilt from saved state first asks KSeF whether the session was already closed.
CertificateEnrollment
Import: from ksef2.clients import CertificateEnrollment
class CertificateEnrollment(OperationHandle[CertificateEnrollmentStatusResponse, CertificateEnrollmentStatusResponse])CertificateEnrollment(
client: CertificatesClient,
response: CertificateEnrollmentResponse,
)Handle to a certificate enrollment that KSeF issues asynchronously.
Returned by auth.certificates.enroll(). It exposes every field of the
enrollment response, for example reference_number and timestamp, and
wait() polls until KSeF has issued the certificate.
get_enrollment_status() on the certificates client reads the same status
for a reference number you stored earlier.
Raises
KSeFApiError— If KSeF returns an API error response.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
CertificateEnrollment.timestamp (property)
timestamp: datetimeGet when KSeF accepted the enrollment request.
Returns
datetime— The acceptance time reported by KSeF.
CertificateEnrollment.response (property)
response: CertificateEnrollmentResponseGet the plain enrollment response.
Returns
CertificateEnrollmentResponse— The data model KSeF returned when it accepted the enrollment.
CertificateEnrollment.get_status
def get_status() -> CertificateEnrollmentStatusResponseFetch the enrollment's current status without waiting.
Returns
CertificateEnrollmentStatusResponse— The enrollment status, including the certificate serial number once issued.
CertificateEnrollment.wait
def wait(
*,
timeout: float = 60.0,
poll_interval: float = 2.0,
) -> CertificateEnrollmentStatusResponsePoll until KSeF has issued the certificate.
Parameters
timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between status checks.
Returns
CertificateEnrollmentStatusResponse— The final status, with the issued certificate's serial number.
Raises
KSeFCertificateEnrollmentFailedError— If KSeF rejects, cancels or fails the enrollment.KSeFCertificateEnrollmentTimeoutError— If polling exceedstimeout.
CertificatesClient
Import: from ksef2.clients import CertificatesClient
class CertificatesClientCertificatesClient(transport: Middleware)High-level API for certificate enrollment, retrieval, and search.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
CertificatesClient.get_limits
def get_limits() -> CertificateLimitsResponseReturn the effective certificate enrollment and issuance quotas.
Returns
CertificateLimitsResponse— The effective certificate enrollment and issuance quotas.
CertificatesClient.get_enrollment_data
def get_enrollment_data() -> CertificateEnrollmentDataReturn subject data needed to prepare a CSR for enrollment.
Returns
CertificateEnrollmentData— Subject data needed to prepare a CSR for enrollment.
CertificatesClient.enroll
def enroll(
*,
certificate_name: str,
certificate_type: CertificateTypeValue,
csr: str,
valid_from: datetime | str | None = None,
) -> CertificateEnrollmentRequest issuance of a certificate from a CSR.
Parameters
certificate_name(str) — Name to give the certificate.certificate_type(CertificateTypeValue) — Certificate type to request,authenticationoroffline.csr(str) — PKCS#10 certificate signing request, DER-encoded and Base64-encoded.valid_from(datetime | str | None) — Requested start of validity as a datetime or ISO 8601 string;Nonefor immediately.
Returns
CertificateEnrollment— A handle to the enrollment; callwait()to wait until KSeF has issued the certificate.
Example
enrollment = auth.certificates.enroll(
certificate_name="signing", certificate_type="offline", csr=csr
)
status = enrollment.wait()
print(status.certificate_serial_number)CertificatesClient.get_enrollment_status
def get_enrollment_status(
*,
reference_number: str,
) -> CertificateEnrollmentStatusResponseFetch the current status of a certificate enrollment request.
Parameters
reference_number(str) — Reference number returned byenroll().
Returns
CertificateEnrollmentStatusResponse— The enrollment status, including the certificate serial number once issued.
CertificatesClient.retrieve
def retrieve(
*,
certificate_serial_numbers: builtins.list[CertificateSerialNumber],
) -> RetrievedCertificatesListDownload issued certificates by serial number.
Parameters
certificate_serial_numbers(builtins.list[CertificateSerialNumber]) — Serial numbers of the certificates to download.
Returns
RetrievedCertificatesList— The requested certificates with their DER data.
CertificatesClient.revoke
def revoke(
*,
certificate_serial_number: CertificateSerialNumber,
reason: RevocationReason | None = None,
) -> NoneRevoke a certificate, optionally providing a revocation reason.
Parameters
certificate_serial_number(CertificateSerialNumber) — Serial number of the certificate to revoke.reason(RevocationReason | None) — Reason for the revocation;Noneto omit it.
CertificatesClient.query
def query(
*,
name: str | None = None,
certificate_serial_number: CertificateSerialNumber | None = None,
certificate_type: CertificateTypeValue | None = None,
status: CertificateStatusValue | None = None,
expires_after: datetime | str | None = None,
params: OffsetPaginationParams | None = None,
) -> CertificatesInfoListDeprecated: fetch one page of certificate search results.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead; first_page() fetches one page.
Parameters
name(str | None) — Match this certificate name.certificate_serial_number(CertificateSerialNumber | None) — Match this certificate serial number.certificate_type(CertificateTypeValue | None) — Match this certificate type.status(CertificateStatusValue | None) — Match this lifecycle status.expires_after(datetime | str | None) — Match certificates that expire after this datetime or ISO 8601 string.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
CertificatesInfoList— One page of certificate metadata.
CertificatesClient.all
def all(
*,
certificate_serial_number: CertificateSerialNumber | None = None,
name: str | None = None,
certificate_type: CertificateTypeValue | None = None,
status: CertificateStatusValue | None = None,
expires_after: datetime | str | None = None,
params: OffsetPaginationParams | None = None,
) -> Iterator[CertificateInfo]Deprecated: iterate over all certificates matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead.
Parameters
certificate_serial_number(CertificateSerialNumber | None) — Match this certificate serial number.name(str | None) — Match this certificate name.certificate_type(CertificateTypeValue | None) — Match this certificate type.status(CertificateStatusValue | None) — Match this lifecycle status.expires_after(datetime | str | None) — Match certificates that expire after this datetime or ISO 8601 string.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Yields
CertificateInfo— Each matching certificate, across all pages.
CertificatesClient.list
def list(
*,
name: str | None = None,
certificate_serial_number: CertificateSerialNumber | None = None,
certificate_type: CertificateTypeValue | None = None,
status: CertificateStatusValue | None = None,
expires_after: datetime | str | None = None,
params: OffsetPaginationParams | None = None,
) -> Pager[CertificateInfo]List the certificates of the authenticated context.
Nothing is requested until the result is consumed. Iterate it for every
matching certificate, call pages() for page-sized lists or
first_page() for one request only.
Parameters
name(str | None) — Match this certificate name.certificate_serial_number(CertificateSerialNumber | None) — Match this certificate serial number.certificate_type(CertificateTypeValue | None) — Match this certificate type.status(CertificateStatusValue | None) — Match this lifecycle status.expires_after(datetime | str | None) — Match certificates that expire after this datetime or ISO 8601 string.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
Pager[CertificateInfo]— A paging object over the matching certificates.
Example
for certificate in auth.certificates.list(status="active"):
print(certificate.certificate_serial_number)Client
Import: from ksef2.clients import Client
class ClientClient(
environment: Environment = Environment.PRODUCTION,
*,
transport_config: TransportConfig | None = None,
http_client: httpx.Client | None = None,
certificate_store: stores.CertificateStoreProtocol | None = None,
)Root KSeF SDK client responsible for transport and lifecycle management.
Branch properties only create child clients. Branch operations document their own API, validation, and transport failures.
Raises
KSeFClientClosedError— If a branch is accessed after the client is closed.KSeFUnsupportedEnvironmentError— If a TEST-only branch is accessed outsideEnvironment.TEST.
Example
from ksef2 import Client, Environment
with Client(Environment.TEST) as client:
auth = client.authentication.with_test_certificate(nip="5261040828")
for invoice in auth.invoices.all_metadata(filters=filters):
print(invoice.ksef_number)Methods
Client.authentication (property)
authentication: AuthClientReturn the authentication entry point.
Returns
AuthClient— The authentication branch, used to log in and obtain an authenticated client.
Raises
KSeFClientClosedError— If the root client has been closed.
Client.encryption (property)
encryption: EncryptionClientReturn the public encryption-certificate client.
Returns
EncryptionClient— The client for downloading KSeF public-key certificates.
Raises
KSeFClientClosedError— If the root client has been closed.
Client.testdata (property)
testdata: TestDataClientReturn the TEST-only data seeding client.
Returns
TestDataClient— The client for creating and removing TEST-environment data.
Raises
KSeFClientClosedError— If the root client has been closed.KSeFUnsupportedEnvironmentError— If the client environment is not TEST.
Client.peppol (property)
peppol: PeppolClientReturn the public Peppol provider client.
Returns
PeppolClient— The client for listing registered Peppol providers.
Raises
KSeFClientClosedError— If the root client has been closed.
Client.raw (property)
raw: RawClientReturn raw unauthenticated endpoints for advanced integrations.
Returns
RawClient— Raw unauthenticated endpoints for advanced integrations.
Client.authenticated
def authenticated(auth_tokens: AuthTokens) -> AuthenticatedClientDeprecated compatibility wrapper for authentication.resume().
Deprecated
May be removed no earlier than ksef2 2.0.0. Use authentication.resume() with AuthenticationResumeState.from_tokens() instead.
Parameters
auth_tokens(AuthTokens) — Access and refresh tokens from a previous authentication.
Returns
AuthenticatedClient— An authenticated client bound to the tokens.
Client.close
def close() -> NoneClose owned resources and invalidate cached child clients.
CollectiveIdentifiersClient
Import: from ksef2.clients import CollectiveIdentifiersClient
class CollectiveIdentifiersClientCollectiveIdentifiersClient(transport: Middleware)API for generating and querying collective invoice identifiers.
Methods
CollectiveIdentifiersClient.generate
def generate(
*,
invoices: builtins.list[CollectiveIdentifierInvoice],
) -> GenerateCollectiveIdentifierResponseGenerate a collective identifier for the supplied invoices.
Parameters
invoices(builtins.list[CollectiveIdentifierInvoice]) — Invoices to group, with optional payment details.
Returns
GenerateCollectiveIdentifierResponse— The generated collective identifier number.
CollectiveIdentifiersClient.query
def query(
*,
filters: CollectiveIdentifiersQuery,
continuation_token: str | None = None,
params: CollectiveIdentifierParams | None = None,
) -> CollectiveIdentifiersPageDeprecated: fetch one page of collective identifiers visible in the context.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead; first_page() fetches one page.
Parameters
filters(CollectiveIdentifiersQuery) — Criteria selecting collective identifiers.continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Returns
CollectiveIdentifiersPage— One page of matching collective identifiers.
CollectiveIdentifiersClient.query_all
def query_all(
*,
filters: CollectiveIdentifiersQuery,
params: CollectiveIdentifierParams | None = None,
) -> Iterator[CollectiveIdentifiersPage]Deprecated: iterate through every page matching a collective identifier query.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list().pages() instead.
Parameters
filters(CollectiveIdentifiersQuery) — Criteria selecting collective identifiers.params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Yields
CollectiveIdentifiersPage— Each page of matching collective identifiers, following continuation tokens.
CollectiveIdentifiersClient.query_by_ksef_number
def query_by_ksef_number(
*,
ksef_number: str,
continuation_token: str | None = None,
params: CollectiveIdentifierParams | None = None,
) -> CollectiveIdentifierReferencesPageDeprecated: fetch one page of identifiers associated with a KSeF invoice.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_for_invoice() instead; first_page() fetches one page.
Parameters
ksef_number(str) — KSeF number of the invoice.continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Returns
CollectiveIdentifierReferencesPage— One page of collective identifiers that reference the invoice.
CollectiveIdentifiersClient.query_all_by_ksef_number
def query_all_by_ksef_number(
*,
ksef_number: str,
params: CollectiveIdentifierParams | None = None,
) -> Iterator[CollectiveIdentifierReferencesPage]Deprecated: iterate through identifiers associated with one KSeF invoice.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_for_invoice().pages() instead.
Parameters
ksef_number(str) — KSeF number of the invoice.params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Yields
CollectiveIdentifierReferencesPage— Each page of identifiers that reference the invoice, following continuation tokens.
CollectiveIdentifiersClient.list_all_invoices
def list_all_invoices(
*,
collective_identifier_numbers: builtins.list[str],
params: CollectiveIdentifierParams | None = None,
) -> Iterator[CollectiveIdentifierInvoicesPage]Deprecated: iterate through every invoice page for the supplied collective identifiers.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_invoices().pages() instead.
Parameters
collective_identifier_numbers(builtins.list[str]) — Collective identifier numbers to expand (1–10).params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Yields
CollectiveIdentifierInvoicesPage— Each page of invoices, following continuation tokens.
CollectiveIdentifiersClient.list_for_invoice
def list_for_invoice(
ksef_number: str,
*,
params: CollectiveIdentifierParams | None = None,
) -> Pager[CollectiveIdentifierReference]List the collective identifiers that reference one KSeF invoice.
Nothing is requested until the result is consumed.
Parameters
ksef_number(str) — KSeF number of the invoice.params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Returns
Pager[CollectiveIdentifierReference]— A paging object over the collective identifiers referencing the invoice.
Example
for reference in auth.collective_identifiers.list_for_invoice(ksef_number):
print(reference.collective_identifier_number)CollectiveIdentifiersClient.list_invoices
def list_invoices(
collective_identifier_numbers: builtins.list[str],
*,
params: CollectiveIdentifierParams | None = None,
) -> Pager[CollectiveIdentifierInvoiceDetails]List the invoices inside the supplied collective identifiers.
Nothing is requested until the result is consumed. Unlike the former
list_invoices(), which fetched one page, this returns a paging object.
Parameters
collective_identifier_numbers(builtins.list[str]) — Collective identifier numbers to expand (1–10).params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Returns
Pager[CollectiveIdentifierInvoiceDetails]— A paging object over the invoices belonging to the identifiers.
Example
for invoice in auth.collective_identifiers.list_invoices([number]):
print(invoice.ksef_number)CollectiveIdentifiersClient.list
def list(
filters: CollectiveIdentifiersQuery,
*,
params: CollectiveIdentifierParams | None = None,
) -> Pager[CollectiveIdentifierSummary]List the collective identifiers visible in the context.
Nothing is requested until the result is consumed. Iterate it for every
identifier, call pages() for page-sized lists or first_page() for
one request only.
Parameters
filters(CollectiveIdentifiersQuery) — Criteria selecting collective identifiers.params(CollectiveIdentifierParams | None) — Page size; defaults are used whenNone.
Returns
Pager[CollectiveIdentifierSummary]— A paging object over the matching collective identifiers.
Example
for identifier in auth.collective_identifiers.list(filters):
print(identifier.collective_identifier_number)EncryptionClient
Import: from ksef2.clients import EncryptionClient
class EncryptionClientEncryptionClient(transport: Middleware)Access to public encryption certificates published by KSeF.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
EncryptionClient.get_certificates
def get_certificates(
*,
usage: list[CertUsage] | None = None,
) -> list[PublicKeyCertificate]Return public certificates, optionally filtered by supported usage.
Parameters
usage(list[CertUsage] | None) — Return only certificates valid for these usages;Nonefor all.
Returns
list[PublicKeyCertificate]— The public-key certificates published by KSeF.
ExportedInvoices
Import: from ksef2.clients import ExportedInvoices
class ExportedInvoicesExportedInvoices(parts: list[bytes], *, package: InvoicePackage | None = None)Decrypted result of an invoice export.
The decrypted package parts are joined into one ZIP archive, which holds one
<ksef_number>.xml file per invoice and a _metadata.json file. The ZIP is
opened lazily; construct this object through ExportJob.wait(). An export that
matched no invoices has an empty archive.
Methods
ExportedInvoices.archive (property)
archive: bytesGet the raw ZIP archive.
Returns
bytes— The decrypted and joined package parts, exactly as KSeF built the archive.
ExportedInvoices.package (property)
package: InvoicePackage | NoneGet the package metadata reported by the export status.
Returns
InvoicePackage | None— Invoice count, size, truncation flag and the dates for continuing a truncated export;Noneif unknown.
ExportedInvoices.metadata (property)
metadata: list[InvoiceMetadata] | NoneGet the invoice metadata stored in the package.
Returns
list[InvoiceMetadata] | None— The parsedinvoiceslist of_metadata.json, orNoneif the package has no such file.
Raises
KSeFValidationError— If_metadata.jsonis not valid metadata.zipfile.BadZipFile— If the archive is not a valid ZIP file.
ExportedInvoices.invoices
def invoices() -> Iterator[tuple[str, bytes]]Iterate over the invoices in the package.
Yields
tuple[str, bytes]— A(ksef_number, xml)pair for each invoice file, in archive order.
Raises
zipfile.BadZipFile— If the archive is not a valid ZIP file.
ExportedInvoices.save
def save(directory: Path | str) -> list[Path]Extract the package into a directory.
Every entry path is validated first, and nothing is written if one is
unsafe: absolute paths, .. segments, backslashes, drive letters and NUL
bytes are refused.
Parameters
directory(Path | str) — Directory to extract into; created if missing.
Returns
list[Path]— The paths of the written files.
Raises
ValueError— If an archive entry path would escapedirectory.zipfile.BadZipFile— If the archive is not a valid ZIP file.OSError— If a file or directory cannot be written.
ExportJob
Import: from ksef2.clients import ExportJob
class ExportJob(OperationHandle[InvoiceExportStatusResponse, ExportedInvoices])ExportJob(
state: ExportResumeState,
*,
get_status: Callable[[], InvoiceExportStatusResponse],
download_parts: Callable[[InvoicePackage], list[bytes]],
)Handle to a scheduled invoice export.
Returned by auth.invoices.export(). wait() polls until KSeF has built
the package, then downloads, decrypts and joins its parts into an
ExportedInvoices result. The handle holds the keys needed to decrypt the
package, so keep it in memory only.
Raises
KSeFApiError— If KSeF returns an API error response.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
ExportJob.resume_state
def resume_state() -> ExportResumeStateReturn the sensitive state needed to resume the export later.
Persist it with to_json() before waiting, and pass it to
auth.invoices.export(state=...) after a restart to get the job back.
It holds the key that decrypts the package, so store it as a credential.
Returns
ExportResumeState— The export's reference number and AES key material.
ExportJob.get_status
def get_status() -> InvoiceExportStatusResponseFetch the export's current status without waiting.
Returns
InvoiceExportStatusResponse— The export status, with package metadata once the export is ready.
ExportJob.wait
def wait(*, timeout: float = 120.0, poll_interval: float = 2.0) -> ExportedInvoicesPoll until the export is ready, then download and decrypt the package.
Parameters
timeout(float) — Maximum number of seconds to wait for the export to become ready.poll_interval(float) — Delay in seconds between export status checks.
Returns
ExportedInvoices— The decrypted package: iterateinvoices(), readmetadataorsave()it to disk.
Raises
KSeFExportFailedError— If KSeF reports that the export failed, was cancelled or expired.KSeFExportTimeoutError— If polling exceedstimeout.KSeFEncryptionError— If a downloaded package part cannot be decrypted.KSeFExternalTransferError— If external storage rejects a part download or its outcome cannot be determined.
GeneratedToken
Import: from ksef2.clients import GeneratedToken
class GeneratedToken(OperationHandle[TokenStatusResponse, TokenStatusResponse])GeneratedToken(client: TokensClient, response: GenerateTokenResponse)Handle to a token KSeF is still activating.
Returned by auth.tokens.generate(). The one-time token is readable
immediately, so persist it before calling wait(): a polling failure does
not contain or recover that secret. The handle exposes every field of the
generation response, for example token and reference_number, and never
includes the token in its repr.
Raises
KSeFApiError— If KSeF returns an API error response.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
GeneratedToken.token (property)
token: strGet the one-time token value.
Returns
str— The secret KSeF returned once at generation; store it securely.
GeneratedToken.response (property)
response: GenerateTokenResponseGet the plain generation response.
Returns
GenerateTokenResponse— The data model KSeF returned when the token was generated.
GeneratedToken.to_sensitive_dict
def to_sensitive_dict() -> dict[str, str]Export the one-time token for deliberately protected persistence.
Returns
dict[str, str]— A dictionary with the reference number and the plain token.
GeneratedToken.get_status
def get_status() -> TokenStatusResponseFetch the token's current status without waiting.
Returns
TokenStatusResponse— The token's current lifecycle status.
GeneratedToken.wait
def wait(*, timeout: float = 60.0, poll_interval: float = 1.0) -> TokenStatusResponsePoll until the token becomes active or reaches a terminal state.
Parameters
timeout(float) — Maximum number of seconds to wait for activation.poll_interval(float) — Delay in seconds between status checks.
Returns
TokenStatusResponse— The first status response that reports the token as active.
Raises
KSeFApiError— If activation ends in a terminal failure state.KSeFTokenStatusTimeoutError— If polling exceedstimeout.
InvoiceSessionsClient
Import: from ksef2.clients import InvoiceSessionsClient
class InvoiceSessionsClientInvoiceSessionsClient(transport: Middleware)Browse historical invoice sessions and download their UPO documents.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
InvoiceSessionsClient.download_upo
def download_upo(
session_reference_number: str,
*,
invoice_reference_number: str | None = None,
ksef_number: str | None = None,
upo_reference_number: str | None = None,
) -> bytesDownload one UPO from stored references without opening a session.
Works for online and batch invoice sessions, including after a process restart. Uses the authenticated client's bearer token and makes one request. It never waits or polls, and needs no session crypto state.
Parameters
session_reference_number(str) — Reference number of the invoice session.invoice_reference_number(str | None) — Invoice reference within that session. Pass exactly one of this,ksef_numberorupo_reference_number.ksef_number(str | None) — KSeF number of an accepted invoice in that session.upo_reference_number(str | None) — Reference number of one session UPO page.
Returns
bytes— The invoice UPO or session UPO page as XML bytes.
Raises
KSeFValidationError— If no selector or multiple selectors are given.KSeFNotReadyError— If KSeF has not issued the requested UPO yet. Check processing status before retrying. Rejected invoices may never receive a UPO.
InvoiceSessionsClient.query
def query(
*,
session_type: str,
continuation_token: str | None = None,
params: ListSessionsQuery | None = None,
statuses: builtins.list[SessionStatus | SessionStatusEnum] | None = None,
) -> ListSessionsResponseDeprecated: fetch one page of invoice session history for the chosen session type.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead; first_page() fetches one page.
Parameters
session_type(str) — Invoice session family to browse, such as"online"or"batch".continuation_token(str | None) — Cursor returned by a previous page.params(ListSessionsQuery | None) — Optional query object with pagination and filter settings.statuses(builtins.list[SessionStatus | SessionStatusEnum] | None) — Optional list of status filters applied on top ofparams.
Returns
ListSessionsResponse— One page of historical invoice sessions.
InvoiceSessionsClient.all
def all(
*,
session_type: str,
params: ListSessionsQuery | None = None,
) -> Iterator[ListSessionsResponse]Deprecated: iterate through all pages of invoice session history.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list().pages() instead.
Parameters
session_type(str) — Invoice session family to browse, such as"online"or"batch".params(ListSessionsQuery | None) — Optional query object with pagination and filter settings.
Yields
ListSessionsResponse— Successive pages of historical invoice sessions until KSeF stopsListSessionsResponse— returning a continuation token.
InvoiceSessionsClient.list
def list(
session_type: str,
*,
params: ListSessionsQuery | None = None,
statuses: builtins.list[SessionStatus | SessionStatusEnum] | None = None,
) -> Pager[SessionSummary]List the invoice sessions of the chosen type, newest history first as KSeF returns it.
Nothing is requested until the result is consumed. Iterate it for every
session, call pages() for page-sized lists or first_page() for one
request only.
Parameters
session_type(str) — Invoice session family to browse, such as"online"or"batch".params(ListSessionsQuery | None) — Optional query object with page size and filter settings.statuses(builtins.list[SessionStatus | SessionStatusEnum] | None) — Optional list of status filters applied on top ofparams.
Returns
Pager[SessionSummary]— A paging object over the matching invoice sessions.
Example
for session in auth.invoice_sessions.list("online"):
print(session.reference_number, session.status)InvoicesService
Import: from ksef2.clients import InvoicesService
class InvoicesServiceInvoicesService(
transport: Middleware,
download_transport: Middleware,
certificate_store: CertificateStoreProtocol,
*,
client: InvoicesClient | None = None,
ensure_encryption_certificates_loaded: Callable[[], None] | None = None,
)Invoice workflows with encryption, polling, and export helpers.
Catch KSeFException for SDK-classified failures raised by this service,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
InvoicesService.search
def search(
filters: InvoicesFilter,
params: InvoiceMetadataParams | None = None,
) -> Pager[InvoiceMetadata]Search invoice metadata, following KSeF page and truncation mechanics.
Nothing is requested until the result is consumed. Iterate it for every
matching invoice, call pages() for page-sized lists, first_page()
for one request only, or wait() to poll until KSeF has indexed at
least one matching invoice.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices.params(InvoiceMetadataParams | None) — Page size and sort order; defaults are used whenNone.
Returns
Pager[InvoiceMetadata]— A paging object over the metadata of matching invoices.
Raises
KSeFMetadataPaginationError— If KSeF returns inconsistent pagination boundaries while paging.
Example
from ksef2.models import InvoicesFilter
filters = InvoicesFilter.for_seller(date_from="2026-01-01T00:00:00+01:00")
for invoice in auth.invoices.search(filters):
print(invoice.ksef_number, invoice.gross_amount)InvoicesService.download
def download(
ksef_number: str,
*,
timeout: float | None = None,
poll_interval: float = 2.0,
) -> bytesDownload one processed invoice by KSeF number.
Parameters
ksef_number(str) — KSeF number of the invoice.timeout(float | None) — Seconds to keep polling while KSeF has not made the invoice available yet;Nonetries once.poll_interval(float) — Delay in seconds between download attempts whentimeoutis set.
Returns
bytes— The invoice XML as bytes.
Raises
KSeFApiError— If KSeF rejects the download, for example because the invoice is not processed yet andtimeoutisNone.KSeFInvoiceDownloadTimeoutError— Iftimeoutis set and polling exceeds it.
Example
xml = auth.invoices.download(ksef_number, timeout=60)InvoicesService.export
def export(
filters: InvoicesFilter | None = None,
*,
state: ExportResumeState | str | None = None,
only_metadata: bool = False,
compression_type: CompressionType | str | None = None,
) -> ExportJobSchedule an encrypted invoice export, or resume one scheduled earlier.
Pass exactly one of filters (schedule a new export) or state
(resume the export described by a saved ExportResumeState).
Parameters
filters(InvoicesFilter | None) — Criteria selecting the invoices to export.state(ExportResumeState | str | None) — State fromExportJob.resume_state(), or its JSON string, to resume an export after a restart. Cannot be combined with the other arguments.only_metadata(bool) — Export only invoice metadata instead of full invoice XML.compression_type(CompressionType | str | None) — Compression applied to the package;Nonefor the server default.
Returns
ExportJob— A handle to the export. Call itswait()to download the decrypted package.
Raises
KSeFArgumentError— If neither or both offiltersandstateare given, orstateis combined with scheduling options.NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If export key encryption fails.KSeFValidationError— Ifstateis not valid export resume state.
Example
job = auth.invoices.export(filters)
saved = job.resume_state().to_json() # persist before waiting
job = auth.invoices.export(state=saved) # after a restart
package = job.wait()
package.save("out/")InvoicesService.query_metadata
def query_metadata(
*,
filters: InvoicesFilter,
params: InvoiceMetadataParams | None = None,
) -> QueryInvoicesMetadataResponseDeprecated: fetch one invoice metadata page matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use search() instead; first_page() fetches one page.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices.params(InvoiceMetadataParams | None) — Page size, page offset and sort order; defaults are used whenNone.
Returns
QueryInvoicesMetadataResponse— One page of invoice metadata.
InvoicesService.query_metadata_pages
def query_metadata_pages(
*,
filters: InvoicesFilter,
params: InvoiceMetadataParams | None = None,
) -> Iterator[QueryInvoicesMetadataResponse]Deprecated: fetch metadata pages, following KSeF page and truncation mechanics.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use search().pages() instead.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices.params(InvoiceMetadataParams | None) — Page size, page offset and sort order; defaults are used whenNone.
Yields
QueryInvoicesMetadataResponse— Each page of invoice metadata in order.
Raises
KSeFMetadataPaginationError— If KSeF returns inconsistent pagination boundaries.
InvoicesService.all_metadata
def all_metadata(
*,
filters: InvoicesFilter,
params: InvoiceMetadataParams | None = None,
) -> Iterator[InvoiceMetadata]Deprecated: iterate over all invoice metadata items matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use search() instead.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices.params(InvoiceMetadataParams | None) — Page size and sort order; defaults are used whenNone.
Yields
InvoiceMetadata— Metadata of each matching invoice, across all pages.
Raises
KSeFMetadataPaginationError— If KSeF returns inconsistent pagination boundaries.
InvoicesService.download_invoice
def download_invoice(*, ksef_number: str) -> bytesDeprecated: download one processed invoice by KSeF number.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use download() instead.
Parameters
ksef_number(str) — KSeF number of the invoice.
Returns
bytes— The invoice XML as bytes.
InvoicesService.wait_for_invoice_download
def wait_for_invoice_download(
*,
ksef_number: str,
timeout: float = 120.0,
poll_interval: float = 2.0,
) -> bytesDeprecated: poll until KSeF makes a processed invoice available for download.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use download(ksef_number, timeout=...) instead.
Parameters
ksef_number(str) — KSeF number of the invoice.timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between download attempts.
Returns
bytes— The invoice XML as bytes.
Raises
KSeFInvoiceDownloadTimeoutError— If polling exceedstimeout.
InvoicesService.schedule_export
def schedule_export(
*,
filters: InvoicesFilter,
only_metadata: bool = False,
compression_type: CompressionType | str | None = None,
) -> ExportHandleDeprecated: schedule an encrypted invoice export.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use export() instead.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices to export.only_metadata(bool) — Export only invoice metadata instead of full invoice XML.compression_type(CompressionType | str | None) — Compression applied to the package;Nonefor the server default.
Returns
ExportHandle— A handle holding the export reference number and the keys needed to decrypt the package.
Raises
NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If export key encryption fails.
InvoicesService.get_export_status
def get_export_status(*, reference_number: str) -> InvoiceExportStatusResponseDeprecated: fetch the current status for a scheduled invoice export.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use export() and ExportJob.get_status() instead.
Parameters
reference_number(str) — Reference number of the export, fromExportHandle.reference_number.
Returns
InvoiceExportStatusResponse— The export status, with package metadata once the export is ready.
InvoicesService.fetch_package
def fetch_package(
*,
package: InvoicePackage,
export: ExportHandle,
target_directory: Path | str = '.',
) -> list[Path]Deprecated: download and decrypt all parts of an export package to disk.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use export().wait() and ExportedInvoices.save() instead.
Parameters
package(InvoicePackage) — Package metadata from the export status.export(ExportHandle) — Handle returned when the export was scheduled; supplies the decryption keys.target_directory(Path | str) — Directory to write the decrypted parts to. Defaults to the current directory.
Returns
list[Path]— The paths of the written part files.
Raises
KSeFEncryptionError— If a downloaded package part cannot be decrypted.ValueError— If a package part name is unsafe for local filesystem output.OSError— If the target directory or output file cannot be written.KSeFExternalTransferError— If external storage rejects a part download or its outcome cannot be determined.
InvoicesService.fetch_package_bytes
def fetch_package_bytes(*, package: InvoicePackage, export: ExportHandle) -> list[bytes]Deprecated: download and decrypt all parts of an export package in memory.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use export().wait() and ExportedInvoices.archive instead.
Parameters
package(InvoicePackage) — Package metadata from the export status.export(ExportHandle) — Handle returned when the export was scheduled; supplies the decryption keys.
Returns
list[bytes]— The decrypted package parts, in order.
Raises
KSeFEncryptionError— If a downloaded package part cannot be decrypted.KSeFExternalTransferError— If external storage rejects a part download or its outcome cannot be determined.
InvoicesService.wait_for_invoices
def wait_for_invoices(
*,
filters: InvoicesFilter,
timeout: float = 120.0,
poll_interval: float = 2.0,
) -> QueryInvoicesMetadataResponseDeprecated: poll invoice metadata until at least one invoice matches the filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use search(filters).wait() instead.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices.timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between queries.
Returns
QueryInvoicesMetadataResponse— The first metadata page that contains at least one invoice.
Raises
KSeFInvoiceQueryTimeoutError— If polling exceedstimeout.
InvoicesService.wait_for_export_package
def wait_for_export_package(
*,
reference_number: str,
timeout: float = 120.0,
poll_interval: float = 2.0,
) -> InvoicePackageDeprecated: poll export status until KSeF exposes a downloadable package.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use export().wait() instead.
Parameters
reference_number(str) — Reference number of the export, fromExportHandle.reference_number.timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between export status checks.
Returns
InvoicePackage— The package metadata once the export is ready.
Raises
KSeFExportTimeoutError— If polling exceedstimeout.
InvoicesService.export_and_download
def export_and_download(
*,
filters: InvoicesFilter,
only_metadata: bool = False,
compression_type: CompressionType | str | None = None,
timeout: float = 120.0,
poll_interval: float = 2.0,
) -> list[bytes]Deprecated: schedule an export, wait for it, and download the decrypted package.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use export().wait() instead; ExportedInvoices.archive is the joined ZIP.
Parameters
filters(InvoicesFilter) — Criteria selecting the invoices to export.only_metadata(bool) — Export only invoice metadata instead of full invoice XML.compression_type(CompressionType | str | None) — Compression applied to the package;Nonefor the server default.timeout(float) — Maximum number of seconds to wait for the export to become ready.poll_interval(float) — Delay in seconds between export status checks.
Returns
list[bytes]— The decrypted package parts, in order. Concatenate them to obtain the package archive.
Raises
NoCertificateAvailableError— If no valid symmetric-key certificate is available.KSeFEncryptionError— If export key encryption or package decryption fails.KSeFExportTimeoutError— If polling exceedstimeout.KSeFExternalTransferError— If external storage rejects a part download or its outcome cannot be determined.
InvoiceSubmission
Import: from ksef2.clients import InvoiceSubmission
class InvoiceSubmission(OperationHandle[SessionInvoiceStatusResponse, SessionInvoiceStatusResponse])InvoiceSubmission(session: OnlineSessionClient, response: invoices.SendInvoiceResponse)Handle to one invoice sent into an online session.
Returned by session.send_invoice(). It exposes every field of the
submission response, for example reference_number, and polls the invoice's
processing status with wait(). It keeps working after the session is
closed, so a typical flow sends inside the with block and waits after it.
Raises
KSeFApiError— If KSeF returns an API error response.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
InvoiceSubmission.response (property)
response: invoices.SendInvoiceResponseGet the plain submission response.
Returns
invoices.SendInvoiceResponse— The data model KSeF returned when the invoice was accepted for processing.
InvoiceSubmission.get_status
def get_status() -> SessionInvoiceStatusResponseFetch the invoice's current processing status without waiting.
Returns
SessionInvoiceStatusResponse— The processing status of the invoice.
InvoiceSubmission.wait
def wait(
*,
timeout: float = 60.0,
poll_interval: float = 2.0,
) -> SessionInvoiceStatusResponsePoll until KSeF assigns the invoice a final processing result.
Parameters
timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between invoice status checks.
Returns
SessionInvoiceStatusResponse— The final processing status, including the invoice's KSeF number once accepted.
Raises
KSeFInvoiceRejectedError— If invoice processing reaches a failed terminal status. It subclassesKSeFSessionErrorand keeps the statusdetailsandextensions.KSeFInvoiceProcessingTimeoutError— If polling exceedstimeout.
InvoiceSubmission.download_upo
def download_upo() -> bytesDownload the UPO of this invoice with a single request.
KSeF issues the UPO once it has accepted the invoice. Call wait()
first, then this; it never waits or polls.
Returns
bytes— The UPO as XML bytes.
Raises
KSeFNotReadyError— If KSeF has not issued the UPO yet. Callwait()on this submission, then ask again.
LimitsClient
Import: from ksef2.clients import LimitsClient
class LimitsClientLimitsClient(transport: Middleware)Read and override KSeF context, subject, and API rate limits.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
LimitsClient.get_context_limits
def get_context_limits() -> ContextLimitsReturn the effective limits for online and batch sessions.
Returns
ContextLimits— The effective limits for online and batch sessions.
LimitsClient.get_subject_limits
def get_subject_limits() -> SubjectLimitsReturn the effective limits for certificate enrollments and issuance.
Returns
SubjectLimits— The effective limits for certificate enrollments and issuance.
LimitsClient.get_api_rate_limits
def get_api_rate_limits() -> ApiRateLimitsReturn the effective per-endpoint API rate limits.
Returns
ApiRateLimits— The effective per-endpoint API rate limits.
LimitsClient.set_session_limits
def set_session_limits(*, limits: ContextLimits) -> NoneOverride session limits for the current subject.
Parameters
limits(ContextLimits) — New session limits.
LimitsClient.reset_session_limits
def reset_session_limits() -> NoneReset session limits to their default values.
LimitsClient.set_subject_limits
def set_subject_limits(*, limits: SubjectLimits) -> NoneOverride subject-level certificate and enrollment limits.
Parameters
limits(SubjectLimits) — New subject-level limits.
LimitsClient.reset_subject_limits
def reset_subject_limits() -> NoneReset subject-level limits to their default values.
LimitsClient.set_api_rate_limits
def set_api_rate_limits(*, limits: ApiRateLimits) -> NoneOverride API rate limits for the current subject.
Parameters
limits(ApiRateLimits) — New API rate limits.
LimitsClient.reset_api_rate_limits
def reset_api_rate_limits() -> NoneReset API rate limits to their default values.
LimitsClient.set_production_rate_limits
def set_production_rate_limits() -> NoneCopy production rate-limit defaults into the current environment.
OnlineSessionClient
Import: from ksef2.clients import OnlineSessionClient
class OnlineSessionClientOnlineSessionClient(
transport: Middleware,
state: OnlineSessionResumeState,
*,
resumed: bool = False,
)Client bound to a single online invoice session.
Send invoices with send_invoice(), close the session by leaving the
with block, then call wait() for the terminal session status and
download_upo() for the session UPO.
Catch KSeFException for SDK-classified failures raised by this session
branch, and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.KSeFClientClosedError— If an operation is attempted after closing the session.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
OnlineSessionClient.reference_number (property)
reference_number: strGet the online session reference number.
Returns
str— The KSeF reference number of the session.
OnlineSessionClient.submission
def submission(reference_number: str) -> InvoiceSubmissionGet the handle of an invoice sent earlier in this session.
Use it after a restart or on a resumed session to wait() for the
invoice or download_upo(). No request is made until you call one.
Parameters
reference_number(str) — Invoice reference number, as exposed by the handlesend_invoice()returned.
Returns
InvoiceSubmission— The invoice submission handle.
OnlineSessionClient.send_invoice
def send_invoice(invoice_xml: bytes | str) -> InvoiceSubmissionEncrypt and submit one invoice into the open session.
Parameters
invoice_xml(bytes | str) — Invoice XML, valid against the session's schema. Astris encoded as UTF-8.
Returns
InvoiceSubmission— A handle exposing the submission'sreference_number. Call itswait()for the processing result anddownload_upo()for the invoice UPO.
Raises
KSeFEncryptionError— If invoice encryption fails.
Example
with auth.online_session(form_code=FormSchema.FA3) as session:
submission = session.send_invoice(xml)
result = submission.wait(timeout=60)
print(result.ksef_number)OnlineSessionClient.send_invoice_and_wait
def send_invoice_and_wait(
*,
invoice_xml: bytes,
timeout: float = 60.0,
poll_interval: float = 2.0,
) -> SessionInvoiceStatusResponseDeprecated: submit an invoice and poll until KSeF assigns a final result.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use send_invoice().wait() instead.
Parameters
invoice_xml(bytes) — Invoice XML bytes, valid against the session's schema.timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between invoice status checks.
Returns
SessionInvoiceStatusResponse— The final processing status, including the invoice's KSeF number once accepted.
Raises
KSeFEncryptionError— If invoice encryption fails.KSeFInvoiceRejectedError— If invoice processing reaches a failed terminal status. It subclassesKSeFSessionErrorand keeps the statusdetailsandextensions.KSeFInvoiceProcessingTimeoutError— If polling exceedstimeout.
OnlineSessionClient.get_status
def get_status() -> SessionStatusResponseFetch the current state of the online session.
Returns
SessionStatusResponse— The session status, including invoice counters.
OnlineSessionClient.list_invoices
def list_invoices(
*,
page_size: int = 10,
continuation_token: str | None = None,
) -> SessionInvoicesResponseFetch one page of invoices submitted in this session.
Parameters
page_size(int) — Number of invoices per page (10–1000).continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.
Returns
SessionInvoicesResponse— One page of invoices submitted in the session, with a continuation token when more exist.
OnlineSessionClient.get_invoice_status
def get_invoice_status(*, invoice_reference_number: str) -> SessionInvoiceStatusResponseFetch processing status for one invoice sent in this session.
Parameters
invoice_reference_number(str) — Reference number of the invoice within the session, as exposed by the handlesend_invoice()returned.
Returns
SessionInvoiceStatusResponse— The processing status of the invoice.
OnlineSessionClient.wait_for_invoice_ready
def wait_for_invoice_ready(
*,
invoice_reference_number: str,
timeout: float = 60.0,
poll_interval: float = 2.0,
) -> SessionInvoiceStatusResponseDeprecated: poll invoice status until it succeeds, fails, or times out.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use send_invoice().wait() instead.
Parameters
invoice_reference_number(str) — Reference number of the invoice within the session.timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between invoice status checks.
Returns
SessionInvoiceStatusResponse— The final processing status, including the invoice's KSeF number once accepted.
Raises
KSeFInvoiceRejectedError— If invoice processing reaches a failed terminal status. It subclassesKSeFSessionErrorand keeps the statusdetailsandextensions.KSeFInvoiceProcessingTimeoutError— If polling exceedstimeout.
OnlineSessionClient.list_failed_invoices
def list_failed_invoices(
*,
page_size: int = 10,
continuation_token: str | None = None,
) -> SessionInvoicesResponseFetch one page of invoices that failed within this session.
Parameters
page_size(int) — Number of invoices per page (10–1000).continuation_token(str | None) — Token from the previous page's response;Nonerequests the first page.
Returns
SessionInvoicesResponse— One page of invoices that failed processing, with a continuation token when more exist.
OnlineSessionClient.download_invoice_upo
def download_invoice_upo(
*,
ksef_number: str | None = None,
reference_number: str | None = None,
) -> bytesDownload the UPO of one invoice accepted in this session.
Parameters
ksef_number(str | None) — KSeF number of the invoice. Pass this orreference_number.reference_number(str | None) — Reference number of the invoice within the session, as exposed by the handlesend_invoice()returned. Pass this orksef_number.
Returns
bytes— The UPO as XML bytes.
Raises
KSeFValidationError— If both or neither ofksef_numberandreference_numberare given.
OnlineSessionClient.get_invoice_upo_by_ksef_number
def get_invoice_upo_by_ksef_number(*, ksef_number: str) -> bytesDeprecated: download the invoice UPO by KSeF number.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use download_invoice_upo(ksef_number=...) instead.
Parameters
ksef_number(str) — KSeF number of an invoice accepted in this session.
Returns
bytes— The UPO as XML bytes.
OnlineSessionClient.get_invoice_upo_by_reference
def get_invoice_upo_by_reference(*, invoice_reference_number: str) -> bytesDeprecated: download the invoice UPO by session invoice reference number.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use download_invoice_upo(reference_number=...) instead.
Parameters
invoice_reference_number(str) — Reference number of the invoice within the session.
Returns
bytes— The UPO as XML bytes.
OnlineSessionClient.wait
def wait(*, timeout: float = 120.0, poll_interval: float = 2.0) -> SessionStatusResponsePoll until KSeF reports a terminal status for the closed session.
KSeF processes the session only after it is closed, so call this after
leaving the with block or calling close().
Parameters
timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between session status checks.
Returns
SessionStatusResponse— The final successful session status, including the session UPO references.
Raises
KSeFSessionError— If the session is still open, or if KSeF reports a failed terminal status.KSeFOnlineSessionTimeoutError— If polling exceedstimeout.
OnlineSessionClient.download_upo
def download_upo() -> list[bytes]Download every page of the session UPO in one pass.
Reads the session status once, resolves the UPO page references from it
and downloads each page. It never waits or polls: call wait() first.
Returns
list[bytes]— The XML bytes of each UPO page, in order; empty if KSeF issued no UPO because no invoice was accepted.
Raises
KSeFSessionError— If the session is still open.KSeFNotReadyError— If KSeF has not finished processing the closed session. Callwait()on the session, then ask again.
OnlineSessionClient.close
def close() -> NoneTerminate the online session if it is still open.
Closing an already-closed session is a no-op. A client rebuilt from saved state first asks KSeF whether the session was already closed.
Raises
KSeFApiError— If KSeF rejects the session termination request.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
OnlineSessionClient.resume_state
def resume_state() -> OnlineSessionResumeStateReturn the sensitive session state needed to resume later.
Returns
OnlineSessionResumeState— The sensitive session state needed to resume later.
OnlineSessionClient.get_state
def get_state() -> OnlineSessionResumeStateDeprecated compatibility wrapper for resume_state().
Deprecated
May be removed no earlier than ksef2 2.0.0. Use resume_state() instead.
Returns
OnlineSessionResumeState— The same state asresume_state().
OperationHandle
Import: from ksef2.clients import OperationHandle
class OperationHandle(ABC, Generic[_TStatus, _TResult])OperationHandle(reference_number: str)Client-side handle to an operation that KSeF finishes asynchronously.
A handle keeps a reference to the client that started the operation and the
operation's reference number. It is not a data model: it cannot be
serialized, and the plain response models stay separate. Subclasses say how
to read the operation's status, when it is still pending and how to turn the
finished status into the result returned by wait().
Catch KSeFException for SDK-classified failures raised while waiting, and
httpx.HTTPError for transport failures.
Methods
OperationHandle.reference_number (property)
reference_number: strGet the KSeF reference number of the operation.
Returns
str— The reference number KSeF assigned to the operation.
OperationHandle.get_status
def get_status() -> _TStatusFetch the current status of the operation without waiting.
Returns
_TStatus— The status as KSeF reports it right now.
Pager
Import: from ksef2.clients import Pager
class Pager(Generic[_T])Pager(
pages: Callable[[], Generator[list[_T], None]],
*,
timeout_error: Callable[[float], BaseException] | None = None,
)Lazy view over a paged collection in KSeF.
Iterating the pager yields every item across all pages, requesting pages as
needed. pages() yields one list of items per page, and first_page()
fetches only the first. Nothing is requested until the pager is consumed, and
every iteration starts from the first page again.
Raises
KSeFApiError— If KSeF returns an API error response while a page is fetched.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
Pager.pages
def pages() -> Iterator[list[_T]]Iterate over the collection one page at a time.
Returns
Iterator[list[_T]]— An iterator yielding the items of each page as a list, in order.
Pager.first_page
def first_page() -> list[_T]Fetch only the first page.
Returns
list[_T]— The items of the first page; empty if the collection is empty.
Pager.wait
def wait(*, timeout: float = 120.0, poll_interval: float = 2.0) -> Pager[_T]Poll until the collection contains at least one item.
Use it when KSeF indexes items with a delay, for example invoices that were accepted a moment ago and are not searchable yet.
Parameters
timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between checks.
Returns
Pager[_T]— This pager, now known to be non-empty. Iterating it requests the pages again.
Raises
KSeFInvoiceQueryTimeoutError— For invoice searches, if no invoice appears withintimeout.TimeoutError— For other collections, if no item appears withintimeout.
PeppolClient
Import: from ksef2.clients import PeppolClient
class PeppolClientPeppolClient(transport: Middleware)Service for querying Peppol service providers.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
PeppolClient.query
def query(
*,
params: OffsetPaginationParams | None = None,
) -> ListPeppolProvidersResponseDeprecated: query one page of Peppol service providers.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead; first_page() fetches one page.
Parameters
params(OffsetPaginationParams | None) — Pagination parameters.
Returns
ListPeppolProvidersResponse— One page of providers with pagination info.
PeppolClient.all
def all(*, params: OffsetPaginationParams | None = None) -> Iterator[PeppolProvider]Deprecated: iterate over all Peppol service providers.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead.
Parameters
params(OffsetPaginationParams | None) — Pagination parameters.
Yields
PeppolProvider— Each Peppol service provider, across all pages.
PeppolClient.list
def list(*, params: OffsetPaginationParams | None = None) -> Pager[PeppolProvider]List the registered Peppol service providers.
Nothing is requested until the result is consumed. Iterate it for every
provider, call pages() for page-sized lists or first_page() for one
request only.
Parameters
params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
Pager[PeppolProvider]— A paging object over the Peppol service providers.
Example
for provider in auth.peppol.list():
print(provider.id, provider.name)PermissionOperation
Import: from ksef2.clients import PermissionOperation
class PermissionOperation(OperationHandle[PermissionOperationStatusResponse, PermissionOperationStatusResponse])PermissionOperation(client: PermissionsClient, response: GrantPermissionsResponse)Handle to a permission grant or revoke that KSeF applies asynchronously.
Returned by every grant_*() and revoke*() call of
auth.permissions. It exposes every field of the response, for example
reference_number, and wait() polls the operation until KSeF has
finished it. get_operation_status() on the permissions client reads the
same status for a reference number you stored earlier.
Raises
KSeFApiError— If KSeF returns an API error response.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
PermissionOperation.response (property)
response: GrantPermissionsResponseGet the plain operation response.
Returns
GrantPermissionsResponse— The data model KSeF returned when it accepted the operation.
PermissionOperation.get_status
def get_status() -> PermissionOperationStatusResponseFetch the operation's current status without waiting.
Returns
PermissionOperationStatusResponse— The operation status;status.codeis200once it has completed successfully.
PermissionOperation.wait
def wait(
*,
timeout: float = 60.0,
poll_interval: float = 1.0,
) -> PermissionOperationStatusResponsePoll until KSeF has finished the operation.
Parameters
timeout(float) — Maximum number of seconds to wait before giving up.poll_interval(float) — Delay in seconds between status checks.
Returns
PermissionOperationStatusResponse— The final status, withstatus.code200.
Raises
KSeFPermissionOperationFailedError— If KSeF finishes the operation without applying it.KSeFPermissionOperationTimeoutError— If polling exceedstimeout.
PermissionsClient
Import: from ksef2.clients import PermissionsClient
class PermissionsClientPermissionsClient(transport: Middleware)High-level API for permission grants, revocations, and queries.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
PermissionsClient.grant_person
def grant_person(
*,
subject_type: CertificateSubjectIdentifierType,
subject_value: str,
permissions: list[PersonPermissionScope],
description: str,
first_name: str,
last_name: str,
) -> PermissionOperationGrant person-scoped permissions to a subject identifier.
Parameters
subject_type(CertificateSubjectIdentifierType) — Kind of identifier insubject_value(nip,peselorfingerprint).subject_value(str) — Identifier of the person receiving the permissions.permissions(list[PersonPermissionScope]) — Permission scopes to grant; at least one is required.description(str) — Free-text reason for the grant.first_name(str) — First name of the person receiving the permissions.last_name(str) — Last name of the person receiving the permissions.
Returns
PermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
PermissionsClient.grant_entity
def grant_entity(
*,
subject_value: str,
permissions: list[EntityPermission],
description: str,
entity_name: str,
) -> PermissionOperationGrant entity permissions to a NIP-identified entity.
Parameters
subject_value(str) — NIP of the entity receiving the permissions.permissions(list[EntityPermission]) — Permissions to grant, each with its delegation flag.description(str) — Free-text reason for the grant.entity_name(str) — Full name of the entity receiving the permissions.
Returns
PermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
PermissionsClient.grant_authorization
def grant_authorization(
*,
subject_type: AuthorizationSubjectIdentifierType,
subject_value: str,
permission: AuthorizationPermissionType,
description: str,
entity_name: str,
) -> PermissionOperationGrant an authorization permission such as self-invoicing.
Parameters
subject_type(AuthorizationSubjectIdentifierType) — Kind of identifier insubject_value(niporpeppol_id).subject_value(str) — Identifier of the entity being authorized (NIP or Peppol ID).permission(AuthorizationPermissionType) — Authorization scope to grant, for exampleself_invoicing.description(str) — Free-text reason for the grant.entity_name(str) — Full name of the entity being authorized.
Returns
PermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
PermissionsClient.grant_indirect
def grant_indirect(
*,
subject_type: CertificateSubjectIdentifierType,
subject_value: str,
permissions: list[IndirectPermissionType],
description: str,
first_name: str,
last_name: str,
target_type: IndirectTargetIdentifierType | None = None,
target_value: str | None = None,
) -> PermissionOperationGrant indirect permissions, optionally limited to a target entity.
Parameters
subject_type(CertificateSubjectIdentifierType) — Kind of identifier insubject_value(nip,peselorfingerprint).subject_value(str) — Identifier of the person receiving the indirect permissions.permissions(list[IndirectPermissionType]) — Indirect permission scopes to grant; at least one is required.description(str) — Free-text reason for the grant.first_name(str) — First name of the person receiving the permissions.last_name(str) — Last name of the person receiving the permissions.target_type(IndirectTargetIdentifierType | None) — Kind of identifier intarget_value;Noneorall_partnersscopes the grant to every partner.target_value(str | None) — Identifier of the partner context the grant is limited to;Nonewhen the target is all partners.
Returns
PermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
PermissionsClient.grant_subunit
def grant_subunit(
*,
subject_type: CertificateSubjectIdentifierType,
subject_value: str,
context_type: SubunitIdentifierType,
context_value: str,
description: str,
first_name: str,
last_name: str,
subunit_name: str | None = None,
) -> PermissionOperationGrant permissions within a subunit context.
Parameters
subject_type(CertificateSubjectIdentifierType) — Kind of identifier insubject_value(nip,peselorfingerprint).subject_value(str) — Identifier of the person receiving the permissions.context_type(SubunitIdentifierType) — Kind of identifier incontext_value(niporinternal_id).context_value(str) — Identifier of the subunit context the permissions apply to.description(str) — Free-text reason for the grant.first_name(str) — First name of the person receiving the permissions.last_name(str) — Last name of the person receiving the permissions.subunit_name(str | None) — Display name of the subunit; optional.
Returns
PermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
PermissionsClient.grant_eu_entity
def grant_eu_entity(
*,
subject_value: str,
permissions: list[EuEntityPermissionType],
description: str,
) -> PermissionOperationGrant permissions to an EU entity identified by fingerprint data.
Parameters
subject_value(str) — Fingerprint of the certificate of the person receiving the permissions.permissions(list[EuEntityPermissionType]) — EU-entity permission scopes to grant.description(str) — Free-text reason for the grant.
Returns
PermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
PermissionsClient.grant_eu_entity_administration
def grant_eu_entity_administration(
*,
subject_value: str,
context_type: EuEntityAdminContextIdentifierType,
context_value: str,
description: str,
eu_entity_name: str,
) -> PermissionOperationGrant administration rights for an EU entity in a VAT UE context.
Parameters
subject_value(str) — Fingerprint of the certificate of the person receiving administration rights.context_type(EuEntityAdminContextIdentifierType) — Kind of identifier incontext_value; alwaysnip_vat_ue.context_value(str) — NIP-VAT UE identifier of the EU entity.description(str) — Free-text reason for the grant.eu_entity_name(str) — Full name of the EU entity.
Returns
PermissionOperation— A handle to the asynchronous grant operation; callwait()to wait until KSeF has applied it.
PermissionsClient.revoke_authorization
def revoke_authorization(*, permission_id: str) -> PermissionOperationRevoke an authorization permission by permission id.
Parameters
permission_id(str) — Identifier of the authorization permission, from a query result.
Returns
PermissionOperation— A handle to the asynchronous revoke operation; callwait()to wait until KSeF has applied it.
PermissionsClient.revoke
def revoke(*, permission_id: str) -> PermissionOperationRevoke a non-authorization permission by permission id.
Use revoke_authorization() for authorization permissions such as self-invoicing.
Parameters
permission_id(str) — Identifier of the permission, from a query result.
Returns
PermissionOperation— A handle to the asynchronous revoke operation; callwait()to wait until KSeF has applied it.
Example
operation = auth.permissions.revoke(permission_id=permission.id)
operation.wait()PermissionsClient.revoke_common
def revoke_common(*, permission_id: str) -> GrantPermissionsResponseDeprecated: revoke a non-authorization permission by permission id.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use revoke() instead.
Parameters
permission_id(str) — Identifier of the permission, from a query result.
Returns
GrantPermissionsResponse— The reference of the asynchronous revoke operation; pollget_operation_status()for the result.
PermissionsClient.get_attachment_permission_status
def get_attachment_permission_status() -> AttachmentPermissionStatusReturn whether attachments are currently allowed for the subject.
Returns
AttachmentPermissionStatus— Whether attachments are currently allowed for the subject.
PermissionsClient.get_operation_status
def get_operation_status(*, reference_number: str) -> PermissionOperationStatusResponseFetch the status of an asynchronous permission operation.
Parameters
reference_number(str) — Reference number returned by a grant or revoke call.
Returns
PermissionOperationStatusResponse— The operation status;status.codeis200once it has completed successfully.
PermissionsClient.get_entity_roles
def get_entity_roles(
*,
params: OffsetPaginationParams | None = None,
) -> EntityRolesResponseDeprecated: fetch one page of roles assigned to the authenticated entity.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_entity_roles() instead; first_page() fetches one page.
Parameters
params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
EntityRolesResponse— One page of roles assigned to the authenticated entity.
PermissionsClient.query_authorizations
def query_authorizations(
*,
query: AuthorizationPermissionsQuery,
params: OffsetPaginationParams | None = None,
) -> AuthorizationPermissionsQueryResponseDeprecated: fetch one page of authorization grants matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_authorizations() instead; first_page() fetches one page.
Parameters
query(AuthorizationPermissionsQuery) — Filters for the authorization grants.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
AuthorizationPermissionsQueryResponse— One page of authorization grants.
PermissionsClient.query_entities
def query_entities(
*,
query: EntityPermissionsQuery,
params: OffsetPaginationParams | None = None,
) -> EntityPermissionsQueryResponseDeprecated: fetch one page of entity permission grants matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_entities() instead; first_page() fetches one page.
Parameters
query(EntityPermissionsQuery) — Filters for the entity permissions.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
EntityPermissionsQueryResponse— One page of entity permissions.
PermissionsClient.query_eu_entities
def query_eu_entities(
*,
query: EuEntityPermissionsQuery,
params: OffsetPaginationParams | None = None,
) -> EuEntityPermissionsQueryResponseDeprecated: fetch one page of EU-entity permissions matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_eu_entities() instead; first_page() fetches one page.
Parameters
query(EuEntityPermissionsQuery) — Filters for the EU-entity permissions.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
EuEntityPermissionsQueryResponse— One page of EU-entity permissions.
PermissionsClient.query_personal
def query_personal(
*,
query: PersonalPermissionsQuery,
params: OffsetPaginationParams | None = None,
) -> PersonalPermissionsQueryResponseDeprecated: fetch one page of permissions held by the authenticated subject.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_personal() instead; first_page() fetches one page.
Parameters
query(PersonalPermissionsQuery) — Filters for the permissions.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
PersonalPermissionsQueryResponse— One page of permissions held by the authenticated subject.
PermissionsClient.query_persons
def query_persons(
*,
query: PersonPermissionsQuery,
params: OffsetPaginationParams | None = None,
) -> PersonPermissionsQueryResponseDeprecated: fetch one page of person permission grants matching the provided filters.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_persons() instead; first_page() fetches one page.
Parameters
query(PersonPermissionsQuery) — Filters for the person permissions.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
PersonPermissionsQueryResponse— One page of person permissions.
PermissionsClient.query_subordinate_entities
def query_subordinate_entities(
*,
query: SubordinateEntityRolesQuery,
params: OffsetPaginationParams | None = None,
) -> SubordinateEntityRolesQueryResponseDeprecated: fetch one page of subordinate entity roles.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_subordinate_entities() instead; first_page() fetches one page.
Parameters
query(SubordinateEntityRolesQuery) — Filters for the subordinate entity roles.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
SubordinateEntityRolesQueryResponse— One page of subordinate entity roles.
PermissionsClient.query_subunits
def query_subunits(
*,
query: SubunitPermissionsQuery,
params: OffsetPaginationParams | None = None,
) -> SubunitPermissionsQueryResponseDeprecated: fetch one page of subunit permission grants.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list_subunits() instead; first_page() fetches one page.
Parameters
query(SubunitPermissionsQuery) — Filters for the subunit permissions.params(OffsetPaginationParams | None) — Page size and offset; defaults are used whenNone.
Returns
SubunitPermissionsQueryResponse— One page of subunit permissions.
PermissionsClient.list_entity_roles
def list_entity_roles(
*,
params: OffsetPaginationParams | None = None,
) -> Pager[EntityRole]List the roles assigned to the authenticated entity.
Nothing is requested until the result is consumed. Iterate it for every
role, call pages() for page-sized lists or first_page() for one
request only.
Parameters
params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
Pager[EntityRole]— A paging object over the roles assigned to the authenticated entity.
Example
for role in auth.permissions.list_entity_roles():
print(role.role)PermissionsClient.list_authorizations
def list_authorizations(
query: AuthorizationPermissionsQuery,
*,
params: OffsetPaginationParams | None = None,
) -> Pager[AuthorizationGrantDetail]List the authorization grants matching the provided filters.
Nothing is requested until the result is consumed. Iterate it for every
grant, call pages() for page-sized lists or first_page() for one
request only.
Parameters
query(AuthorizationPermissionsQuery) — Filters for the authorization grants.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
Pager[AuthorizationGrantDetail]— A paging object over the authorization grants.
Example
for grant in auth.permissions.list_authorizations(query):
print(grant.id)PermissionsClient.list_entities
def list_entities(
query: EntityPermissionsQuery,
*,
params: OffsetPaginationParams | None = None,
) -> Pager[EntityPermissionDetail]List the entity permission grants matching the provided filters.
Nothing is requested until the result is consumed. Iterate it for every
grant, call pages() for page-sized lists or first_page() for one
request only.
Parameters
query(EntityPermissionsQuery) — Filters for the entity permissions.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
Pager[EntityPermissionDetail]— A paging object over the entity permissions.
Example
for permission in auth.permissions.list_entities(query):
print(permission.id)PermissionsClient.list_eu_entities
def list_eu_entities(
query: EuEntityPermissionsQuery,
*,
params: OffsetPaginationParams | None = None,
) -> Pager[EuEntityPermission]List the EU-entity permissions matching the provided filters.
Nothing is requested until the result is consumed. Iterate it for every
permission, call pages() for page-sized lists or first_page() for
one request only.
Parameters
query(EuEntityPermissionsQuery) — Filters for the EU-entity permissions.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
Pager[EuEntityPermission]— A paging object over the EU-entity permissions.
Example
for permission in auth.permissions.list_eu_entities(query):
print(permission.id)PermissionsClient.list_personal
def list_personal(
query: PersonalPermissionsQuery,
*,
params: OffsetPaginationParams | None = None,
) -> Pager[PersonalPermissionDetail]List the permissions held by the authenticated subject.
Nothing is requested until the result is consumed. Iterate it for every
permission, call pages() for page-sized lists or first_page() for
one request only.
Parameters
query(PersonalPermissionsQuery) — Filters for the permissions.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
Pager[PersonalPermissionDetail]— A paging object over the permissions held by the authenticated subject.
Example
for permission in auth.permissions.list_personal(query):
print(permission.id)PermissionsClient.list_persons
def list_persons(
query: PersonPermissionsQuery,
*,
params: OffsetPaginationParams | None = None,
) -> Pager[PersonPermissionDetail]List the person permission grants matching the provided filters.
Nothing is requested until the result is consumed. Iterate it for every
grant, call pages() for page-sized lists or first_page() for one
request only.
Parameters
query(PersonPermissionsQuery) — Filters for the person permissions.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
Pager[PersonPermissionDetail]— A paging object over the person permissions.
Example
for permission in auth.permissions.list_persons(query):
print(permission.id)PermissionsClient.list_subordinate_entities
def list_subordinate_entities(
query: SubordinateEntityRolesQuery,
*,
params: OffsetPaginationParams | None = None,
) -> Pager[SubordinateEntityRoleDetail]List the subordinate entity roles matching the provided filters.
Nothing is requested until the result is consumed. Iterate it for every
role, call pages() for page-sized lists or first_page() for one
request only.
Parameters
query(SubordinateEntityRolesQuery) — Filters for the subordinate entity roles.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
Pager[SubordinateEntityRoleDetail]— A paging object over the subordinate entity roles.
Example
for role in auth.permissions.list_subordinate_entities(query):
print(role.role)PermissionsClient.list_subunits
def list_subunits(
query: SubunitPermissionsQuery,
*,
params: OffsetPaginationParams | None = None,
) -> Pager[SubunitPermission]List the subunit permission grants matching the provided filters.
Nothing is requested until the result is consumed. Iterate it for every
grant, call pages() for page-sized lists or first_page() for one
request only.
Parameters
query(SubunitPermissionsQuery) — Filters for the subunit permissions.params(OffsetPaginationParams | None) — Page size and offset of the first page; defaults are used whenNone.
Returns
Pager[SubunitPermission]— A paging object over the subunit permissions.
Example
for permission in auth.permissions.list_subunits(query):
print(permission.id)SessionManagementClient
Import: from ksef2.clients import SessionManagementClient
class SessionManagementClientSessionManagementClient(transport: Middleware)Manage authentication sessions opened through the auth API.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
SessionManagementClient.query
def query(
*,
page_size: int | None = None,
continuation_token: str | None = None,
) -> AuthenticationSessionsResponseDeprecated: fetch one page of authentication sessions.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead; first_page() fetches one page.
Parameters
page_size(int | None) — Maximum number of sessions to request from KSeF.continuation_token(str | None) — Cursor returned by a previous page.
Returns
AuthenticationSessionsResponse— One page of authentication sessions for the current subject.
SessionManagementClient.all
def all(*, page_size: int | None = None) -> Iterator[AuthenticationSessionsResponse]Deprecated: iterate through all authentication session pages.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list().pages() instead.
Parameters
page_size(int | None) — Maximum number of sessions to request per page.
Yields
AuthenticationSessionsResponse— Successive pages of authentication sessions until KSeF stopsAuthenticationSessionsResponse— returning a continuation token.
SessionManagementClient.terminate_current
def terminate_current() -> NoneTerminate the authentication session backing the current bearer token.
SessionManagementClient.terminate
def terminate(reference_number: str) -> NoneTerminate an authentication session by reference number.
Parameters
reference_number(str) — Reference number of the authentication session to terminate.
SessionManagementClient.close
def close(*, reference_number: str) -> NoneDeprecated: terminate an authentication session by reference number.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use terminate() instead.
Parameters
reference_number(str) — Reference number of the authentication session to terminate.
Returns
None—Noneonce the session is terminated.
SessionManagementClient.list
def list(*, page_size: int | None = None) -> Pager[AuthenticationSession]List the authentication sessions of the current subject.
Nothing is requested until the result is consumed. Iterate it for every
session, call pages() for page-sized lists or first_page() for one
request only.
Parameters
page_size(int | None) — Maximum number of sessions to request per page; the KSeF default whenNone.
Returns
Pager[AuthenticationSession]— A paging object over the authentication sessions.
Example
for session in auth.sessions.list():
print(session.reference_number)TemporalTestData
Import: from ksef2.clients import TemporalTestData
class TemporalTestDataTemporalTestData(client: TestDataClient)Context manager that records testdata mutations and reverts them on exit.
Cleanup failures are logged and suppressed. Direct mutation methods expose the same catch contract as the parent test-data branch.
Raises
KSeFApiError— If KSeF returns an API error response during direct mutations.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
TemporalTestData.create_subject
def create_subject(
*,
nip: str,
subject_type: SubjectType,
description: str,
subunits: list[SubUnit] | None = None,
created_date: datetime | None = None,
) -> NoneCreate a TEST subject and register it for context-manager cleanup.
Parameters
nip(str) — NIP of the subject to create.subject_type(SubjectType) — Kind of subject, such as an enforcement authority or a VAT group.description(str) — Description of the subject.subunits(list[SubUnit] | None) — Subunits to create with the subject;Nonefor none.created_date(datetime | None) — Creation date to record for the subject;Nonefor now.
TemporalTestData.delete_subject
def delete_subject(*, nip: str) -> NoneDelete a TEST subject and remove it from cleanup tracking.
Parameters
nip(str) — NIP of the subject to delete.
TemporalTestData.create_person
def create_person(
*,
nip: str,
pesel: str,
description: str,
is_bailiff: bool = False,
is_deceased: bool = False,
created_date: datetime | None = None,
) -> NoneCreate a TEST person and register it for context-manager cleanup.
Parameters
nip(str) — NIP of the person.pesel(str) — PESEL of the person.description(str) — Description of the person.is_bailiff(bool) — Whether the person is a bailiff.is_deceased(bool) — Whether the person is marked as deceased.created_date(datetime | None) — Creation date to record for the person;Nonefor now.
TemporalTestData.delete_person
def delete_person(*, nip: str) -> NoneDelete a TEST person and remove it from cleanup tracking.
Parameters
nip(str) — NIP of the person to delete.
TemporalTestData.grant_permissions
def grant_permissions(
*,
permissions: list[Permission],
grant_to: Identifier,
in_context_of: Identifier,
) -> NoneGrant TEST permissions and register them for cleanup.
Parameters
permissions(list[Permission]) — Permissions to grant.grant_to(Identifier) — Identifier of the subject receiving the permissions.in_context_of(Identifier) — Identifier of the context in which the permissions apply.
TemporalTestData.revoke_permissions
def revoke_permissions(*, revoke_from: Identifier, in_context_of: Identifier) -> NoneRevoke TEST permissions and remove them from cleanup tracking.
Parameters
revoke_from(Identifier) — Identifier of the subject losing the permissions.in_context_of(Identifier) — Identifier of the context from which the permissions are revoked.
TemporalTestData.enable_attachments
def enable_attachments(*, nip: str) -> NoneEnable TEST attachments and register the context for cleanup.
Parameters
nip(str) — NIP of the subject to enable attachments for.
TemporalTestData.revoke_attachments
def revoke_attachments(*, nip: str, expected_end_date: date | None = None) -> NoneRevoke TEST attachment access and remove it from cleanup tracking.
Parameters
nip(str) — NIP of the subject to revoke attachments for.expected_end_date(date | None) — Date on which attachment permission should end;Noneto revoke immediately.
TemporalTestData.block_context
def block_context(*, context: AuthContextIdentifier) -> NoneBlock a TEST context and register it for cleanup.
Parameters
context(AuthContextIdentifier) — Authentication context to block.
TemporalTestData.unblock_context
def unblock_context(*, context: AuthContextIdentifier) -> NoneUnblock a TEST context and remove it from cleanup tracking.
Parameters
context(AuthContextIdentifier) — Authentication context to unblock.
TestDataClient
Import: from ksef2.clients import TestDataClient
class TestDataClientTestDataClient(transport: Middleware)Helper for TEST-only endpoints that seed and mutate sandbox data.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
TestDataClient.create_subject
def create_subject(
*,
nip: str,
subject_type: SubjectType,
description: str,
subunits: list[SubUnit] | None = None,
created_date: datetime | None = None,
) -> NoneCreate a test subject with optional subunits.
Parameters
nip(str) — NIP of the subject to create.subject_type(SubjectType) — Kind of subject, such as an enforcement authority or a VAT group.description(str) — Description of the subject.subunits(list[SubUnit] | None) — Subunits to create with the subject;Nonefor none.created_date(datetime | None) — Creation date to record for the subject;Nonefor now.
TestDataClient.delete_subject
def delete_subject(*, nip: str) -> NoneDelete a test subject by NIP.
Parameters
nip(str) — NIP of the subject to delete.
TestDataClient.create_person
def create_person(
*,
nip: str,
pesel: str,
description: str,
is_bailiff: bool = False,
is_deceased: bool = False,
created_date: datetime | None = None,
) -> NoneCreate a test person in the chosen subject.
Parameters
nip(str) — NIP of the person.pesel(str) — PESEL of the person.description(str) — Description of the person.is_bailiff(bool) — Whether the person is a bailiff.is_deceased(bool) — Whether the person is marked as deceased.created_date(datetime | None) — Creation date to record for the person;Nonefor now.
TestDataClient.delete_person
def delete_person(*, nip: str) -> NoneDelete a test person by subject NIP.
Parameters
nip(str) — NIP of the person to delete.
TestDataClient.grant_permissions
def grant_permissions(
*,
permissions: list[Permission],
grant_to: Identifier,
in_context_of: Identifier,
) -> NoneGrant test permissions in a chosen context.
Parameters
permissions(list[Permission]) — Permissions to grant.grant_to(Identifier) — Identifier of the subject receiving the permissions.in_context_of(Identifier) — Identifier of the context in which the permissions apply.
TestDataClient.revoke_permissions
def revoke_permissions(*, revoke_from: Identifier, in_context_of: Identifier) -> NoneRevoke test permissions in a chosen context.
Parameters
revoke_from(Identifier) — Identifier of the subject losing the permissions.in_context_of(Identifier) — Identifier of the context from which the permissions are revoked.
TestDataClient.enable_attachments
def enable_attachments(*, nip: str) -> NoneEnable invoice attachments for a test subject.
Parameters
nip(str) — NIP of the subject to enable attachments for.
TestDataClient.revoke_attachments
def revoke_attachments(*, nip: str, expected_end_date: date | None = None) -> NoneRevoke attachment permissions, optionally effective on a given date.
Parameters
nip(str) — NIP of the subject to revoke attachments for.expected_end_date(date | None) — Date on which attachment permission should end;Noneto revoke immediately.
TestDataClient.block_context
def block_context(*, context: AuthContextIdentifier) -> NoneBlock authentication for a specific test context.
Parameters
context(AuthContextIdentifier) — Authentication context to block.
TestDataClient.unblock_context
def unblock_context(*, context: AuthContextIdentifier) -> NoneUnblock authentication for a specific test context.
Parameters
context(AuthContextIdentifier) — Authentication context to unblock.
TestDataClient.update_certificate_valid_to
def update_certificate_valid_to(*, serial_number: str, valid_to: datetime) -> NoneShorten the validity of a certificate in the TEST environment.
Parameters
serial_number(str) — Serial number of the certificate to shorten.valid_to(datetime) — New, earlier end of the certificate validity period.
TestDataClient.temporal
def temporal() -> TemporalTestDataReturn a context manager that automatically cleans up created test data.
Returns
TemporalTestData— A context manager that automatically cleans up created test data.
TokensClient
Import: from ksef2.clients import TokensClient
class TokensClientTokensClient(transport: Middleware)High-level API for the KSeF token lifecycle.
Catch KSeFException for SDK-classified failures raised by this branch,
and httpx.HTTPError for transport failures.
Raises
KSeFApiError— If KSeF returns an API error response. CatchKSeFAuthErrorfor authentication or authorization failures andKSeFRateLimitErrorfor throttling.KSeFValidationError— If a KSeF response cannot be parsed into SDK models.httpx.HTTPError— If the HTTP transport fails before KSeF returns a response.
Methods
TokensClient.wait_for_activation
def wait_for_activation(
*,
reference_number: str,
timeout: float = 60.0,
poll_interval: float = 1.0,
) -> TokenStatusResponseDeprecated: wait until a generated token becomes active or reaches a terminal state.
Deprecated
May be removed no earlier than ksef2 2.0.0. Call wait() on the handle returned by generate() instead.
Parameters
reference_number(str) — Reference returned bygenerate.timeout(float) — Maximum number of seconds to wait for activation.poll_interval(float) — Delay in seconds between status checks.
Returns
TokenStatusResponse— The first status response that reports the token as active.
Raises
KSeFApiError— If activation ends in a terminal failure state.KSeFTokenStatusTimeoutError— If polling exceedstimeout.httpx.HTTPError— If a status request fails at the transport boundary.
TokensClient.generate
def generate(
*,
permissions: builtins.list[TokenPermission],
description: str,
) -> GeneratedTokenCreate a token and return a handle exposing its one-time credential.
Parameters
permissions(builtins.list[TokenPermission]) — Permissions to include in the generated token.description(str) — Human-readable label shown in KSeF token listings.
Returns
GeneratedToken— A handle whosetokenis the one-time secret KSeF returns only once;GeneratedToken— persist it before calling the handle'swait()for activation.
Example
token = auth.tokens.generate(
permissions=["invoice_read"], description="reporting"
)
secret = token.token # store it now, KSeF will not show it again
token.wait()TokensClient.list_page
def list_page(
*,
continuation_token: str | None = None,
params: TokenListParams | None = None,
) -> QueryTokensResponseDeprecated: fetch one page of tokens using optional filters and continuation state.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list() instead; first_page() fetches one page.
Parameters
continuation_token(str | None) — Token identifying the next page to fetch.params(TokenListParams | None) — Optional filters and page size for the request.
Returns
QueryTokensResponse— A single page of token results.
TokensClient.list_all
def list_all(*, params: TokenListParams | None = None) -> Iterator[QueryTokensResponse]Deprecated: iterate through all token pages until KSeF stops returning a continuation token.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use list().pages() instead.
Parameters
params(TokenListParams | None) — Optional filters and page size applied to every request.
Yields
QueryTokensResponse— Each page returned by the token listing endpoint.
TokensClient.get_status
def get_status(*, reference_number: str) -> TokenStatusResponseReturn the current status of a token.
Parameters
reference_number(str) — Reference number of the token.
Returns
TokenStatusResponse— The token's current lifecycle status.
TokensClient.status
def status(*, reference_number: str) -> TokenStatusResponseDeprecated: return the current status of a token.
Deprecated
May be removed no earlier than ksef2 2.0.0. Use get_status() instead.
Parameters
reference_number(str) — Reference number of the token.
Returns
TokenStatusResponse— The token's current lifecycle status.
TokensClient.revoke
def revoke(*, reference_number: str) -> NoneRevoke a token.
Parameters
reference_number(str) — Reference number of the token to revoke.
TokensClient.list
def list(*, params: TokenListParams | None = None) -> Pager[TokenInfo]List the tokens of the authenticated context.
Nothing is requested until the result is consumed. Iterate it for every
token, call pages() for page-sized lists or first_page() for one
request only.
Parameters
params(TokenListParams | None) — Optional filters and page size applied to every request.
Returns
Pager[TokenInfo]— A paging object over the tokens matchingparams.
Example
for token in auth.tokens.list():
print(token.reference_number, token.status)