GitHub

Client Lifecycle Reference

Constructor arguments, branch ownership, close behavior, and lifecycle errors for ksef2 clients.

On this page

This page is the reference contract for root clients and authenticated clients. Use the how-to guide when you need a runnable setup sequence.

Root client constructors

Client(
    environment=Environment.PRODUCTION,
    *,
    transport_config=None,
    http_client=None,
)

AsyncClient(
    environment=Environment.PRODUCTION,
    *,
    transport_config=None,
    http_client=None,
)
python
ArgumentSync typeAsync typeDefaultMeaning
environmentEnvironmentEnvironmentEnvironment.PRODUCTIONKSeF environment and base URL used by the root client.
transport_config`TransportConfigNone``TransportConfigNone`
http_client`httpx.ClientNone``httpx.AsyncClientNone`

When http_client is omitted, the SDK creates the underlying httpx client from transport_config and closes it when the root client closes.

Root client members

MemberAvailable onReturnsNotes
authenticationClient, AsyncClientAuthClient / AsyncAuthClientEntry point for token, XAdES, TEST certificate, and profile authentication.
encryptionClient, AsyncClientEncryptionClient / AsyncEncryptionClientPublic KSeF encryption-certificate lookup.
peppolClient, AsyncClientPeppolClient / AsyncPeppolClientPublic PEPPOL provider lookup.
testdataClient, AsyncClientTestDataClient / AsyncTestDataClientTEST-only fixture branch. Raises outside Environment.TEST.
rawClient, AsyncClientRawClient / AsyncRawClientLow-level unauthenticated endpoint groups.
authenticated(auth_tokens)Client, AsyncClientAuthenticatedClient / AsyncAuthenticatedClientDeprecated compatibility wrapper. Use authentication.resume(AuthenticationResumeState.from_tokens(auth_tokens)).
close()ClientNoneIdempotently closes an SDK-owned sync HTTP client and invalidates cached branches.
aclose()AsyncClientNoneIdempotently closes async resources and invalidates cached branches.

Branch properties are cached while the root client is open. After the root client closes, branch access and operations guarded by lifecycle middleware raise KSeFClientClosedError.

Context managers

ClientContext protocolCleanup method
Clientwith Client(...) as client:client.close() on exit.
AsyncClientasync with AsyncClient(...) as client:await client.aclose() on exit.

Context managers only close the root client. Online and batch sessions are separate lifecycle boundaries and should also be closed through their own context managers or service methods.

Authenticated client members

Authentication returns an authenticated client bound to one KSeF context and one token pair.

MemberReturnsNotes
auth_tokensAuthTokensAccess and refresh token models used by this authenticated branch.
access_tokenstrBearer access-token string. Treat as a secret.
refresh_tokenstrRefresh-token string. Treat as a secret.
resume_state()AuthenticationResumeStateSerializable authentication state containing access and refresh tokens.
online_session(form_code=... | state=...)Online session clientOpens one online invoice session, or resumes one from saved state (object or JSON). Async returns an awaitable async context-manager wrapper.
resume_online_session(state)Online session clientDeprecated; use online_session(state=...).
batch_session(prepared_batch= | batch_file= | state=)Batch session clientOpens a batch session from a prepared batch or declared batch file, or resumes one from saved state.
open_batch_session(...)Batch session clientOpens a batch session when caller owns encryption metadata.
resume_batch_session(state)Batch session clientDeprecated; use batch_session(state=...).
invoicesInvoicesServiceMetadata, direct download, export, package download, and waiting helpers.
batchBatchServiceHigh-level batch package preparation, upload, close, status, and UPO workflow.
limitsLimitsClientContext, subject, and API rate-limit endpoints.
tokensTokensClientToken generation, status, listing, and revocation.
certificatesCertificatesClientCertificate enrollment, retrieval, query, limits, and revocation.
sessionsSessionManagementClientAuthentication session listing and termination.
invoice_sessionsInvoiceSessionsClientOnline and batch invoice-session history and UPO downloads from stored references.
permissionsPermissionsClientPermission grants, queries, revokes, and operation status.
rawRawAuthenticatedClientLow-level authenticated endpoint groups.

AuthenticationResumeState owns bearer access and refresh tokens. OnlineSessionResumeState and BatchSessionResumeState do not contain bearer authentication; resume them through an authenticated client.

Authenticated clients share the root client's transport and certificate cache. They do not own an independent HTTP client.

HTTP client ownership

SetupHTTP configuration sourceWho closes HTTP resources
Client(Environment.TEST)SDK builds httpx.Client from TransportConfig.Client.close() or context-manager exit.
AsyncClient(Environment.TEST)SDK builds httpx.AsyncClient from TransportConfig.await AsyncClient.aclose() or async context-manager exit.
Client(..., http_client=http)Supplied httpx.Client.Caller closes http.
AsyncClient(..., http_client=http)Supplied httpx.AsyncClient.Caller closes http.

When http_client is supplied, HTTP-client settings such as timeout, pool, TLS, proxy, trust_env, HTTP/2, custom transports, and event hooks come from that supplied object. SDK retry middleware still uses transport_config.retry.

Lifecycle errors

ErrorRaised when
KSeFClientClosedErrorA root client or lifecycle-guarded branch is used after close.
KSeFUnsupportedEnvironmentErrorA TEST-only root branch, currently testdata, is accessed outside Environment.TEST.
  • Client setup: Create clients in scripts, jobs, and framework dependencies.
  • Authentication methods: Understand how root clients become authenticated clients.
  • Operations reference: Review transport config, retry behavior, timeouts, and resumability.
  • Low-level API: Use schema-native endpoint wrappers when workflow clients are not enough.