GitHub

ksef2.models

Public domain model facade.

On this page

Public domain model facade.

Classes

ApiRateLimits

Import: from ksef2.models import ApiRateLimits

class ApiRateLimits(KSeFBaseModel)
python

Rate limits grouped by API operation family.

Attributes

  • online_session: RateLimitValues — Limits for opening online sessions.
  • online_session_close: RateLimitValues — Limits for closing online sessions.
  • batch_session: RateLimitValues — Limits for opening batch sessions.
  • batch_session_close: RateLimitValues — Limits for closing batch sessions.
  • invoice_send: RateLimitValues — Limits for sending invoices.
  • invoice_status: RateLimitValues — Limits for reading invoice status.
  • session_list: RateLimitValues — Limits for listing sessions.
  • session_invoice_list: RateLimitValues — Limits for listing invoices of a session.
  • session_misc: RateLimitValues — Limits for other session operations.
  • invoice_metadata: RateLimitValues — Limits for querying invoice metadata.
  • invoice_export: RateLimitValues — Limits for starting invoice exports.
  • invoice_export_status: RateLimitValues — Limits for reading export status.
  • invoice_download: RateLimitValues — Limits for downloading invoices.
  • collective_identifier: RateLimitValues — Limits for collective identifier operations.
  • other: RateLimitValues — Limits for operations not covered by another category.
  • anonymous: RateLimitValues — Limits for unauthenticated requests.
  • global_: RateLimitValues — Overall limits across all operations.

AttachmentPermissionStatus

Import: from ksef2.models import AttachmentPermissionStatus

class AttachmentPermissionStatus(KSeFBaseModel)
python

Current attachment availability for the authenticated subject.

Attributes

  • is_attachment_allowed: bool — Whether the subject may currently send invoices with attachments.
  • revoked_date: datetime | None — When attachment permission was or will be revoked; None if it is not scheduled for revocation.

AuthContextIdentifier

Import: from ksef2.models import AuthContextIdentifier

class AuthContextIdentifier(KSeFBaseModel)
python

Authentication context identifier used for blocking and unblocking access.

Attributes

  • type: AuthContextIdentifierType — Kind of identifier in value.
  • value: str — Identifier of the authentication context.

AuthenticationResumeState

Import: from ksef2.models import AuthenticationResumeState

class AuthenticationResumeState(KSeFPersistedModel)
python

Serializable authentication state used to rehydrate an authenticated client.

Use to_json() when intentionally exporting resumable JSON containing bearer credentials. Normal Pydantic dumps and repr output keep token values redacted.

Attributes

  • format_version: Literal[1] — Version of the serialized state format; currently always 1.
  • access_token: SecretStr — Access token value.
  • access_token_valid_until: datetime — When the access token expires.
  • refresh_token: SecretStr — Refresh token value.
  • refresh_token_valid_until: datetime — When the refresh token expires.

Methods

AuthenticationResumeState.from_tokens

@classmethod
def from_tokens(auth_tokens: AuthTokens) -> Self
python

Create resume state from authenticated token credentials.

Parameters

  • auth_tokens (AuthTokens) — Access and refresh tokens obtained from authentication.

Returns

  • Self — Resume state holding both tokens and their expiry times.

AuthenticationResumeState.to_tokens

def to_tokens() -> AuthTokens
python

Return the token model needed to bind authenticated SDK clients.

Returns

  • AuthTokens — The access and refresh tokens with their expiry times.

AuthenticationResumeState.to_dict

def to_dict(*, mode: Literal['json', 'python'] | str = 'json') -> dict[str, object]
python

Export authentication state with bearer credentials included.

Store and log the result only as protected credential material.

Parameters

  • mode (Literal['json', 'python'] | str) — Pydantic dump mode, "json" for JSON-safe values or "python" for native types.

Returns

  • dict[str, object] — A dictionary containing the plain access and refresh tokens.

AuthenticationResumeState.to_json

def to_json(*, indent: int | None = None) -> str
python

Export authentication state as JSON with bearer credentials included.

Store and log the result only as protected credential material.

Parameters

  • indent (int | None) — Number of spaces to indent nested values; None for compact output.

Returns

  • str — JSON text containing the plain access and refresh tokens.

AuthenticationResumeState.from_dict

@classmethod
def from_dict(state: Mapping[str, object]) -> Self
python

Restore authentication state from a dictionary exported by to_dict().

Parameters

  • state (Mapping[str, object]) — Mapping produced by to_dict().

Returns

  • Self — The restored authentication state.

AuthenticationResumeState.from_json

@classmethod
def from_json(state: str | bytes | bytearray) -> Self
python

Restore authentication state from JSON exported by to_json().

Parameters

  • state (str | bytes | bytearray) — JSON text produced by to_json().

Returns

  • Self — The restored authentication state.

AuthenticationSession

Import: from ksef2.models import AuthenticationSession

class AuthenticationSession(KSeFBaseModel)
python

Metadata describing an authentication session visible in session listings.

Attributes

  • reference_number: str — Reference number of the authentication session.
  • start_date: datetime — When the session started.
  • authentication_method: AuthenticationMethod — Authentication method used.
  • authentication_method_category: AuthenticationMethodCategory — Broad category of the authentication method.
  • authentication_method_code: str — Raw authentication method code reported by KSeF.
  • authentication_method_display_name: str — Display name of the authentication method.
  • status_code: int — Numeric status code of the session.
  • status_description: str — Human-readable description of the status.
  • status_details: list[str] | None — Additional status details, if any.
  • is_token_redeemed: bool | None — Whether the access tokens were already redeemed.
  • last_token_refresh_date: datetime | None — When the access token was last refreshed; None if never.
  • refresh_token_valid_until: datetime | None — When the refresh token expires.
  • is_current: bool | None — Whether this is the session of the calling client.

AuthenticationSessionsResponse

Import: from ksef2.models import AuthenticationSessionsResponse

class AuthenticationSessionsResponse(KSeFBaseModel)
python

A single page of authentication sessions.

Attributes

  • continuation_token: str | None — Opaque token for requesting the next page; None when there are no more pages.
  • items: list[AuthenticationSession] — Authentication sessions on this page.

AuthInitResponse

Import: from ksef2.models import AuthInitResponse

class AuthInitResponse(KSeFBaseModel)
python

Initial authentication response containing the short-lived auth token.

Attributes

  • reference_number: str — Reference number of the authentication operation.
  • authentication_token: TokenCredentials — Short-lived token used to poll the operation and redeem the access tokens.

AuthOperationStatus

Import: from ksef2.models import AuthOperationStatus

class AuthOperationStatus(KSeFBaseModel)
python

Status of an in-progress authentication operation.

Attributes

  • start_date: datetime — When the authentication operation started.
  • authentication_method: AuthenticationMethod — Authentication method in use.
  • authentication_method_category: AuthenticationMethodCategory — Broad category of the authentication method.
  • authentication_method_code: str — Raw authentication method code reported by KSeF.
  • authentication_method_display_name: str — Display name of the authentication method.
  • status_code: int — Numeric status code; 200 means authentication succeeded.
  • status_description: str — Human-readable description of the status.
  • status_details: list[str] | None — Additional status details, if any.
  • is_token_redeemed: bool | None — Whether the access tokens were already redeemed.
  • last_token_refresh_date: datetime | None — When the access token was last refreshed; None if never.
  • refresh_token_valid_until: datetime | None — When the refresh token expires.

AuthorizationGrantDetail

Import: from ksef2.models import AuthorizationGrantDetail

class AuthorizationGrantDetail(KSeFBaseModel)
python

Authorization grant returned from authorization queries.

Attributes

  • id: Annotated[str, Field(max_length=36, min_length=36)] — Grant identifier (36-character UUID), usable for revocation.
  • author_type: CertificateSubjectIdentifierType | None — Kind of identifier in author_value.
  • author_value: str | None — Identifier of the person who created the grant.
  • authorized_entity_type: AuthorizationSubjectIdentifierType — Kind of identifier in authorized_entity_value.
  • authorized_entity_value: str — Identifier of the entity that received the authorization.
  • authorizing_entity_type: EntityIdentifierType — Kind of identifier in authorizing_entity_value.
  • authorizing_entity_value: str — Identifier of the entity that gave the authorization.
  • authorization_scope: AuthorizationPermissionType — Authorization scope that was granted.
  • description: str — Reason recorded when the grant was created.
  • entity_full_name: str | None — Full name of the authorized entity, if known.
  • start_date: datetime — When the grant became effective.

AuthorizationPermissionsQuery

Import: from ksef2.models import AuthorizationPermissionsQuery

class AuthorizationPermissionsQuery(KSeFBaseModel)
python

Filters for querying authorization grants between entities.

Attributes

  • query_type: QueryType — Whether to list grants granted by or received by the current context.
  • permission_types: list[AuthorizationPermissionType] | None — Restrict results to these authorization scopes; None for all.
  • authorizing_type: EntityIdentifierType | None — Kind of identifier in authorizing_value.
  • authorizing_value: str | None — Restrict results to grants given by this entity (NIP).
  • authorized_type: AuthorizationSubjectIdentifierType | None — Kind of identifier in authorized_value.
  • authorized_value: str | None — Restrict results to grants received by this entity.

AuthorizationPermissionsQueryResponse

Import: from ksef2.models import AuthorizationPermissionsQueryResponse

class AuthorizationPermissionsQueryResponse(KSeFBaseModel)
python

One page of authorization grant query results.

Attributes

  • authorization_grants: list[AuthorizationGrantDetail] — Authorization grants on this page.
  • has_more: bool — Whether more results are available after this page.

AuthTokens

Import: from ksef2.models import AuthTokens

class AuthTokens(KSeFBaseModel)
python

Access and refresh tokens returned after successful authentication.

Attributes

  • access_token: TokenCredentials — Short-lived token sent with API requests.
  • refresh_token: TokenCredentials — Longer-lived token used to obtain new access tokens.

BaseSessionResumeState

Import: from ksef2.models import BaseSessionResumeState

class BaseSessionResumeState(KSeFPersistedModel)
python

Base class for session resume state with common fields.

This class contains fields shared between online and batch sessions. It provides serialization/deserialization support and helper methods for accessing the encryption keys.

Deprecated

The alias BaseSessionState may be removed no earlier than ksef2 2.0.0; use BaseSessionResumeState. An access_token key in restored state is ignored and also deprecated; persist AuthenticationResumeState separately instead.

Attributes

  • format_version: Literal[1] — Version of the serialized state format; currently always 1.
  • reference_number: str — Reference number of the session.
  • aes_key: SecretStr — AES key for encrypting data, Base64 encoded.
  • iv: SecretStr — Initialization vector for AES encryption, Base64 encoded.
  • form_code: FormSchema — Invoice schema used for this session.

Methods

BaseSessionResumeState.get_aes_key_bytes

def get_aes_key_bytes() -> bytes
python

Get the AES key as raw bytes.

Returns

  • bytes — The raw AES key.

BaseSessionResumeState.get_iv_bytes

def get_iv_bytes() -> bytes
python

Get the initialization vector as raw bytes.

Returns

  • bytes — The raw initialization vector.

BaseSessionResumeState.to_dict

def to_dict(*, mode: Literal['json', 'python'] | str = 'json') -> dict[str, object]
python

Export resume state with credentials included.

The returned data contains the AES key, IV, and for batch sessions the presigned upload URLs. Store and log it only as protected credential material.

Parameters

  • mode (Literal['json', 'python'] | str) — Pydantic dump mode, "json" for JSON-safe values or "python" for native types.

Returns

  • dict[str, object] — A dictionary with the full resume state, including secrets.

BaseSessionResumeState.to_json

def to_json(*, indent: int | None = None) -> str
python

Export resume state as JSON with credentials included.

Parameters

  • indent (int | None) — Number of spaces to indent nested values; None for compact output.

Returns

  • str — JSON text with the full resume state, including secrets.

BaseSessionResumeState.from_dict

@classmethod
def from_dict(state: Mapping[str, object]) -> Self
python

Restore resume state from a dictionary exported by to_dict().

Parameters

  • state (Mapping[str, object]) — Mapping produced by to_dict().

Returns

  • Self — The restored resume state.

BaseSessionResumeState.from_json

@classmethod
def from_json(state: str | bytes | bytearray) -> Self
python

Restore resume state from JSON exported by to_json().

Parameters

  • state (str | bytes | bytearray) — JSON text produced by to_json().

Returns

  • Self — The restored resume state.

BaseSessionResumeState.dump_state

def dump_state(*, mode: Literal['json', 'python'] | str = 'python') -> dict[str, object]
python

Deprecated compatibility wrapper for to_dict().

Deprecated

May be removed no earlier than ksef2 2.0.0. Use to_dict() instead.

Parameters

  • mode (Literal['json', 'python'] | str) — Pydantic dump mode, "json" for JSON-safe values or "python" for native types.

Returns

  • dict[str, object] — The same dictionary as to_dict().

BaseSessionResumeState.model_dump_sensitive

def model_dump_sensitive(
    *,
    mode: Literal['json', 'python'] | str = 'python',
) -> dict[str, object]
python

Deprecated compatibility wrapper for to_dict().

Deprecated

May be removed no earlier than ksef2 2.0.0. Use to_dict() instead.

Parameters

  • mode (Literal['json', 'python'] | str) — Pydantic dump mode, "json" for JSON-safe values or "python" for native types.

Returns

  • dict[str, object] — The same dictionary as to_dict().

BaseSessionResumeState.model_dump_sensitive_json

def model_dump_sensitive_json(*, indent: int | None = None) -> str
python

Deprecated compatibility wrapper for to_json().

Deprecated

May be removed no earlier than ksef2 2.0.0. Use to_json() instead.

Parameters

  • indent (int | None) — Number of spaces to indent nested values; None for compact output.

Returns

  • str — The same JSON text as to_json().

BaseSessionResumeState.from_state

@classmethod
def from_state(state: Mapping[str, object]) -> Self
python

Deprecated compatibility wrapper for from_dict().

Deprecated

May be removed no earlier than ksef2 2.0.0. Use from_dict() instead.

Parameters

  • state (Mapping[str, object]) — Mapping produced by to_dict().

Returns

  • Self — The restored resume state.

BatchEncryptionData

Import: from ksef2.models import BatchEncryptionData

class BatchEncryptionData(KSeFBaseModel)
python

Encryption material used for the prepared batch payload.

Attributes

  • aes_key: str — AES-256 session key, Base64-encoded. Excluded from serialization and repr.
  • iv: str — AES initialization vector, Base64-encoded. Excluded from serialization and repr.
  • encrypted_key: str — Session key encrypted with the KSeF public key, Base64-encoded. Excluded from serialization and repr.
  • public_key_id: str | None — Identifier of the KSeF public key used for encryption; None for the default.

Methods

BatchEncryptionData.from_bytes

@classmethod
def from_bytes(
    *,
    aes_key: bytes,
    iv: bytes,
    encrypted_key: bytes,
    public_key_id: str | None = None,
) -> Self
python

Create encoded batch encryption data from raw key bytes.

Parameters

  • aes_key (bytes) — Raw AES-256 key.
  • iv (bytes) — Raw AES initialization vector.
  • encrypted_key (bytes) — AES key encrypted with the KSeF public key.
  • public_key_id (str | None) — Identifier of the KSeF public key used; None for the default.

Returns

  • Self — Encryption data with all byte values Base64-encoded.

BatchEncryptionData.get_aes_key_bytes

def get_aes_key_bytes() -> bytes
python

Return the decoded AES key.

Returns

  • bytes — The raw AES key bytes.

BatchEncryptionData.get_iv_bytes

def get_iv_bytes() -> bytes
python

Return the decoded initialization vector.

Returns

  • bytes — The raw initialization vector bytes.

BatchEncryptionData.get_encrypted_key_bytes

def get_encrypted_key_bytes() -> bytes
python

Return the decoded encrypted symmetric key.

Returns

  • bytes — The raw encrypted key bytes.

BatchEncryptionData.to_sensitive_dict

def to_sensitive_dict() -> dict[str, str | None]
python

Export encryption material for deliberately protected persistence.

Returns

  • dict[str, str | None] — A dictionary with the Base64 AES key, IV, encrypted key and public key identifier.

BatchFileInfo

Import: from ksef2.models import BatchFileInfo

class BatchFileInfo(KSeFBaseModel)
python

Information about the batch file being uploaded.

Attributes

  • file_size: int — Total size of the batch file in bytes. Max 5GB.
  • file_hash: str — SHA-256 hash of the batch file, Base64 encoded.
  • compression_type: CompressionType | None — Compression used for the batch file. Defaults to KSeF's ZIP behavior.
  • parts: list[BatchFilePart] — List of file parts. Max 50 parts, each max 100MB before encryption.

BatchFilePart

Import: from ksef2.models import BatchFilePart

class BatchFilePart(KSeFBaseModel)
python

Information about a part of the batch file.

Attributes

  • ordinal_number: int — Sequential number of the file part (1-indexed).
  • file_size: int — Size of the encrypted file part in bytes.
  • file_hash: str — SHA-256 hash of the encrypted file part, Base64 encoded.

BatchInvoice

Import: from ksef2.models import BatchInvoice

class BatchInvoice(KSeFBaseModel)
python

Single invoice payload to include in a batch ZIP.

Attributes

  • file_name: str — Name of the ZIP entry, for example invoice-1.xml.
  • content: bytes — Invoice XML bytes.

BatchInvoiceHash

Import: from ksef2.models import BatchInvoiceHash

class BatchInvoiceHash(KSeFBaseModel)
python

Correlation data between a ZIP entry and the original XML hash.

Attributes

  • file_name: str — Name of the ZIP entry the hash belongs to.
  • invoice_hash: str — SHA-256 hash of the original invoice XML, Base64-encoded.

BatchPreparedPart

Import: from ksef2.models import BatchPreparedPart

class BatchPreparedPart(KSeFBaseModel)
python

Prepared encrypted batch part ready for upload.

Attributes

  • ordinal_number: int — One-based position of the part in the package.
  • content: bytes — Encrypted part bytes to upload.
  • file_size: int — Size of the encrypted part in bytes.
  • file_hash: str — SHA-256 hash of the encrypted part, Base64-encoded.

BatchSessionResumeState

Import: from ksef2.models import BatchSessionResumeState

class BatchSessionResumeState(BaseSessionResumeState)
python

Serializable resume state of a batch session.

This class holds all information needed to resume a batch session or to upload file parts. Use to_json() when intentionally exporting resumable JSON containing encryption material and presigned upload URLs.

Inherits common session fields from BaseSessionResumeState:

  • reference_number, aes_key, iv, form_code
  • get_aes_key_bytes(), get_iv_bytes() helper methods

Deprecated

The alias BatchSessionState may be removed no earlier than ksef2 2.0.0; use BatchSessionResumeState.

Attributes

  • part_upload_requests: list[PartUploadRequest] — Upload instructions for each file part.

Methods

BatchSessionResumeState.to_dict

def to_dict(*, mode: Literal['json', 'python'] | str = 'json') -> dict[str, object]
python

Export batch resume state with secrets and upload URLs included.

The returned data contains the AES key, IV, and presigned upload URLs. Store and log it only as protected credential material.

Parameters

  • mode (Literal['json', 'python'] | str) — Pydantic dump mode, "json" for JSON-safe values or "python" for native types.

Returns

  • dict[str, object] — A dictionary with the full resume state, including secrets.

BatchSessionResumeState.from_encoded

@classmethod
def from_encoded(
    reference_number: str,
    aes_key: bytes,
    iv: bytes,
    form_code: FormSchema,
    part_upload_requests: list[PartUploadRequest],
    *,
    access_token: str | None = None,
) -> Self
python

Create state from raw bytes (aes_key, iv).

Parameters

  • reference_number (str) — Batch session reference number.
  • aes_key (bytes) — Raw AES key bytes.
  • iv (bytes) — Raw initialization vector bytes.
  • form_code (FormSchema) — Invoice schema for this session.
  • part_upload_requests (list[PartUploadRequest]) — Upload instructions for file parts.
  • access_token (str | None) — Deprecated and ignored. Persist authentication state separately with AuthenticationResumeState.

Returns

  • Self — BatchSessionResumeState with Base64-encoded key and IV.

BlockContextRequest

Import: from ksef2.models import BlockContextRequest

class BlockContextRequest(KSeFBaseModel)
python

Payload used to block authentication for a TEST context.

Attributes

  • context: AuthContextIdentifier — Authentication context to block.

Certificate

Import: from ksef2.models import Certificate

class Certificate(KSeFBaseModel)
python

Issued certificate payload returned by retrieval endpoints.

Attributes

  • base64_encoded_certificate: str — DER-encoded X.509 certificate, Base64-encoded.
  • name: str — Name given to the certificate at enrollment.
  • serial_number: CertificateSerialNumber — Certificate serial number, in uppercase hexadecimal.
  • certificate_type: CertificateTypeValue — Certificate type, authentication or offline.

CertificateEnrollmentData

Import: from ksef2.models import CertificateEnrollmentData

class CertificateEnrollmentData(KSeFBaseModel)
python

Subject data that should be embedded in a certificate enrollment CSR.

Attributes

  • common_name: str — Common name (CN) of the subject.
  • name: str | None — Given name of the subject, for certificates issued to a natural person.
  • surname: str | None — Surname of the subject, for certificates issued to a natural person.
  • iso_country_code: str — Two-letter ISO 3166 country code of the subject.
  • serial_number: str | None — Serial number attribute of the subject, such as a PESEL or NIP identifier.
  • unique_identifier: str | None — Unique identifier attribute of the subject.
  • organization_name: str | None — Organization name of the subject, for certificates issued to an entity.
  • organization_identifier: str | None — Organization identifier of the subject, such as VATPL-<NIP>.

Methods

CertificateEnrollmentData.country_name (property)

country_name: str
python

Alias for iso_country_code used by certificate tooling.

Returns

  • str — The two-letter ISO country code.

CertificateEnrollmentResponse

Import: from ksef2.models import CertificateEnrollmentResponse

class CertificateEnrollmentResponse(KSeFBaseModel)
python

Reference returned after submitting a certificate enrollment request.

Attributes

  • reference_number: str — KSeF reference number of the operation or resource.
  • timestamp: datetime — When KSeF accepted the enrollment request.

CertificateEnrollmentStatusResponse

Import: from ksef2.models import CertificateEnrollmentStatusResponse

class CertificateEnrollmentStatusResponse(KSeFBaseModel)
python

Current status of a certificate enrollment request.

Attributes

  • request_date: datetime — When the enrollment was requested.
  • status_code: int — Numeric status code; 200 means the certificate was issued.
  • status_description: str — Human-readable description of the status.
  • status_details: list[str] | None — Additional status details, if any.
  • certificate_serial_number: CertificateSerialNumber | None — Serial number of the issued certificate; None until issued.

CertificateInfo

Import: from ksef2.models import CertificateInfo

class CertificateInfo(KSeFBaseModel)
python

Metadata for one certificate visible in certificate queries.

Attributes

  • serial_number: CertificateSerialNumber — Certificate serial number, in uppercase hexadecimal.
  • name: str — Name given to the certificate at enrollment.
  • common_name: str — Common name (CN) of the certificate subject.
  • type: CertificateTypeValue — Certificate type, authentication or offline.
  • status: CertificateStatusValue — Lifecycle status of the certificate, such as active or revoked.
  • subject_identifier: SubjectIdentifier — Identifier of the subject the certificate was issued for.
  • valid_from: datetime — Start of the certificate validity period.
  • valid_to: datetime — End of the certificate validity period.
  • last_use_date: datetime | None — When the certificate was last used; None if never used.
  • request_date: datetime — When the certificate was requested.

CertificateLimitsResponse

Import: from ksef2.models import CertificateLimitsResponse

class CertificateLimitsResponse(KSeFBaseModel)
python

Effective enrollment and certificate quotas for the current subject.

Attributes

  • can_request: bool — Whether the subject may currently submit an enrollment request.
  • enrollment_limit: int — Maximum number of enrollment requests allowed.
  • enrollment_remaining: int — Number of enrollment requests still available.
  • certificate_limit: int — Maximum number of active certificates allowed.
  • certificate_remaining: int — Number of additional certificates that may still be issued.

Methods

CertificateLimitsResponse.enrollment (property)

enrollment: CertificateQuota
python

Return the enrollment quota as a structured value.

Returns

  • CertificateQuota — The enrollment limit and remaining count.

CertificateLimitsResponse.certificate (property)

certificate: CertificateQuota
python

Return the issued-certificate quota as a structured value.

Returns

  • CertificateQuota — The certificate limit and remaining count.

CertificateQuota

Import: from ksef2.models import CertificateQuota

class CertificateQuota(KSeFBaseModel)
python

Limit and remaining count for one certificate quota.

Attributes

  • limit: int — Maximum number allowed.
  • remaining: int — Number still available.

CertificatesInfoList

Import: from ksef2.models import CertificatesInfoList

class CertificatesInfoList(KSeFBaseModel)
python

One page of certificate query results.

Attributes

  • certificates: list[CertificateInfo] — Certificates on this page.
  • has_more: bool — Whether more results are available after this page.

ChallengeResponse

Import: from ksef2.models import ChallengeResponse

class ChallengeResponse(KSeFBaseModel)
python

Challenge material returned before token or XAdES authentication starts.

Attributes

  • challenge: str — Challenge string to include in the authentication request.
  • timestamp: datetime — Server time at which the challenge was issued.
  • timestamp_ms: int — Challenge issue time as Unix milliseconds.

CollectiveIdentifierInvoice

Import: from ksef2.models import CollectiveIdentifierInvoice

class CollectiveIdentifierInvoice(KSeFBaseModel)
python

Invoice included when generating a collective identifier.

Attributes

  • ksef_number: str — KSeF number of the invoice.
  • payment: CollectiveIdentifierInvoicePayment | None — Payment details; None when not provided.
  • description: str | None — Free-text description, up to 512 characters.

CollectiveIdentifierInvoiceDetails

Import: from ksef2.models import CollectiveIdentifierInvoiceDetails

class CollectiveIdentifierInvoiceDetails(KSeFBaseModel)
python

Invoice details returned for a collective identifier.

Attributes

  • ksef_number: str — KSeF number of the invoice.
  • payment: CollectiveIdentifierInvoicePayment | None — Payment details; None when not provided.
  • description: str | None — Free-text description, if any.
  • details_hidden: bool — Whether the payment and description are hidden because the invoice was added in another context.

CollectiveIdentifierInvoicePayment

Import: from ksef2.models import CollectiveIdentifierInvoicePayment

class CollectiveIdentifierInvoicePayment(KSeFBaseModel)
python

Payment details attached to one invoice in a collective identifier.

Attributes

  • amount: float — Payment amount.
  • currency: CurrencyCodes — Currency of the payment.

CollectiveIdentifierInvoicesPage

Import: from ksef2.models import CollectiveIdentifierInvoicesPage

class CollectiveIdentifierInvoicesPage(KSeFBaseModel)
python

One page of invoices belonging to a collective identifier.

Attributes

  • continuation_token: str | None — Opaque token for requesting the next page; None when there are no more pages.
  • invoices: list[CollectiveIdentifierInvoiceDetails] — Invoices on this page.

CollectiveIdentifierInvoicesQuery

Import: from ksef2.models import CollectiveIdentifierInvoicesQuery

class CollectiveIdentifierInvoicesQuery(KSeFBaseModel)
python

Collective identifiers to expand into their member invoices.

KSeF accepts at most 10 identifiers in one request.

Attributes

  • collective_identifier_numbers: list[str] — Collective identifier numbers to expand (1–10).

CollectiveIdentifierLimits

Import: from ksef2.models import CollectiveIdentifierLimits

class CollectiveIdentifierLimits(KSeFBaseModel)
python

Invoice count limit for one collective identifier.

Attributes

  • max_invoices: int — Maximum number of invoices in one collective identifier.

CollectiveIdentifierParams

Import: from ksef2.models import CollectiveIdentifierParams

class CollectiveIdentifierParams(KSeFBaseParams[CollectiveIdentifierQueryParams], PageSizeMixin)
python

Continuation-token pagination for collective identifier endpoints.

Attributes

  • page_size: int — Number of results per page (10–200).

CollectiveIdentifierReference

Import: from ksef2.models import CollectiveIdentifierReference

class CollectiveIdentifierReference(KSeFBaseModel)
python

Collective identifier associated with one KSeF invoice number.

Attributes

  • collective_identifier_number: str — Number of the collective identifier.
  • date_created: datetime — When the identifier was created.
  • created_in_current_context: bool — Whether it was created in the current context.

CollectiveIdentifierReferencesPage

Import: from ksef2.models import CollectiveIdentifierReferencesPage

class CollectiveIdentifierReferencesPage(KSeFBaseModel)
python

One page of collective identifiers associated with an invoice.

Attributes

  • continuation_token: str | None — Opaque token for requesting the next page; None when there are no more pages.
  • collective_identifiers: list[CollectiveIdentifierReference] — Collective identifiers on this page.

CollectiveIdentifiersPage

Import: from ksef2.models import CollectiveIdentifiersPage

class CollectiveIdentifiersPage(KSeFBaseModel)
python

One page of collective identifiers returned by a context query.

Attributes

  • continuation_token: str | None — Opaque token for requesting the next page; None when there are no more pages.
  • collective_identifiers: list[CollectiveIdentifierSummary] — Collective identifiers on this page.

CollectiveIdentifiersQuery

Import: from ksef2.models import CollectiveIdentifiersQuery

class CollectiveIdentifiersQuery(KSeFBaseModel)
python

Filters for collective identifiers visible in the current context.

Attributes

  • date_created_from: datetime — Start of the creation date range.
  • date_created_to: datetime — End of the creation date range.
  • collective_identifier_number: str | None — Match this collective identifier number.
  • invoice_count_from: int | None — Minimum number of invoices.
  • invoice_count_to: int | None — Maximum number of invoices.
  • created_in_current_context: bool | None — Match only identifiers created in the current context (True) or elsewhere (False).

CollectiveIdentifierSummary

Import: from ksef2.models import CollectiveIdentifierSummary

class CollectiveIdentifierSummary(KSeFBaseModel)
python

Collective identifier returned by a context query.

Attributes

  • collective_identifier_number: str — Number of the collective identifier.
  • date_created: datetime — When the identifier was created.
  • invoice_count: int — Number of invoices it groups.
  • created_in_current_context: bool — Whether it was created in the current context.

ContextLimits

Import: from ksef2.models import ContextLimits

class ContextLimits(KSeFBaseModel)
python

Limits applied to sessions and collective identifiers.

Attributes

  • online_session: SessionLimits — Limits for online sessions.
  • batch_session: SessionLimits — Limits for batch sessions.
  • collective_identifier: CollectiveIdentifierLimits — Limits for collective identifiers.

CreatePersonRequest

Import: from ksef2.models import CreatePersonRequest

class CreatePersonRequest(KSeFBaseModel)
python

Payload used to create a test person within a subject.

Attributes

  • 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: AwareDatetime | None — Creation date to record for the person; None for now.

CreateSubjectRequest

Import: from ksef2.models import CreateSubjectRequest

class CreateSubjectRequest(KSeFBaseModel)
python

Payload used to create a test subject.

Attributes

  • subject_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; None for none.
  • created_date: AwareDatetime | None — Creation date to record for the subject; None for now.

DeletePersonRequest

Import: from ksef2.models import DeletePersonRequest

class DeletePersonRequest(KSeFBaseModel)
python

Payload used to delete a TEST person.

Attributes

  • nip: str — NIP of the person to delete.

DeleteSubjectRequest

Import: from ksef2.models import DeleteSubjectRequest

class DeleteSubjectRequest(KSeFBaseModel)
python

Payload used to delete a TEST subject.

Attributes

  • subject_nip: str — NIP of the subject to delete.

EnableAttachmentsRequest

Import: from ksef2.models import EnableAttachmentsRequest

class EnableAttachmentsRequest(KSeFBaseModel)
python

Payload used to enable attachments for a TEST subject.

Attributes

  • nip: str — NIP of the subject to enable attachments for.

EntityPermission

Import: from ksef2.models import EntityPermission

class EntityPermission(KSeFBaseModel)
python

Entity permission scope together with delegation capability.

Attributes

  • type: EntityPermissionType — Permission scope granted to the entity.
  • can_delegate: bool — Whether the holder may delegate this permission further.

EntityPermissionDetail

Import: from ksef2.models import EntityPermissionDetail

class EntityPermissionDetail(KSeFBaseModel)
python

Permission record returned from entity permission queries.

Attributes

  • id: Annotated[str, Field(max_length=36, min_length=36)] — Permission identifier (36-character UUID), usable for revocation.
  • context_type: EntityPermissionsContextIdentifierType — Kind of identifier in context_value.
  • context_value: str — Identifier of the context in which the permission applies.
  • permission_type: EntityPermissionType — Permission scope.
  • description: str — Reason recorded when the permission was granted.
  • start_date: datetime — When the permission became effective.
  • can_delegate: bool — Whether the holder may delegate this permission further.

EntityPermissionsQuery

Import: from ksef2.models import EntityPermissionsQuery

class EntityPermissionsQuery(KSeFBaseModel)
python

Filters for querying entity permission grants in the current context.

Attributes

  • context_type: EntityPermissionsContextIdentifierType | None — Restrict results to this kind of context identifier; None for no restriction.
  • context_value: str | None — Restrict results to this context identifier; None for no restriction.

EntityPermissionsQueryResponse

Import: from ksef2.models import EntityPermissionsQueryResponse

class EntityPermissionsQueryResponse(KSeFBaseModel)
python

One page of entity permission query results.

Attributes

  • permissions: list[EntityPermissionDetail] — Permission records on this page.
  • has_more: bool — Whether more results are available after this page.

EntityRole

Import: from ksef2.models import EntityRole

class EntityRole(KSeFBaseModel)
python

Role assigned to the authenticated entity, optionally within a parent entity.

Attributes

  • role: EntityRoleType — Role assigned to the entity.
  • description: str — Human-readable description of the role.
  • start_date: datetime — When the role became effective.
  • parent_entity_id_type: EntityIdentifierType | None — Kind of identifier of the parent entity; None when the role has no parent.
  • parent_entity_id_value: str | None — Identifier of the parent entity; None when the role has no parent.

EntityRolesResponse

Import: from ksef2.models import EntityRolesResponse

class EntityRolesResponse(KSeFBaseModel)
python

One page of entity roles.

Attributes

  • roles: list[EntityRole] — Roles on this page.
  • has_more: bool — Whether more results are available after this page.

EuEntityPermission

Import: from ksef2.models import EuEntityPermission

class EuEntityPermission(KSeFBaseModel)
python

Permission record returned from EU-entity permission queries.

Attributes

  • id: Annotated[str, Field(max_length=36, min_length=36)] — Permission identifier (36-character UUID).
  • author_type: CertificateSubjectIdentifierType — Kind of identifier in author_value.
  • author_value: str — Identifier of the author who granted the permission.
  • vat_ue_identifier: str — NIP-VAT UE identifier of the EU entity.
  • eu_entity_name: str — Full name of the EU entity.
  • authorized_fingerprint_identifier: str — Fingerprint of the certificate holding the permission.
  • permission_type: EuEntityQueryPermissionType — Permission scope.
  • description: str — Reason recorded when the permission was granted.
  • subject_first_name: str | None — First name of the person holding the permission, if known.
  • subject_last_name: str | None — Last name of the person holding the permission, if known.
  • entity_full_name: str | None — Full name of the entity the permission belongs to, if known.
  • entity_address: str | None — Address of the entity the permission belongs to, if known.
  • start_date: datetime — When the permission became effective.

EuEntityPermissionsQuery

Import: from ksef2.models import EuEntityPermissionsQuery

class EuEntityPermissionsQuery(KSeFBaseModel)
python

Filters for querying EU-entity permissions.

Attributes

  • vat_ue_identifier: str | None — Restrict results to this NIP-VAT UE identifier.
  • authorized_fingerprint_identifier: str | None — Restrict results to permissions held by the certificate with this fingerprint.
  • permission_types: list[EuEntityQueryPermissionType] | None — Restrict results to these permission scopes; None for all.

EuEntityPermissionsQueryResponse

Import: from ksef2.models import EuEntityPermissionsQueryResponse

class EuEntityPermissionsQueryResponse(KSeFBaseModel)
python

One page of EU-entity permission query results.

Attributes

  • permissions: list[EuEntityPermission] — Permission records on this page.
  • has_more: bool — Whether more results are available after this page.

ExportHandle

Import: from ksef2.models import ExportHandle

class ExportHandle(KSeFBaseModel)
python

Holds export reference + crypto keys needed to later fetch/decrypt the package.

Attributes

  • model_config
  • reference_number: str — KSeF reference number of the export operation.
  • aes_key: bytes — AES-256 key used to decrypt the exported package. Excluded from serialization and repr.
  • iv: bytes — Initialization vector used to decrypt the exported package. Excluded from serialization and repr.

Methods

ExportHandle.to_sensitive_dict

def to_sensitive_dict() -> dict[str, str | bytes]
python

Export the key material only for deliberate protected handling.

Returns

  • dict[str, str | bytes] — A dictionary with the reference number, AES key and initialization vector.

ExportInvoicesPayload

Import: from ksef2.models import ExportInvoicesPayload

class ExportInvoicesPayload(KSeFBaseModel)
python

Payload used to schedule an encrypted invoice export.

Attributes

  • filter: InvoicesFilter — Filter selecting the invoices to export.
  • encrypted_symmetric_key: str — AES key encrypted with the KSeF public key, Base64-encoded.
  • initialization_vector: str — AES initialization vector, Base64-encoded.
  • public_key_id: str | None — Identifier of the KSeF public key used for encryption; None to use the default.
  • only_metadata: bool — Export only invoice metadata instead of full invoice XML.
  • compression_type: CompressionType | None — Compression applied to the package; None for the server default.

ExportInvoicesResponse

Import: from ksef2.models import ExportInvoicesResponse

class ExportInvoicesResponse(KSeFBaseModel)
python

Reference returned after scheduling an invoice export.

Attributes

  • reference_number: str — KSeF reference number of the scheduled export operation.

ExportResumeState

Import: from ksef2.models import ExportResumeState

class ExportResumeState(KSeFPersistedModel)
python

Serializable state needed to resume an invoice export after a restart.

ExportJob.resume_state() returns it and auth.invoices.export(state=...) turns it back into an ExportJob. It holds the AES key and IV that decrypt the package, so treat to_json() and to_dict() output as credential material. model_dump() and repr() redact the secrets and are not a persistence format.

Attributes

  • format_version: Literal[1] — Version of the serialized state format; currently always 1.
  • reference_number: str — KSeF reference number of the export operation.
  • aes_key: SecretStr — AES-256 key that decrypts the package, Base64 encoded.
  • iv: SecretStr — Initialization vector that decrypts the package, Base64 encoded.

Methods

ExportResumeState.from_handle

@classmethod
def from_handle(handle: ExportHandle) -> Self
python

Create state from an export handle.

Parameters

  • handle (ExportHandle) — Handle returned when the export was scheduled.

Returns

  • Self — State holding the reference number and the Base64-encoded key material.

ExportResumeState.to_handle

def to_handle() -> ExportHandle
python

Rebuild the export handle with raw key material.

Returns

  • ExportHandle — A handle with the reference number and the decoded AES key and IV.

ExportResumeState.to_dict

def to_dict(*, mode: Literal['json', 'python'] | str = 'json') -> dict[str, object]
python

Export the state with the secrets included.

Parameters

  • mode (Literal['json', 'python'] | str) — Pydantic dump mode, "json" for JSON-safe values or "python" for native types.

Returns

  • dict[str, object] — A dictionary with the full state, including the AES key and IV.

ExportResumeState.to_json

def to_json(*, indent: int | None = None) -> str
python

Export the state as JSON with the secrets included.

Parameters

  • indent (int | None) — Number of spaces to indent nested values; None for compact output.

Returns

  • str — JSON text with the full state, including the AES key and IV.

ExportResumeState.from_dict

@classmethod
def from_dict(state: Mapping[str, object]) -> Self
python

Restore the state from a dictionary exported by to_dict().

Parameters

  • state (Mapping[str, object]) — Mapping produced by to_dict().

Returns

  • Self — The restored state.

ExportResumeState.from_json

@classmethod
def from_json(state: str | bytes | bytearray) -> Self
python

Restore the state from JSON exported by to_json().

Parameters

  • state (str | bytes | bytearray) — JSON text produced by to_json().

Returns

  • Self — The restored state.

ExportStatusInfo

Import: from ksef2.models import ExportStatusInfo

class ExportStatusInfo(KSeFBaseModel)
python

Status code and description for an invoice export operation.

Attributes

  • code: int — Numeric status code of the export operation.
  • description: str — Human-readable description of the status.
  • details: list[str] | None — Additional status details, if any.

GenerateCollectiveIdentifierResponse

Import: from ksef2.models import GenerateCollectiveIdentifierResponse

class GenerateCollectiveIdentifierResponse(KSeFBaseModel)
python

Identifier returned after grouping invoices.

Attributes

  • collective_identifier_number: str — Number of the generated collective identifier.

GenerateTokenResponse

Import: from ksef2.models import GenerateTokenResponse

class GenerateTokenResponse(KSeFBaseModel)
python

Token value returned after a successful generate operation.

Attributes

  • reference_number: str — KSeF reference number of the operation or resource.
  • token: str — KSeF token value. Returned only once, so store it securely. Excluded from serialization and repr.

Methods

GenerateTokenResponse.to_sensitive_dict

def to_sensitive_dict() -> dict[str, str]
python

Export the one-time token for deliberately protected persistence.

Returns

  • dict[str, str] — A dictionary with the reference number and the plain token.

GrantAuthorizationPermissionsRequest

Import: from ksef2.models import GrantAuthorizationPermissionsRequest

class GrantAuthorizationPermissionsRequest(KSeFBaseModel)
python

Payload for granting invoice authorization rights to an entity.

Attributes

  • subject_type: AuthorizationSubjectIdentifierType — Kind of identifier in subject_value (nip or peppol_id).
  • subject_value: str — Identifier of the entity being authorized (NIP or Peppol ID).
  • permission: AuthorizationPermissionType — Authorization scope to grant, for example self_invoicing.
  • description: str — Free-text reason for the grant, stored by KSeF with the permission.
  • entity_name: str — Full name of the entity being authorized.

GrantEntityPermissionsRequest

Import: from ksef2.models import GrantEntityPermissionsRequest

class GrantEntityPermissionsRequest(KSeFBaseModel)
python

Payload for granting permissions to an entity.

Attributes

  • 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, stored by KSeF with the permission.
  • entity_name: str — Full name of the entity receiving the permissions.

GrantEuEntityAdministrationRequest

Import: from ksef2.models import GrantEuEntityAdministrationRequest

class GrantEuEntityAdministrationRequest(KSeFBaseModel)
python

Payload for granting EU-entity administration rights in a VAT UE context.

Attributes

  • subject_value: str — Fingerprint of the certificate of the person receiving administration rights.
  • context_type: EuEntityAdminContextIdentifierType — Kind of identifier in context_value; always nip_vat_ue.
  • context_value: str — NIP-VAT UE identifier of the EU entity the rights apply to.
  • description: str — Free-text reason for the grant, stored by KSeF with the permission.
  • eu_entity_name: str — Full name of the EU entity.

GrantEuEntityPermissionsRequest

Import: from ksef2.models import GrantEuEntityPermissionsRequest

class GrantEuEntityPermissionsRequest(KSeFBaseModel)
python

Payload for granting permissions to an EU entity.

Attributes

  • 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, stored by KSeF with the permission.

GrantIndirectPermissionsRequest

Import: from ksef2.models import GrantIndirectPermissionsRequest

class GrantIndirectPermissionsRequest(KSeFBaseModel)
python

Payload for granting indirect permissions, optionally scoped to a target.

Attributes

  • subject_type: CertificateSubjectIdentifierType — Kind of identifier in subject_value (nip, pesel or fingerprint).
  • 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, stored by KSeF with the permission.
  • 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 in target_value; None or all_partners scopes the grant to every partner.
  • target_value: str | None — Identifier of the partner context the grant is limited to; None when the target is all partners.

GrantPermissionsRequest

Import: from ksef2.models import GrantPermissionsRequest

class GrantPermissionsRequest(KSeFBaseModel)
python

Payload used to grant test permissions in a chosen context.

Attributes

  • 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.

GrantPermissionsResponse

Import: from ksef2.models import GrantPermissionsResponse

class GrantPermissionsResponse(KSeFBaseModel)
python

Reference returned after starting a permission grant or revoke operation.

Attributes

  • reference_number: str — KSeF reference number of the operation or resource.

GrantPersonPermissionsRequest

Import: from ksef2.models import GrantPersonPermissionsRequest

class GrantPersonPermissionsRequest(KSeFBaseModel)
python

Payload for granting permissions directly to a person.

Attributes

  • subject_type: CertificateSubjectIdentifierType — Kind of identifier in subject_value (nip, pesel or fingerprint).
  • subject_value: str — Identifier of the person receiving the permissions (NIP, PESEL or certificate fingerprint).
  • permissions: list[PersonPermissionScope] — Permission scopes to grant; at least one is required.
  • description: str — Free-text reason for the grant, stored by KSeF with the permission.
  • first_name: str — First name of the person receiving the permissions.
  • last_name: str — Last name of the person receiving the permissions.

GrantSubunitPermissionsRequest

Import: from ksef2.models import GrantSubunitPermissionsRequest

class GrantSubunitPermissionsRequest(KSeFBaseModel)
python

Payload for granting permissions in a subunit context.

Attributes

  • subject_type: CertificateSubjectIdentifierType — Kind of identifier in subject_value (nip, pesel or fingerprint).
  • subject_value: str — Identifier of the person receiving the permissions.
  • context_type: SubunitIdentifierType — Kind of identifier in context_value (nip or internal_id).
  • context_value: str — Identifier of the subunit context the permissions apply to.
  • description: str — Free-text reason for the grant, stored by KSeF with the permission.
  • 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.

Identifier

Import: from ksef2.models import Identifier

class Identifier(KSeFBaseModel)
python

Generic subject identifier used in testdata operations.

Attributes

  • type: IdentifierType — Kind of identifier in value.
  • value: str — Identifier value.

InitTokenAuthenticationRequest

Import: from ksef2.models import InitTokenAuthenticationRequest

class InitTokenAuthenticationRequest(KSeFBaseModel)
python

Payload used to authenticate with a previously generated KSeF token.

Attributes

  • challenge: str — Challenge obtained from KSeF before authenticating.
  • context_type: ContextIdentifierType — Kind of identifier in context_value.
  • context_value: str — Identifier of the context to authenticate in, such as a NIP.
  • encrypted_token: str — KSeF token and challenge timestamp, encrypted with the KSeF public key and Base64-encoded.
  • public_key_id: str | None — Identifier of the KSeF public key used for encryption; None for the default.

InvoiceExportStatusResponse

Import: from ksef2.models import InvoiceExportStatusResponse

class InvoiceExportStatusResponse(KSeFBaseModel)
python

Status response for a scheduled invoice export.

Attributes

  • status: ExportStatusInfo — Status of the export operation.
  • completed_date: datetime | None — When the export finished; None while it is running.
  • package_expiration_date: datetime | None — When the package stops being downloadable; None until the export is ready.
  • package: InvoicePackage | None — Package metadata once the export is ready; None before that.

InvoiceMetadata

Import: from ksef2.models import InvoiceMetadata

class InvoiceMetadata(KSeFBaseModel)
python

Metadata describing an invoice visible to the authenticated subject.

Attributes

  • ksef_number: str — KSeF number assigned to the invoice.
  • invoice_number: str — Seller's invoice number.
  • issue_date: date — Issue date stated on the invoice.
  • invoicing_date: datetime — When the invoice was submitted to KSeF.
  • acquisition_date: datetime — When KSeF accepted the invoice and assigned its KSeF number.
  • permanent_storage_date: datetime — When the invoice was moved to permanent storage.
  • seller: InvoiceMetadataSeller — Seller of the invoice.
  • buyer: InvoiceMetadataBuyer — Buyer of the invoice.
  • net_amount: float — Total net amount.
  • gross_amount: float — Total gross amount.
  • vat_amount: float — Total VAT amount.
  • currency: str — ISO 4217 currency code of the invoice.
  • invoicing_mode: InvoicingMode — Whether the invoice was issued online or offline.
  • invoice_type: InvoiceType — KSeF invoice type, such as a standard invoice or a correction.
  • form_code_system: str — System code of the invoice schema, for example FA (3).
  • form_code_version: str — Schema version of the invoice, for example 1-0E.
  • form_code_value: str — Form value of the invoice schema, for example FA.
  • is_self_invoicing: bool — Whether the invoice was issued by the buyer on the seller's behalf (self-invoicing).
  • has_attachment: bool — Whether the invoice carries an attachment.
  • invoice_hash: str — SHA-256 hash of the invoice XML, Base64-encoded.
  • hash_of_corrected_invoice: str | None — Hash of the invoice corrected by this one; None for non-corrections.
  • third_subjects: list[InvoiceMetadataThirdSubject] | None — Third subjects named on the invoice, if any.
  • authorized_subject: InvoiceMetadataAuthorizedSubject | None — Authorized subject named on the invoice, if any.

InvoiceMetadataAuthorizedSubject

Import: from ksef2.models import InvoiceMetadataAuthorizedSubject

class InvoiceMetadataAuthorizedSubject(KSeFBaseModel)
python

Authorized subject data returned with invoice metadata.

Attributes

  • nip: str — NIP of the authorized subject.
  • name: str | None — Name of the authorized subject, if present on the invoice.
  • role: int — Numeric role code of the authorized subject on the invoice.

InvoiceMetadataBuyer

Import: from ksef2.models import InvoiceMetadataBuyer

class InvoiceMetadataBuyer(KSeFBaseModel)
python

Buyer data returned with invoice metadata.

Attributes

  • identifier: InvoiceMetadataBuyerIdentifier — Identifier of the buyer.
  • name: str | None — Name of the buyer, if present on the invoice.

InvoiceMetadataBuyerIdentifier

Import: from ksef2.models import InvoiceMetadataBuyerIdentifier

class InvoiceMetadataBuyerIdentifier(KSeFBaseModel)
python

Buyer identifier returned with invoice metadata.

Attributes

  • type: BuyerIdentifierType — Kind of buyer identifier, such as nip, vat_ue, other or none.
  • value: str | None — Buyer identifier value; None when the buyer has no identifier.

InvoiceMetadataParams

Import: from ksef2.models import InvoiceMetadataParams

class InvoiceMetadataParams(KSeFBaseParams[InvoiceMetadataQueryParams], PageSizeMixin, PageOffsetMixin, SortOrderMixin)
python

Pagination parameters for invoice metadata queries.

Attributes

  • page_size: int — Number of results per page (10–250).

Methods

InvoiceMetadataParams.with_page_offset

def with_page_offset(page_offset: int) -> Self
python

Return a copy with an explicit page offset.

Parameters

  • page_offset (int) — Zero-based index of the page to return.

Returns

  • Self — A copy of these parameters with page_offset replaced.

InvoiceMetadataParams.next_page

def next_page() -> Self
python

Return a copy advanced by one invoice metadata page.

Returns

  • Self — A copy advanced by one invoice metadata page.

InvoiceMetadataSeller

Import: from ksef2.models import InvoiceMetadataSeller

class InvoiceMetadataSeller(KSeFBaseModel)
python

Seller data returned with invoice metadata.

Attributes

  • nip: str — NIP of the seller.
  • name: str | None — Name of the seller, if present on the invoice.

InvoiceMetadataThirdSubject

Import: from ksef2.models import InvoiceMetadataThirdSubject

class InvoiceMetadataThirdSubject(KSeFBaseModel)
python

Third subject data returned with invoice metadata.

Attributes

  • identifier: InvoiceMetadataThirdSubjectIdentifier — Identifier of the third subject.
  • name: str | None — Name of the third subject, if present on the invoice.
  • role: int — Numeric role code of the third subject on the invoice.

InvoiceMetadataThirdSubjectIdentifier

Import: from ksef2.models import InvoiceMetadataThirdSubjectIdentifier

class InvoiceMetadataThirdSubjectIdentifier(KSeFBaseModel)
python

Third-subject identifier returned with invoice metadata.

Attributes

  • type: ThirdSubjectIdentifierType — Kind of third-subject identifier.
  • value: str | None — Third-subject identifier value; None when absent.

InvoicePackage

Import: from ksef2.models import InvoicePackage

class InvoicePackage(KSeFBaseModel)
python

Package metadata returned when an invoice export is ready.

Attributes

  • invoice_count: int — Number of invoices in the package.
  • size: int — Total size of the package in bytes.
  • parts: list[PackagePart] — Package parts to download and concatenate.
  • is_truncated: bool — Whether the export hit the server-side limit and more invoices match the filter.
  • last_issue_date: date | None — Issue date of the last invoice in the package, for continuing a truncated export.
  • last_invoicing_date: datetime | None — Invoicing date of the last invoice in the package, for continuing a truncated export.
  • last_permanent_storage_date: datetime | None — Permanent-storage date of the last invoice in the package, for continuing a truncated export.
  • permanent_storage_hwm_date: datetime | None — High-water mark of permanent storage covered by the package.

InvoicesFilter

Import: from ksef2.models import InvoicesFilter

class InvoicesFilter(KSeFBaseModel)
python

Filters accepted by invoice metadata query and export operations.

Datetimes are stored as UTC-aware values. Inputs with an explicit offset keep their instant. Naive inputs are interpreted as Europe/Warsaw local time; ambiguous or nonexistent daylight-saving times require an explicit offset.

Attributes

  • role: Literal['buyer', 'seller', 'third_subject', 'authorized_subject'] — Role of the authenticated subject on the invoices to match.
  • date_type: Literal['issue_date', 'invoicing_date', 'permanent_storage'] — Which date date_from and date_to apply to: issue date, invoicing date or permanent-storage date.
  • date_from: datetime — Start of the date range (inclusive). Naive values are read as Europe/Warsaw local time.
  • date_to: datetime — End of the date range. Defaults to the current UTC time.
  • restrict_to_permanent_storage_hwm_date: bool | None — Limit results to the permanent-storage high-water mark so repeated queries stay consistent.
  • currency_codes: list[CurrencyCodes] | None — Match invoices in any of these currencies.
  • amount_type: Literal['brutto', 'netto', 'vat'] | None — Which amount amount_min and amount_max apply to: gross (brutto), net (netto) or vat.
  • amount_min: float | None — Minimum amount, in the currency of the invoice.
  • amount_max: float | None — Maximum amount, in the currency of the invoice.
  • seller_nip: str | None — Match invoices from this seller NIP.
  • buyer_nip: str | None — Match invoices to this buyer NIP.
  • buyer_vat_ue: str | None — Match invoices to this buyer EU VAT identifier.
  • buyer_other_id: str | None — Match invoices to this buyer identifier of another kind.
  • invoice_number: str | None — Match this seller invoice number.
  • ksef_number: str | None — Match this KSeF number.
  • invoice_schema: FormSchema | None — Match invoices issued in this schema.
  • invoice_types: list[KsefInvoiceTypes] | None — Match any of these invoice types.
  • has_attachment: bool | None — Match only invoices with (True) or without (False) an attachment.
  • invoicing_mode: InvoicingMode | None — Match only online or offline invoices.
  • is_self_invoicing: bool | None — Match only self-invoiced invoices (True) or exclude them (False).

Methods

InvoicesFilter.for_buyer

@classmethod
def for_buyer(
    *,
    date_from: datetime | str,
    date_to: datetime | str | None = None,
    date_type: Literal['issue_date', 'invoicing_date', 'permanent_storage'] = 'issue_date',
    restrict_to_permanent_storage_hwm_date: bool | None = None,
    currency_codes: list[CurrencyCodes] | None = None,
    amount_type: Literal['brutto', 'netto', 'vat'] | None = None,
    amount_min: float | None = None,
    amount_max: float | None = None,
    seller_nip: str | None = None,
    buyer_nip: str | None = None,
    buyer_vat_ue: str | None = None,
    buyer_other_id: str | None = None,
    invoice_number: str | None = None,
    ksef_number: str | None = None,
    invoice_schema: FormSchema | None = None,
    invoice_types: list[KsefInvoiceTypes] | None = None,
    has_attachment: bool | None = None,
    invoicing_mode: InvoicingMode | None = None,
    is_self_invoicing: bool | None = None,
) -> Self
python

Build a filter for invoices where the authenticated subject is the buyer.

Parameters

  • date_from (datetime | str) — Start of the date range. Naive values are read as Europe/Warsaw local time.
  • date_to (datetime | str | None) — End of the date range; defaults to the current UTC time.
  • date_type (Literal['issue_date', 'invoicing_date', 'permanent_storage']) — Which date the range applies to: issue date, invoicing date or permanent-storage date.
  • restrict_to_permanent_storage_hwm_date (bool | None) — Limit results to the permanent-storage high-water mark so repeated queries stay consistent.
  • currency_codes (list[CurrencyCodes] | None) — Match invoices in any of these currencies.
  • amount_type (Literal['brutto', 'netto', 'vat'] | None) — Which amount amount_min and amount_max apply to: gross (brutto), net (netto) or vat.
  • amount_min (float | None) — Minimum amount.
  • amount_max (float | None) — Maximum amount.
  • seller_nip (str | None) — Match invoices from this seller NIP.
  • buyer_nip (str | None) — Match invoices to this buyer NIP.
  • buyer_vat_ue (str | None) — Match invoices to this buyer EU VAT identifier.
  • buyer_other_id (str | None) — Match invoices to this buyer identifier of another kind.
  • invoice_number (str | None) — Match this seller invoice number.
  • ksef_number (str | None) — Match this KSeF number.
  • invoice_schema (FormSchema | None) — Match invoices issued in this schema.
  • invoice_types (list[KsefInvoiceTypes] | None) — Match any of these invoice types.
  • has_attachment (bool | None) — Match only invoices with or without an attachment.
  • invoicing_mode (InvoicingMode | None) — Match only online or offline invoices.
  • is_self_invoicing (bool | None) — Match only self-invoiced invoices, or exclude them.

Returns

  • Self — A filter with role="buyer".

Example

from ksef2.models import InvoicesFilter

filters = InvoicesFilter.for_buyer(date_from="2026-01-01T00:00:00+01:00")
python

InvoicesFilter.for_seller

@classmethod
def for_seller(
    *,
    date_from: datetime | str,
    date_to: datetime | str | None = None,
    date_type: Literal['issue_date', 'invoicing_date', 'permanent_storage'] = 'issue_date',
    restrict_to_permanent_storage_hwm_date: bool | None = None,
    currency_codes: list[CurrencyCodes] | None = None,
    amount_type: Literal['brutto', 'netto', 'vat'] | None = None,
    amount_min: float | None = None,
    amount_max: float | None = None,
    seller_nip: str | None = None,
    buyer_nip: str | None = None,
    buyer_vat_ue: str | None = None,
    buyer_other_id: str | None = None,
    invoice_number: str | None = None,
    ksef_number: str | None = None,
    invoice_schema: FormSchema | None = None,
    invoice_types: list[KsefInvoiceTypes] | None = None,
    has_attachment: bool | None = None,
    invoicing_mode: InvoicingMode | None = None,
    is_self_invoicing: bool | None = None,
) -> Self
python

Build a filter for invoices where the authenticated subject is the seller.

Parameters

  • date_from (datetime | str) — Start of the date range. Naive values are read as Europe/Warsaw local time.
  • date_to (datetime | str | None) — End of the date range; defaults to the current UTC time.
  • date_type (Literal['issue_date', 'invoicing_date', 'permanent_storage']) — Which date the range applies to: issue date, invoicing date or permanent-storage date.
  • restrict_to_permanent_storage_hwm_date (bool | None) — Limit results to the permanent-storage high-water mark so repeated queries stay consistent.
  • currency_codes (list[CurrencyCodes] | None) — Match invoices in any of these currencies.
  • amount_type (Literal['brutto', 'netto', 'vat'] | None) — Which amount amount_min and amount_max apply to: gross (brutto), net (netto) or vat.
  • amount_min (float | None) — Minimum amount.
  • amount_max (float | None) — Maximum amount.
  • seller_nip (str | None) — Match invoices from this seller NIP.
  • buyer_nip (str | None) — Match invoices to this buyer NIP.
  • buyer_vat_ue (str | None) — Match invoices to this buyer EU VAT identifier.
  • buyer_other_id (str | None) — Match invoices to this buyer identifier of another kind.
  • invoice_number (str | None) — Match this seller invoice number.
  • ksef_number (str | None) — Match this KSeF number.
  • invoice_schema (FormSchema | None) — Match invoices issued in this schema.
  • invoice_types (list[KsefInvoiceTypes] | None) — Match any of these invoice types.
  • has_attachment (bool | None) — Match only invoices with or without an attachment.
  • invoicing_mode (InvoicingMode | None) — Match only online or offline invoices.
  • is_self_invoicing (bool | None) — Match only self-invoiced invoices, or exclude them.

Returns

  • Self — A filter with role="seller".

Example

from ksef2.models import InvoicesFilter

filters = InvoicesFilter.for_seller(date_from="2026-01-01T00:00:00+01:00")
python

InvoiceStatusInfo

Import: from ksef2.models import InvoiceStatusInfo

class InvoiceStatusInfo(KSeFBaseModel)
python

Invoice processing status returned within session APIs.

Attributes

  • code: int — Numeric invoice processing status code; 200 means accepted.
  • description: str — Human-readable description of the status.
  • details: list[str] | None — Additional status details, for example validation errors.
  • extensions: dict[str, str | None] | None — Extra key/value data attached to the status, if any.

KSeFBaseModel

Import: from ksef2.models import KSeFBaseModel

class KSeFBaseModel(BaseModel)
python

Base model that ignores undeclared fields and logs warnings about them.

Attributes

  • model_config

KSeFBaseParams

Import: from ksef2.models import KSeFBaseParams

class KSeFBaseParams(KSeFBaseModel)
python

Base model for query-parameter objects serialized with camelCase aliases.

Attributes

  • model_config

Methods

KSeFBaseParams.to_query_params

def to_query_params() -> ParamsT
python

Serialize the model into a JSON-safe query-parameter mapping.

Returns

  • ParamsT — Query parameters keyed by their API names, with unset values omitted.

ListPeppolProvidersResponse

Import: from ksef2.models import ListPeppolProvidersResponse

class ListPeppolProvidersResponse(KSeFBaseModel)
python

Response from querying Peppol service providers.

Attributes

  • providers: list[PeppolProvider] — List of Peppol service providers.
  • has_more: bool — Flag indicating if more results are available on the next page.

ListSessionsQuery

Import: from ksef2.models import ListSessionsQuery

class ListSessionsQuery(SessionFiltersMixin, KSeFBaseParams[ListSessionsQueryParams], PageSizeMixin)
python

Query parameters for authentication or invoice session listings.

Attributes

  • session_type: SessionType — Kind of sessions to list: online or batch.
  • reference_number: str | None — Match this session reference number.
  • date_created_from: datetime | None — Match sessions created at or after this time.
  • date_created_to: datetime | None — Match sessions created at or before this time.
  • date_closed_from: datetime | None — Match sessions closed at or after this time.
  • date_closed_to: datetime | None — Match sessions closed at or before this time.
  • date_modified_from: datetime | None — Match sessions modified at or after this time.
  • date_modified_to: datetime | None — Match sessions modified at or before this time.
  • statuses: list[SessionStatus] | None — Match sessions in any of these statuses.

ListSessionsResponse

Import: from ksef2.models import ListSessionsResponse

class ListSessionsResponse(KSeFBaseModel)
python

One page of session summaries.

Attributes

  • continuation_token: str | None — Opaque token for requesting the next page; None when there are no more pages.
  • sessions: list[SessionSummary] — Session summaries on this page.

OffsetPaginationParams

Import: from ksef2.models import OffsetPaginationParams

class OffsetPaginationParams(KSeFBaseParams[OffsetPaginationQueryParams], PageSizeMixin, PageOffsetMixin)
python

Offset-based pagination parameters.

Methods

OffsetPaginationParams.next_page

def next_page() -> Self
python

Return a copy advanced by one page offset.

Returns

  • Self — A copy advanced by one page offset.

OnlineSessionResumeState

Import: from ksef2.models import OnlineSessionResumeState

class OnlineSessionResumeState(BaseSessionResumeState)
python

Serializable resume state of an online session.

This class holds all information needed to resume an online session. Use to_json() when intentionally exporting resumable JSON containing credentials.

Deprecated

The alias OnlineSessionState may be removed no earlier than ksef2 2.0.0; use OnlineSessionResumeState.

Attributes

  • valid_until: AwareDatetime — Expiration time of the session.

Methods

OnlineSessionResumeState.from_encoded

@classmethod
def from_encoded(
    reference_number: str,
    aes_key: bytes,
    iv: bytes,
    valid_until: datetime,
    form_code: FormSchema,
    *,
    access_token: str | None = None,
) -> Self
python

Create state from raw bytes (aes_key, iv).

Parameters

  • reference_number (str) — Session reference number.
  • aes_key (bytes) — Raw AES key bytes.
  • iv (bytes) — Raw initialization vector bytes.
  • valid_until (datetime) — Session expiration time.
  • form_code (FormSchema) — Invoice schema for this session.
  • access_token (str | None) — Deprecated and ignored. Persist authentication state separately with AuthenticationResumeState.

Returns

  • Self — OnlineSessionResumeState with Base64-encoded key and IV.

OpenBatchSessionRequest

Import: from ksef2.models import OpenBatchSessionRequest

class OpenBatchSessionRequest(KSeFBaseModel)
python

Request to open a batch session.

Attributes

  • encrypted_key: bytes — Session AES key encrypted with the KSeF public key.
  • iv: bytes — AES initialization vector used for the session.
  • public_key_id: str | None — Identifier of the KSeF public key used for encryption; None for the default.
  • batch_file: BatchFileInfo — Size, hash and part metadata of the batch file.
  • form_code: FormSchema — Invoice schema of the batch. Defaults to FA(3).
  • offline_mode: bool — Whether the invoices were issued in offline mode.

OpenBatchSessionResponse

Import: from ksef2.models import OpenBatchSessionResponse

class OpenBatchSessionResponse(KSeFBaseModel)
python

Response from opening a batch session.

Attributes

  • reference_number: str — Reference number of the batch session.
  • part_upload_requests: list[PartUploadRequest] — Upload instructions for each file part.

OpenOnlineSessionRequest

Import: from ksef2.models import OpenOnlineSessionRequest

class OpenOnlineSessionRequest(KSeFBaseModel)
python

Payload used to open an online invoice session.

Attributes

  • encrypted_key: bytes — Session AES key encrypted with the KSeF public key.
  • iv: bytes — AES initialization vector used for the session.
  • public_key_id: str | None — Identifier of the KSeF public key used for encryption; None for the default.
  • form_code: FormSchema — Invoice schema accepted by the session. Defaults to FA(3).

OpenOnlineSessionResponse

Import: from ksef2.models import OpenOnlineSessionResponse

class OpenOnlineSessionResponse(KSeFBaseModel)
python

Response returned after opening an online invoice session.

Attributes

  • reference_number: str — KSeF reference number of the opened session.
  • valid_until: AwareDatetime — When the session expires.

OperationStatus

Import: from ksef2.models import OperationStatus

class OperationStatus(KSeFBaseModel)
python

Operation status code and description returned by asynchronous permission APIs.

Attributes

  • code: OperationStatusCode — Numeric status code; 200 means the operation completed successfully, 100 that it is still in progress.
  • description: str — Human-readable description of the status.

PackagePart

Import: from ksef2.models import PackagePart

class PackagePart(KSeFBaseModel)
python

Download metadata for one encrypted package part.

Attributes

  • ordinal_number: int — One-based position of this part in the package.
  • part_name: str — File name of the part.
  • method: str — HTTP method to use when downloading the part.
  • url: str — Pre-signed download URL of the part. Excluded from serialization and repr.
  • part_size: int — Size of the part in bytes before encryption.
  • part_hash: str — SHA-256 hash of the part before encryption, Base64-encoded.
  • encrypted_part_size: int — Size of the encrypted part in bytes.
  • encrypted_part_hash: str — SHA-256 hash of the encrypted part, Base64-encoded.
  • expiration_date: datetime — When the download URL expires.

Methods

PackagePart.to_sensitive_dict

def to_sensitive_dict(
    *,
    mode: Literal['json', 'python'] | str = 'json',
) -> dict[str, object]
python

Export package metadata with its presigned capability URL.

Parameters

  • mode (Literal['json', 'python'] | str) — Pydantic dump mode, "json" for JSON-safe values or "python" for native types.

Returns

  • dict[str, object] — A dictionary including the plain download URL.

PartUploadRequest

Import: from ksef2.models import PartUploadRequest

class PartUploadRequest(KSeFBaseModel)
python

Upload endpoint information for a batch session part.

Attributes

  • ordinal_number: int — Sequential number of the file part (1-indexed).
  • method: str — HTTP method to use for uploading (typically PUT).
  • url: str — URL to upload the file part to.
  • headers: dict[str, str | None] — Headers to include in the upload request.

Methods

PartUploadRequest.to_sensitive_dict

def to_sensitive_dict(
    *,
    mode: Literal['json', 'python'] | str = 'json',
) -> dict[str, object]
python

Export upload instructions with the presigned capability URL.

Parameters

  • mode (Literal['json', 'python'] | str) — Pydantic dump mode, "json" for JSON-safe values or "python" for native types.

Returns

  • dict[str, object] — A dictionary including the plain upload URL.

PeppolProvider

Import: from ksef2.models import PeppolProvider

class PeppolProvider(KSeFBaseModel)
python

A Peppol service provider registered in the KSeF system.

Attributes

  • id: str — Provider ID in format P[A-Z]{2}[0-9]{6}, e.g. 'PPL123456'.
  • name: str | None — Name of the Peppol service provider.
  • date_created: datetime — Date when the provider was registered in the system.

Permission

Import: from ksef2.models import Permission

class Permission(KSeFBaseModel)
python

Permission granted through the testdata helper endpoints.

Attributes

  • type: PermissionType — Permission scope.
  • description: str — Description stored with the permission.

PermissionOperationStatusResponse

Import: from ksef2.models import PermissionOperationStatusResponse

class PermissionOperationStatusResponse(KSeFBaseModel)
python

Status wrapper for a permission grant or revoke operation.

Attributes

  • status: OperationStatus — Current status of the operation.

PersonalPermissionDetail

Import: from ksef2.models import PersonalPermissionDetail

class PersonalPermissionDetail(KSeFBaseModel)
python

Permission record returned from personal permission queries.

Attributes

  • id: Annotated[str, Field(max_length=36, min_length=36)] — Permission identifier (36-character UUID).
  • context_type: PersonalPermissionsContextIdentifierType | None — Kind of identifier in context_value.
  • context_value: str | None — Identifier of the context in which the permission applies.
  • authorized_type: PersonalPermissionsAuthorizedIdentifierType | None — Kind of identifier in authorized_value.
  • authorized_value: str | None — Identifier of the subject holding the permission.
  • target_type: PersonalPermissionsTargetIdentifierType | None — Kind of identifier in target_value.
  • target_value: str | None — Identifier of the target the permission is scoped to, if any.
  • permission_type: PersonalPermissionScope — Permission scope.
  • description: str — Reason recorded when the permission was granted.
  • subject_first_name: str | None — First name of the subject holding the permission, if known.
  • subject_last_name: str | None — Last name of the subject holding the permission, if known.
  • entity_first_name: str | None — First name of the entity owner, if the entity is a natural person.
  • entity_address: str | None — Address of the entity the permission applies to, if known.
  • permission_state: PermissionState — Whether the permission is active or inactive.
  • start_date: datetime — When the permission became effective.
  • can_delegate: bool — Whether the holder may delegate this permission further.

PersonalPermissionsQuery

Import: from ksef2.models import PersonalPermissionsQuery

class PersonalPermissionsQuery(KSeFBaseModel)
python

Filters for querying permissions held by the authenticated subject.

Attributes

  • permission_types: list[PersonalPermissionScope] | None — Restrict results to these permission scopes; None for all.
  • permission_state: PermissionState | None — Restrict results to active or inactive permissions; None for both.
  • context_type: PersonalPermissionsContextIdentifierType | None — Kind of identifier in context_value.
  • context_value: str | None — Restrict results to this context identifier.
  • target_type: PersonalPermissionsTargetIdentifierType | None — Kind of identifier in target_value.
  • target_value: str | None — Restrict results to permissions scoped to this target.

PersonalPermissionsQueryResponse

Import: from ksef2.models import PersonalPermissionsQueryResponse

class PersonalPermissionsQueryResponse(KSeFBaseModel)
python

One page of personal permission query results.

Attributes

  • permissions: list[PersonalPermissionDetail] — Permission records on this page.
  • has_more: bool — Whether more results are available after this page.

PersonPermissionDetail

Import: from ksef2.models import PersonPermissionDetail

class PersonPermissionDetail(KSeFBaseModel)
python

Permission record returned from person permission queries.

Attributes

  • id: Annotated[str, Field(max_length=36, min_length=36)] — Permission identifier (36-character UUID), usable for revocation.
  • author_type: PersonAuthorIdentifierType | None — Kind of identifier in author_value.
  • author_value: str | None — Identifier of the author who granted the permission.
  • authorized_type: PersonPermissionsAuthorizedIdentifierType | None — Kind of identifier in authorized_value.
  • authorized_value: str | None — Identifier of the person holding the permission.
  • context_type: PersonPermissionsContextIdentifierType | None — Kind of identifier in context_value.
  • context_value: str | None — Identifier of the context in which the permission applies.
  • target_type: PersonPermissionsTargetIdentifierType | None — Kind of identifier in target_value.
  • target_value: str | None — Identifier of the target the permission is scoped to, if any.
  • permission_state: PermissionState — Whether the permission is active or inactive.
  • permission_type: PersonPermissionScope — Permission scope.
  • description: str — Reason recorded when the permission was granted.
  • start_date: datetime — When the permission became effective.
  • can_delegate: bool — Whether the holder may delegate this permission further.
  • person_first_name: str | None — First name of the person holding the permission, if known.
  • person_last_name: str | None — Last name of the person holding the permission, if known.
  • entity_first_name: str | None — First name of the entity owner holding the permission, if the entity is a natural person.
  • entity_last_name: str | None — Last name of the entity owner holding the permission, if the entity is a natural person.

PersonPermissionsQuery

Import: from ksef2.models import PersonPermissionsQuery

class PersonPermissionsQuery(KSeFBaseModel)
python

Filters for querying person-related permission grants.

Attributes

  • query_type: PersonPermissionsQueryType — Direction of the query: in_context (held in the current context) or granted_in_context (granted by the current context).
  • permission_types: list[PersonPermissionScope] | None — Restrict results to these permission scopes; None for all.
  • permission_state: PermissionState | None — Restrict results to active or inactive permissions; None for both.
  • author_type: PersonAuthorIdentifierType | None — Kind of identifier in author_value.
  • author_value: str | None — Restrict results to permissions granted by this author.
  • authorized_type: PersonPermissionsAuthorizedIdentifierType | None — Kind of identifier in authorized_value.
  • authorized_value: str | None — Restrict results to permissions held by this person.
  • context_type: PersonPermissionsContextIdentifierType | None — Kind of identifier in context_value.
  • context_value: str | None — Restrict results to this context identifier.
  • target_type: PersonPermissionsTargetIdentifierType | None — Kind of identifier in target_value.
  • target_value: str | None — Restrict results to permissions scoped to this target.

PersonPermissionsQueryResponse

Import: from ksef2.models import PersonPermissionsQueryResponse

class PersonPermissionsQueryResponse(KSeFBaseModel)
python

One page of person permission query results.

Attributes

  • permissions: list[PersonPermissionDetail] — Permission records on this page.
  • has_more: bool — Whether more results are available after this page.

PreparedBatch

Import: from ksef2.models import PreparedBatch

class PreparedBatch(KSeFBaseModel)
python

Prepared batch package with encrypted parts and upload metadata.

Attributes

  • form_code: FormSchema — Invoice schema of the batch. Defaults to FA(3).
  • offline_mode: bool — Whether the invoices were issued in offline mode.
  • batch_file: BatchFileInfo — Size, hash and part metadata of the whole batch file.
  • parts: list[BatchPreparedPart] — Encrypted parts to upload.
  • encryption: BatchEncryptionData — Encryption material used for the parts.
  • invoices: list[BatchInvoiceHash] — Hash of each invoice in the package, keyed by ZIP entry name.

PublicKeyCertificate

Import: from ksef2.models import PublicKeyCertificate

class PublicKeyCertificate(KSeFBaseModel)
python

Public certificate that can encrypt tokens or session keys for KSeF.

Attributes

  • certificate: str — DER-encoded X.509 certificate, Base64-encoded.
  • certificate_id: str | None — Identifier of the certificate; None if not reported.
  • public_key_id: str | None — Identifier to pass as public_key_id when encrypting with this key; None if not reported.
  • valid_from: datetime — Start of the certificate validity period.
  • valid_to: datetime — End of the certificate validity period.
  • usage: list[CertUsage] — What the key may be used for, such as token or session-key encryption.

QueryInvoicesMetadataResponse

Import: from ksef2.models import QueryInvoicesMetadataResponse

class QueryInvoicesMetadataResponse(KSeFBaseModel)
python

One page of invoice metadata query results.

Attributes

  • has_more: bool — Whether more results are available after this page.
  • is_truncated: bool — Whether the result set was cut at the server-side limit; narrow the filter or continue from the last dates.
  • permanent_storage_hwm_date: datetime | None — High-water mark of permanent storage up to which results are complete; None if not reported.
  • invoices: list[InvoiceMetadata] — Invoice metadata records on this page.

QueryTokensResponse

Import: from ksef2.models import QueryTokensResponse

class QueryTokensResponse(KSeFBaseModel)
python

A single page of token search results.

Attributes

  • continuation_token: str | None — Opaque token for requesting the next page; None when there are no more pages.
  • tokens: list[TokenInfo] — Tokens on this page.

RateLimitValues

Import: from ksef2.models import RateLimitValues

class RateLimitValues(KSeFBaseModel)
python

Per-second, per-minute, and per-hour caps for one API category.

Attributes

  • per_second: int — Maximum requests per second.
  • per_minute: int — Maximum requests per minute.
  • per_hour: int — Maximum requests per hour.

RefreshedToken

Import: from ksef2.models import RefreshedToken

class RefreshedToken(KSeFBaseModel)
python

Access token returned by the refresh endpoint.

Attributes

  • access_token: TokenCredentials — New access token.

RetrievedCertificatesList

Import: from ksef2.models import RetrievedCertificatesList

class RetrievedCertificatesList(KSeFBaseModel)
python

Certificates returned by the retrieval endpoint.

Attributes

  • certificates: list[Certificate] — Retrieved certificates.

RevokeAttachmentsRequest

Import: from ksef2.models import RevokeAttachmentsRequest

class RevokeAttachmentsRequest(KSeFBaseModel)
python

Payload used to schedule or perform attachment revocation.

Attributes

  • nip: str — NIP of the subject to revoke attachments for.
  • expected_end_date: date | None — Date on which attachment permission should end; None to revoke immediately.

RevokePermissionsRequest

Import: from ksef2.models import RevokePermissionsRequest

class RevokePermissionsRequest(KSeFBaseModel)
python

Payload used to revoke TEST permissions in a chosen context.

Attributes

  • revoke_from: Identifier — Identifier of the subject losing the permissions.
  • in_context_of: Identifier — Identifier of the context from which the permissions are revoked.

SendInvoicePayload

Import: from ksef2.models import SendInvoicePayload

class SendInvoicePayload(KSeFBaseModel)
python

Plain and encrypted bytes for one invoice submitted to an online session.

Attributes

  • xml_bytes: bytes — Plain invoice XML bytes.
  • encrypted_bytes: bytes — Invoice XML encrypted with the session key.

SendInvoiceResponse

Import: from ksef2.models import SendInvoiceResponse

class SendInvoiceResponse(KSeFBaseModel)
python

Response from POST /sessions/online/{ref}/invoices.

Attributes

  • reference_number: str — KSeF reference number of the submitted invoice within the session.

SessionInvoicesResponse

Import: from ksef2.models import SessionInvoicesResponse

class SessionInvoicesResponse(KSeFBaseModel)
python

One page of invoices submitted in a session.

Attributes

  • continuation_token: str | None — Opaque token for requesting the next page; None when there are no more pages.
  • invoices: list[SessionInvoiceStatusResponse] — Invoice statuses on this page.

SessionInvoiceStatusResponse

Import: from ksef2.models import SessionInvoiceStatusResponse

class SessionInvoiceStatusResponse(KSeFBaseModel)
python

Processing status for one invoice submitted in a session.

Attributes

  • ordinal_number: int — One-based position of the invoice within the session.
  • invoice_number: str | None — Seller's invoice number; None until processed.
  • ksef_number: str | None — KSeF number; None until the invoice is accepted.
  • reference_number: str — KSeF reference number of the invoice submission.
  • invoice_hash: str — SHA-256 hash of the invoice XML, Base64-encoded.
  • invoice_file_name: str | None — File name of the invoice in a batch package; None for online sessions.
  • acquisition_date: AwareDatetime | None — When KSeF accepted the invoice; None until accepted.
  • invoicing_date: AwareDatetime — When the invoice was submitted.
  • permanent_storage_date: AwareDatetime | None — When the invoice was moved to permanent storage; None until then.
  • upo_download_url: AnyUrl | None — Pre-signed URL of the invoice UPO. Excluded from serialization and repr.
  • upo_download_url_expiration_date: AwareDatetime | None — When the UPO download URL expires.
  • invoicing_mode: str | None — Invoicing mode reported by KSeF, such as online or offline.
  • status: InvoiceStatusInfo — Processing status of the invoice.

Methods

SessionInvoiceStatusResponse.to_sensitive_dict

def to_sensitive_dict(
    *,
    mode: Literal['json', 'python'] | str = 'json',
) -> dict[str, object]
python

Export invoice status with its capability-bearing UPO URL.

Parameters

  • mode (Literal['json', 'python'] | str) — Pydantic dump mode, "json" for JSON-safe values or "python" for native types.

Returns

  • dict[str, object] — A dictionary including the plain UPO download URL.

SessionLimits

Import: from ksef2.models import SessionLimits

class SessionLimits(KSeFBaseModel)
python

Invoice count and payload size limits for one session type.

Attributes

  • max_invoice_size_mb: int — Maximum size of one invoice without attachment, in megabytes.
  • max_invoice_with_attachment_size_mb: int — Maximum size of one invoice with an attachment, in megabytes.
  • max_invoices: int — Maximum number of invoices in one session.

SessionStatusResponse

Import: from ksef2.models import SessionStatusResponse

class SessionStatusResponse(KSeFBaseModel)
python

Current status and counters for an online or batch session.

Attributes

  • status: StatusInfo — Current status of the session.
  • date_created: AwareDatetime — When the session was opened.
  • date_updated: AwareDatetime — When the session status last changed.
  • valid_until: AwareDatetime | None — When the session expires; None if not reported.
  • upo: Upo | None — Session-level UPO once the session is closed and processed; None before that.
  • invoice_count: int | None — Number of invoices submitted in the session.
  • successful_invoice_count: int | None — Number of invoices accepted by KSeF.
  • failed_invoice_count: int | None — Number of invoices rejected by KSeF.

SessionSummary

Import: from ksef2.models import SessionSummary

class SessionSummary(KSeFBaseModel)
python

Summary row returned when listing sessions.

Attributes

  • reference_number: str — KSeF reference number of the session.
  • status: StatusInfo — Status of the session.
  • date_created: AwareDatetime — When the session was opened.
  • date_updated: AwareDatetime — When the session status last changed.
  • valid_until: AwareDatetime | None — When the session expires; None if not reported.
  • total_invoice_count: int — Number of invoices submitted in the session.
  • successful_invoice_count: int — Number of invoices accepted by KSeF.
  • failed_invoice_count: int — Number of invoices rejected by KSeF.

StatusInfo

Import: from ksef2.models import StatusInfo

class StatusInfo(KSeFBaseModel)
python

Generic KSeF status code, description, and optional details.

Attributes

  • code: int — Numeric status code.
  • description: str — Human-readable description of the status.
  • details: list[str] | None — Additional status details reported by KSeF, if any.

SubjectCertificateLimits

Import: from ksef2.models import SubjectCertificateLimits

class SubjectCertificateLimits(KSeFBaseModel)
python

Certificate issuance limit override for the current subject.

Attributes

  • max_certificates: int | None — Maximum number of certificates; None when no override is set.

SubjectEnrollmentLimits

Import: from ksef2.models import SubjectEnrollmentLimits

class SubjectEnrollmentLimits(KSeFBaseModel)
python

Certificate enrollment limit override for the current subject.

Attributes

  • max_enrollments: int | None — Maximum number of enrollment requests; None when no override is set.

SubjectIdentifier

Import: from ksef2.models import SubjectIdentifier

class SubjectIdentifier(KSeFBaseModel)
python

Identifier of the subject the certificate was issued for.

Attributes

  • type: IdentifierType — Kind of identifier in value (nip, pesel or fingerprint).
  • value: str — Identifier of the certificate subject.

SubjectLimits

Import: from ksef2.models import SubjectLimits

class SubjectLimits(KSeFBaseModel)
python

Subject-level limits for certificate enrollment and issuance.

Attributes

  • certificate: SubjectCertificateLimits | None — Certificate issuance limit override; None when no override is set.
  • enrollment: SubjectEnrollmentLimits | None — Certificate enrollment limit override; None when no override is set.

SubordinateEntityRoleDetail

Import: from ksef2.models import SubordinateEntityRoleDetail

class SubordinateEntityRoleDetail(KSeFBaseModel)
python

Role record returned from subordinate-entity role queries.

Attributes

  • subordinate_entity_type: EntityIdentifierType — Kind of identifier in subordinate_entity_value.
  • subordinate_entity_value: str — Identifier of the subordinate entity.
  • role: SubordinateEntityRoleType — Role of the subordinate entity.
  • description: str — Human-readable description of the role.
  • start_date: datetime — When the role became effective.

SubordinateEntityRolesQuery

Import: from ksef2.models import SubordinateEntityRolesQuery

class SubordinateEntityRolesQuery(KSeFBaseModel)
python

Filters for querying subordinate entity roles.

Attributes

  • subordinate_nip: str | None — Restrict results to this subordinate entity NIP; None for all.

SubordinateEntityRolesQueryResponse

Import: from ksef2.models import SubordinateEntityRolesQueryResponse

class SubordinateEntityRolesQueryResponse(KSeFBaseModel)
python

One page of subordinate entity role query results.

Attributes

  • roles: list[SubordinateEntityRoleDetail] — Roles on this page.
  • has_more: bool — Whether more results are available after this page.

SubUnit

Import: from ksef2.models import SubUnit

class SubUnit(KSeFBaseModel)
python

Subunit belonging to a TEST subject.

Attributes

  • subject_nip: str — NIP of the subunit.
  • description: str — Description of the subunit.

SubunitPermission

Import: from ksef2.models import SubunitPermission

class SubunitPermission(KSeFBaseModel)
python

Permission record returned from subunit permission queries.

Attributes

  • id: Annotated[str, Field(max_length=36, min_length=36)] — Permission identifier (36-character UUID).
  • authorized_type: CertificateSubjectIdentifierType — Kind of identifier in authorized_value.
  • authorized_value: str — Identifier of the person holding the permission.
  • subunit_type: SubunitIdentifierType — Kind of identifier in subunit_value.
  • subunit_value: str — Identifier of the subunit.
  • author_type: CertificateSubjectIdentifierType — Kind of identifier in author_value.
  • author_value: str — Identifier of the author who granted the permission.
  • permission_type: PersonPermissionScope — Permission scope.
  • description: str — Reason recorded when the permission was granted.
  • subject_first_name: str | None — First name of the person holding the permission, if known.
  • subject_last_name: str | None — Last name of the person holding the permission, if known.
  • entity_first_name: str | None — First name of the entity owner, if the entity is a natural person.
  • entity_last_name: str | None — Last name of the entity owner, if the entity is a natural person.
  • subunit_name: str | None — Display name of the subunit, if known.
  • start_date: datetime — When the permission became effective.

SubunitPermissionsQuery

Import: from ksef2.models import SubunitPermissionsQuery

class SubunitPermissionsQuery(KSeFBaseModel)
python

Filters for querying permissions assigned to subunits.

Attributes

  • subunit_nip: str | None — Restrict results to this subunit NIP; None for all.

SubunitPermissionsQueryResponse

Import: from ksef2.models import SubunitPermissionsQueryResponse

class SubunitPermissionsQueryResponse(KSeFBaseModel)
python

One page of subunit permission query results.

Attributes

  • permissions: list[SubunitPermission] — Permission records on this page.
  • has_more: bool — Whether more results are available after this page.

TokenAuthorIdentifier

Import: from ksef2.models import TokenAuthorIdentifier

class TokenAuthorIdentifier(KSeFBaseModel)
python

Identifies the subject that created the token.

Attributes

  • type: TokenAuthorIdentifierType — Kind of identifier in value.
  • value: str — Identifier of the subject that created the token.

TokenContextIdentifier

Import: from ksef2.models import TokenContextIdentifier

class TokenContextIdentifier(KSeFBaseModel)
python

Identifies the taxpayer or organizational context bound to a token.

Attributes

  • type: TokenContextIdentifierType — Kind of identifier in value.
  • value: str — Identifier of the context the token is bound to.

TokenCredentials

Import: from ksef2.models import TokenCredentials

class TokenCredentials(KSeFBaseModel)
python

A bearer token together with its expiration time.

Attributes

  • token: str — Bearer token value. Excluded from serialization and repr.
  • valid_until: datetime — When the token expires.

TokenInfo

Import: from ksef2.models import TokenInfo

class TokenInfo(KSeFBaseModel)
python

Metadata returned when querying tokens.

Attributes

  • reference_number: str — KSeF reference number of the operation or resource.
  • author_identifier: TokenAuthorIdentifier — Subject that created the token.
  • context_identifier: TokenContextIdentifier — Context the token is bound to.
  • description: str — Description given when the token was generated.
  • requested_permissions: list[TokenPermission] — Permissions the token was generated with.
  • date_created: datetime — When the token was generated.
  • last_use_date: datetime | None — When the token was last used; None if never used.
  • status: TokenStatus — Current lifecycle status of the token.
  • status_details: list[str] | None — Additional status details, if any.

TokenListParams

Import: from ksef2.models import TokenListParams

class TokenListParams(KSeFBaseParams[ListTokensQueryParams], PageSizeMixin)
python

Query parameters for token listings.

Attributes

  • status: list[TokenStatus] | None — Match tokens in any of these statuses.
  • description: str | None — Match tokens whose description contains this text.
  • author_identifier: str | None — Match tokens created by this identifier.
  • author_identifier_type: TokenAuthorIdentifierType | None — Kind of identifier in author_identifier.

TokenStatusResponse

Import: from ksef2.models import TokenStatusResponse

class TokenStatusResponse(KSeFBaseModel)
python

Current lifecycle status of one token.

Attributes

  • reference_number: str — KSeF reference number of the operation or resource.
  • status: TokenStatus — Current lifecycle status of the token.

UnblockContextRequest

Import: from ksef2.models import UnblockContextRequest

class UnblockContextRequest(KSeFBaseModel)
python

Payload used to unblock authentication for a TEST context.

Attributes

  • context: AuthContextIdentifier — Authentication context to unblock.

UpdateCertificateRequest

Import: from ksef2.models import UpdateCertificateRequest

class UpdateCertificateRequest(KSeFBaseModel)
python

Payload used to shorten a TEST certificate's validity.

Attributes

  • valid_to: AwareDatetime — New, earlier end of the certificate validity period.

Upo

Import: from ksef2.models import Upo

class Upo(KSeFBaseModel)
python

Collection of UPO pages available for a session or invoice.

Attributes

  • pages: list[UpoPage] — UPO pages available for download.

UpoPage

Import: from ksef2.models import UpoPage

class UpoPage(KSeFBaseModel)
python

Download information for one UPO page.

Attributes

  • reference_number: str — Reference number of the UPO page.
  • download_url: AnyUrl — Pre-signed URL of the UPO page. Excluded from serialization and repr.
  • download_url_expiration_date: AwareDatetime — When the download URL expires.

Methods

UpoPage.to_sensitive_dict

def to_sensitive_dict(
    *,
    mode: Literal['json', 'python'] | str = 'json',
) -> dict[str, object]
python

Export UPO metadata with its capability-bearing download URL.

Parameters

  • mode (Literal['json', 'python'] | str) — Pydantic dump mode, "json" for JSON-safe values or "python" for native types.

Returns

  • dict[str, object] — A dictionary including the plain download URL.

Enumerations

AuthContextIdentifierTypeEnum

Import: from ksef2.models import AuthContextIdentifierTypeEnum

class AuthContextIdentifierTypeEnum(StrEnum)
python

Runtime enum for TEST authentication context identifiers.

Values

NameValue
NIP'nip'
INTERNAL_ID'internal_id'
NIP_VAT_UE'nip_vat_ue'
PEPPOL_ID'peppol_id'

AuthorizationPermissionTypeEnum

Import: from ksef2.models import AuthorizationPermissionTypeEnum

class AuthorizationPermissionTypeEnum(StrEnum)
python

Runtime enum for authorization permission scopes.

Values

NameValue
SELF_INVOICING'self_invoicing'
RR_INVOICING'rr_invoicing'
TAX_REPRESENTATIVE'tax_representative'
PEF_INVOICING'pef_invoicing'

AuthorizationSubjectIdentifierTypeEnum

Import: from ksef2.models import AuthorizationSubjectIdentifierTypeEnum

class AuthorizationSubjectIdentifierTypeEnum(StrEnum)
python

Runtime enum for authorization subject identifier types.

Values

NameValue
NIP'nip'
PEPPOL_ID'peppol_id'

CertificateStatusEnum

Import: from ksef2.models import CertificateStatusEnum

class CertificateStatusEnum(StrEnum)
python

Runtime enum for certificate lifecycle statuses.

Values

NameValue
ACTIVE'active'
BLOCKED'blocked'
REVOKED'revoked'
EXPIRED'expired'

CertificateTypeEnum

Import: from ksef2.models import CertificateTypeEnum

class CertificateTypeEnum(StrEnum)
python

Runtime enum for certificate types.

Values

NameValue
AUTHENTICATION'authentication'
OFFLINE'offline'

CertUsageEnum

Import: from ksef2.models import CertUsageEnum

class CertUsageEnum(StrEnum)
python

Runtime enum for KSeF public-certificate usages.

Values

NameValue
KSEF_TOKEN_ENCRYPTION'ksef_token_encryption'
SYMMETRIC_KEY_ENCRYPTION'symmetric_key_encryption'

CompressionTypeEnum

Import: from ksef2.models import CompressionTypeEnum

class CompressionTypeEnum(StrEnum)
python

Runtime enum for KSeF compression values.

Values

NameValue
ZIP'Zip'
TAR_GZ'TarGz'

ContextIdentifierTypeEnum

Import: from ksef2.models import ContextIdentifierTypeEnum

class ContextIdentifierTypeEnum(StrEnum)
python

Runtime enum for authentication context identifier types.

Values

NameValue
NIP'nip'
INTERNAL_ID'internal_id'
NIP_VAT_UE'nip_vat_ue'
PEPPOL_ID'peppol_id'

EntityPermissionTypeEnum

Import: from ksef2.models import EntityPermissionTypeEnum

class EntityPermissionTypeEnum(StrEnum)
python

Runtime enum for entity permission scopes.

Values

NameValue
INVOICE_READ'invoice_read'
INVOICE_WRITE'invoice_write'
COLLECTIVE_IDENTIFIER_MANAGE'collective_identifier_manage'

EuEntityAdminContextIdentifierTypeEnum

Import: from ksef2.models import EuEntityAdminContextIdentifierTypeEnum

class EuEntityAdminContextIdentifierTypeEnum(StrEnum)
python

Runtime enum for EU-entity administration context identifiers.

Values

NameValue
NIP_VAT_UE'nip_vat_ue'

EuEntityPermissionTypeEnum

Import: from ksef2.models import EuEntityPermissionTypeEnum

class EuEntityPermissionTypeEnum(StrEnum)
python

Runtime enum for EU-entity permission scopes.

Values

NameValue
INVOICE_READ'invoice_read'
INVOICE_WRITE'invoice_write'

FormSchema

Import: from ksef2.models import FormSchema

class FormSchema(Enum)
python
FormSchema(system_code: str, schema_version: str, schema_value: str)
python

Supported form schemas for online sessions.

Values

NameValue
FA2('FA (2)', '1-0E', 'FA')
FA3('FA (3)', '1-0E', 'FA')
FA_RR1('FA_RR (1)', '1-1E', 'FA_RR')
PEF3('PEF (3)', '2-1', 'PEF')
PEF_KOR3('PEF_KOR (3)', '2-1', 'PEF')
system_codesystem_code
schema_versionschema_version
schema_valueschema_value

IdentifierTypeEnum

Import: from ksef2.models import IdentifierTypeEnum

class IdentifierTypeEnum(StrEnum)
python

Runtime enum for TEST data identifier types.

Values

NameValue
NIP'nip'
PESEL'pesel'
FINGERPRINT'fingerprint'
SYSTEM'system'

IndirectPermissionTypeEnum

Import: from ksef2.models import IndirectPermissionTypeEnum

class IndirectPermissionTypeEnum(StrEnum)
python

Runtime enum for indirect permission scopes.

Values

NameValue
INVOICE_READ'invoice_read'
INVOICE_WRITE'invoice_write'
COLLECTIVE_IDENTIFIER_MANAGE'collective_identifier_manage'

IndirectTargetIdentifierTypeEnum

Import: from ksef2.models import IndirectTargetIdentifierTypeEnum

class IndirectTargetIdentifierTypeEnum(StrEnum)
python

Runtime enum for indirect permission target identifiers.

Values

NameValue
NIP'nip'
ALL_PARTNERS'all_partners'
INTERNAL_ID'internal_id'

PermissionTypeEnum

Import: from ksef2.models import PermissionTypeEnum

class PermissionTypeEnum(StrEnum)
python

Runtime enum for TEST permission scopes.

Values

NameValue
INVOICE_READ'invoice_read'
INVOICE_WRITE'invoice_write'
PEF_INVOICE_WRITE'pef_invoice_write'
INTROSPECTION'introspection'
CREDENTIALS_READ'credentials_read'
CREDENTIALS_MANAGE'credentials_manage'
ENFORCEMENT_OPERATIONS'enforcement_operations'
SUBUNIT_MANAGE'subunit_manage'
VAT_UE_MANAGE'vat_ue_manage'
COLLECTIVE_IDENTIFIER_MANAGE'collective_identifier_manage'

RevocationReasonEnum

Import: from ksef2.models import RevocationReasonEnum

class RevocationReasonEnum(StrEnum)
python

Runtime enum for certificate revocation reasons.

Values

NameValue
UNSPECIFIED'unspecified'
SUPERSEDED'superseded'
KEY_COMPROMISE'key_compromise'

SessionStatusEnum

Import: from ksef2.models import SessionStatusEnum

class SessionStatusEnum(StrEnum)
python

Runtime enum for KSeF session status values.

Values

NameValue
IN_PROGRESS'InProgress'
SUCCEEDED'Succeeded'
FAILED'Failed'
CANCELLED'Cancelled'

SubjectTypeEnum

Import: from ksef2.models import SubjectTypeEnum

class SubjectTypeEnum(StrEnum)
python

Runtime enum for TEST subject types.

Values

NameValue
ENFORCEMENT_AUTHORITY'enforcement_authority'
VAT_GROUP'vat_group'
JST'jst'

SubunitIdentifierTypeEnum

Import: from ksef2.models import SubunitIdentifierTypeEnum

class SubunitIdentifierTypeEnum(StrEnum)
python

Runtime enum for subunit context identifiers.

Values

NameValue
NIP'nip'
INTERNAL_ID'internal_id'

TokenAuthorIdentifierTypeEnum

Import: from ksef2.models import TokenAuthorIdentifierTypeEnum

class TokenAuthorIdentifierTypeEnum(StrEnum)
python

Runtime enum for token author identifier types.

Values

NameValue
NIP'nip'
PESEL'pesel'
FINGERPRINT'fingerprint'

TokenPermissionEnum

Import: from ksef2.models import TokenPermissionEnum

class TokenPermissionEnum(StrEnum)
python

Runtime enum for token permission scopes.

Values

NameValue
INVOICE_READ'invoice_read'
INVOICE_WRITE'invoice_write'
INTROSPECTION'introspection'
CREDENTIALS_READ'credentials_read'
CREDENTIALS_MANAGE'credentials_manage'
SUBUNIT_MANAGE'subunit_manage'
ENFORCEMENT_OPERATIONS'enforcement_operations'
COLLECTIVE_IDENTIFIER_MANAGE'collective_identifier_manage'

TokenStatusEnum

Import: from ksef2.models import TokenStatusEnum

class TokenStatusEnum(StrEnum)
python

Runtime enum for token lifecycle statuses.

Values

NameValue
PENDING'pending'
ACTIVE'active'
REVOKING'revoking'
REVOKED'revoked'
FAILED'failed'

Functions

validate_certificate_serial_number

Import: from ksef2.models import validate_certificate_serial_number

def validate_certificate_serial_number(value: str) -> CertificateSerialNumber
python

Validate and return a KSeF certificate serial number.

Parameters

  • value (str) — Candidate serial number.

Returns

  • CertificateSerialNumber — The validated serial number.

Raises

  • pydantic.ValidationError — If value is not a valid certificate serial number.

Type aliases

AuthContextIdentifierType

Import: from ksef2.models import AuthContextIdentifierType

type AuthContextIdentifierType = Literal['nip', 'internal_id', 'nip_vat_ue',
    'peppol_id']
python

AuthenticationMethod

Import: from ksef2.models import AuthenticationMethod

type AuthenticationMethod = Literal['token', 'trusted_profile', 'internal_certificate',
    'qualified_signature', 'qualified_seal', 'personal_signature', 'peppol_signature',
    'ksef_certificate', 'other']
python

AuthenticationMethodCategory

Import: from ksef2.models import AuthenticationMethodCategory

type AuthenticationMethodCategory = Literal['xades_signature', 'national_node', 'token',
    'other']
python

AuthorizationPermissionType

Import: from ksef2.models import AuthorizationPermissionType

type AuthorizationPermissionType = Literal['self_invoicing', 'rr_invoicing',
    'tax_representative', 'pef_invoicing']
python

AuthorizationSubjectIdentifierType

Import: from ksef2.models import AuthorizationSubjectIdentifierType

type AuthorizationSubjectIdentifierType = Literal['nip', 'peppol_id']
python

BuyerIdentifierType

Import: from ksef2.models import BuyerIdentifierType

type BuyerIdentifierType = Literal['nip', 'vat_ue', 'other', 'none']
python

CertificateSerialNumber

Import: from ksef2.models import CertificateSerialNumber

type CertificateSerialNumber = Annotated[str, Field(max_length=16, min_length=16,
    pattern='^[0-9A-F]{16}$')]
python

CertificateStatusValue

Import: from ksef2.models import CertificateStatusValue

type CertificateStatusValue = Literal['active', 'blocked', 'revoked', 'expired']
python

CertificateSubjectIdentifierType

Import: from ksef2.models import CertificateSubjectIdentifierType

type CertificateSubjectIdentifierType = Literal['nip', 'pesel', 'fingerprint']
python

CertificateTypeValue

Import: from ksef2.models import CertificateTypeValue

type CertificateTypeValue = Literal['authentication', 'offline']
python

CertUsage

Import: from ksef2.models import CertUsage

type CertUsage = CertUsageValue
python

CompressionType

Import: from ksef2.models import CompressionType

type CompressionType = Literal['zip', 'tar_gz']
python

ContextIdentifierType

Import: from ksef2.models import ContextIdentifierType

type ContextIdentifierType = Literal['nip', 'internal_id', 'nip_vat_ue', 'peppol_id']
python

CurrencyCodes

Import: from ksef2.models import CurrencyCodes

type CurrencyCodes = Literal['AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AUD',
    'AWG', 'AZN', 'BAM', 'BBD', 'BDT', 'BGN', 'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BOV',
    'BRL', 'BSD', 'BTN', 'BWP', 'BYN', 'BZD', 'CAD', 'CDF', 'CHE', 'CHF', 'CHW', 'CLF',
    'CLP', 'CNY', 'COP', 'COU', 'CRC', 'CUC', 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP',
    'DZD', 'EGP', 'ERN', 'ETB', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GGP', 'GHS', 'GIP',
    'GMD', 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', 'IDR', 'ILS', 'IMP',
    'INR', 'IQD', 'IRR', 'ISK', 'JEP', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF',
    'KPW', 'KRW', 'KWD', 'KYD', 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LYD', 'MAD',
    'MDL', 'MGA', 'MKD', 'MMK', 'MNT', 'MOP', 'MRU', 'MUR', 'MVR', 'MWK', 'MXN', 'MXV',
    'MYR', 'MZN', 'NAD', 'NGN', 'NIO', 'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK',
    'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', 'RUB', 'RWF', 'SAR', 'SBD', 'SCR',
    'SDG', 'SEK', 'SGD', 'SHP', 'SLL', 'SOS', 'SRD', 'SSP', 'STN', 'SVC', 'SYP', 'SZL',
    'THB', 'TJS', 'TMT', 'TND', 'TOP', 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD',
    'USN', 'UYI', 'UYU', 'UYW', 'UZS', 'VES', 'VND', 'VUV', 'WST', 'XAF', 'XAG', 'XAU',
    'XBA', 'XBB', 'XBC', 'XBD', 'XCD', 'XCG', 'XDR', 'XOF', 'XPD', 'XPF', 'XPT', 'XSU',
    'XUA', 'XXX', 'YER', 'ZAR', 'ZMW', 'ZWL']
python

EntityIdentifierType

Import: from ksef2.models import EntityIdentifierType

type EntityIdentifierType = Literal['nip']
python

EntityPermissionsContextIdentifierType

Import: from ksef2.models import EntityPermissionsContextIdentifierType

type EntityPermissionsContextIdentifierType = Literal['nip', 'internal_id']
python

EntityPermissionType

Import: from ksef2.models import EntityPermissionType

type EntityPermissionType = Literal['invoice_read', 'invoice_write',
    'collective_identifier_manage']
python

EuEntityAdminContextIdentifierType

Import: from ksef2.models import EuEntityAdminContextIdentifierType

type EuEntityAdminContextIdentifierType = Literal['nip_vat_ue']
python

EuEntityPermissionType

Import: from ksef2.models import EuEntityPermissionType

type EuEntityPermissionType = Literal['invoice_read', 'invoice_write']
python

EuEntityQueryPermissionType

Import: from ksef2.models import EuEntityQueryPermissionType

type EuEntityQueryPermissionType = Literal['vat_ue_manage', 'invoice_write',
    'invoice_read', 'introspection']
python

IdentifierType

Import: from ksef2.models import IdentifierType

type IdentifierType = Literal['nip', 'pesel', 'fingerprint', 'system']
python

IndirectPermissionType

Import: from ksef2.models import IndirectPermissionType

type IndirectPermissionType = Literal['invoice_read', 'invoice_write',
    'collective_identifier_manage']
python

IndirectTargetIdentifierType

Import: from ksef2.models import IndirectTargetIdentifierType

type IndirectTargetIdentifierType = Literal['nip', 'all_partners', 'internal_id']
python

InvoiceType

Import: from ksef2.models import InvoiceType

type InvoiceType = KsefInvoiceTypes
python

InvoicingMode

Import: from ksef2.models import InvoicingMode

type InvoicingMode = Literal['online', 'offline']
python

OperationStatusCode

Import: from ksef2.models import OperationStatusCode

type OperationStatusCode = Literal[100, 200, 400, 410, 420, 430, 440, 450, 500, 550]
python

PermissionState

Import: from ksef2.models import PermissionState

type PermissionState = Literal['active', 'inactive']
python

PermissionType

Import: from ksef2.models import PermissionType

type PermissionType = Literal['invoice_read', 'invoice_write', 'pef_invoice_write',
    'introspection', 'credentials_read', 'credentials_manage', 'enforcement_operations',
    'subunit_manage', 'vat_ue_manage', 'collective_identifier_manage']
python

PersonalPermissionsAuthorizedIdentifierType

Import: from ksef2.models import PersonalPermissionsAuthorizedIdentifierType

type PersonalPermissionsAuthorizedIdentifierType = Literal['nip', 'pesel',
    'fingerprint']
python

PersonalPermissionsContextIdentifierType

Import: from ksef2.models import PersonalPermissionsContextIdentifierType

type PersonalPermissionsContextIdentifierType = Literal['nip', 'internal_id']
python

PersonalPermissionScope

Import: from ksef2.models import PersonalPermissionScope

type PersonalPermissionScope = Literal['invoice_read', 'invoice_write', 'introspection',
    'credentials_read', 'credentials_manage', 'enforcement_operations',
    'subunit_manage', 'vat_ue_manage', 'collective_identifier_manage']
python

PersonalPermissionsTargetIdentifierType

Import: from ksef2.models import PersonalPermissionsTargetIdentifierType

type PersonalPermissionsTargetIdentifierType = Literal['nip', 'all_partners',
    'internal_id']
python

PersonAuthorIdentifierType

Import: from ksef2.models import PersonAuthorIdentifierType

type PersonAuthorIdentifierType = Literal['nip', 'pesel', 'fingerprint', 'system']
python

PersonContextIdentifierType

Import: from ksef2.models import PersonContextIdentifierType

type PersonContextIdentifierType = Literal['nip', 'internal_id']
python

PersonPermissionsAuthorizedIdentifierType

Import: from ksef2.models import PersonPermissionsAuthorizedIdentifierType

type PersonPermissionsAuthorizedIdentifierType = Literal['nip', 'pesel', 'fingerprint']
python

PersonPermissionsContextIdentifierType

Import: from ksef2.models import PersonPermissionsContextIdentifierType

type PersonPermissionsContextIdentifierType = Literal['nip', 'internal_id']
python

PersonPermissionScope

Import: from ksef2.models import PersonPermissionScope

type PersonPermissionScope = Literal['invoice_read', 'invoice_write', 'introspection',
    'credentials_read', 'credentials_manage', 'enforcement_operations',
    'subunit_manage', 'collective_identifier_manage']
python

PersonPermissionsQueryType

Import: from ksef2.models import PersonPermissionsQueryType

type PersonPermissionsQueryType = Literal['in_context', 'granted_in_context']
python

PersonPermissionsTargetIdentifierType

Import: from ksef2.models import PersonPermissionsTargetIdentifierType

type PersonPermissionsTargetIdentifierType = Literal['nip', 'all_partners',
    'internal_id']
python

QueryType

Import: from ksef2.models import QueryType

type QueryType = Literal['granted', 'received']
python

RevocationReason

Import: from ksef2.models import RevocationReason

type RevocationReason = Literal['unspecified', 'superseded', 'key_compromise']
python

SessionStatus

Import: from ksef2.models import SessionStatus

type SessionStatus = Literal['in_progress', 'succeeded', 'failed', 'cancelled']
python

SortOrder

Import: from ksef2.models import SortOrder

type SortOrder = Literal['asc', 'desc']
python

SubjectType

Import: from ksef2.models import SubjectType

type SubjectType = Literal['enforcement_authority', 'vat_group', 'jst']
python

SubordinateEntityRoleType

Import: from ksef2.models import SubordinateEntityRoleType

type SubordinateEntityRoleType = Literal['local_government_sub_unit',
    'vat_group_sub_unit']
python

SubunitIdentifierType

Import: from ksef2.models import SubunitIdentifierType

type SubunitIdentifierType = Literal['nip', 'internal_id']
python

ThirdSubjectIdentifierType

Import: from ksef2.models import ThirdSubjectIdentifierType

type ThirdSubjectIdentifierType = Literal['nip', 'internal_id', 'vat_ue', 'other',
    'none']
python

TokenAuthorIdentifierType

Import: from ksef2.models import TokenAuthorIdentifierType

type TokenAuthorIdentifierType = Literal['nip', 'pesel', 'fingerprint']
python

TokenContextIdentifierType

Import: from ksef2.models import TokenContextIdentifierType

type TokenContextIdentifierType = Literal['nip', 'internal_id', 'nip_vat_ue',
    'peppol_id']
python

TokenPermission

Import: from ksef2.models import TokenPermission

type TokenPermission = Literal['invoice_read', 'invoice_write', 'introspection',
    'credentials_read', 'credentials_manage', 'subunit_manage',
    'enforcement_operations', 'collective_identifier_manage']
python

TokenStatus

Import: from ksef2.models import TokenStatus

type TokenStatus = Literal['pending', 'active', 'revoking', 'revoked', 'failed']
python