Skip to main content

Modern Python SDK + CLI for Poland's National e-Invoice System (KSeF)

Project description

ksef-py

A modern Python SDK + CLI for Poland's National e-Invoice System (KSeF)

CI Coverage PyPI version Python versions License: MIT

โš ๏ธ Important: KSeF will become mandatory for large taxpayers on 1 February 2026, and for everyone else on 1 April 2026. Start your integration now!

๐Ÿš€ Quick Start

# Install via pip
pip install ksef-py

# Or with Poetry
poetry add ksef-py
from ksef import KsefClient
from pathlib import Path

# Initialize client
client = KsefClient(
    nip="1234567890",
    env="test",  # "test" or "prod"
    token_path="~/tokens/ksef.jwt"
)

# Send an invoice
xml = Path("invoice_FA3.xml").read_text()
ksef_nr = await client.send_invoice(xml)

# Check status
status = await client.get_status(ksef_nr)

# Download PDF
pdf_path = await client.download(ksef_nr, format="pdf")

print(f"โœ… Sent! KSeF no: {ksef_nr}")
print(f"๐Ÿ“„ Status: {status}")
print(f"๐Ÿ’พ PDF saved to: {pdf_path}")

๐Ÿ› ๏ธ CLI Usage

# Send an invoice
ksef send invoice.xml --nip 1234567890 --env test

# Check invoice status
ksef status KSEF:2025:PL/123/ABC... --nip 1234567890

# Download invoice
ksef download KSEF:2025:PL/123/ABC... --nip 1234567890 --format pdf

# Validate XML before sending
ksef validate invoice.xml

# Start local stub server for development
ksef stub-server --port 8000

๐Ÿ“‹ Features

Core SDK

  • ๐Ÿ”„ Async-first design with httpx for modern Python applications
  • ๐Ÿ” Flexible authentication - token-based or challenge-file methods
  • ๐Ÿ›ก๏ธ Strong typing with Pydantic models generated from official XSD schemas
  • ๐Ÿ” Automatic retries with exponential backoff
  • ๐Ÿ“ Comprehensive logging and error handling
  • ๐ŸŒ Both REST and SOAP endpoint support

CLI Tools

  • ๐Ÿ“ค Send invoices with progress indicators and beautiful output
  • ๐Ÿ“Š Check status with formatted tables
  • ๐Ÿ’พ Download files in PDF or XML format
  • โœ… Validate XML against official KSeF schemas
  • ๐Ÿงช Local stub server for offline development and testing

Developer Experience

  • ๐Ÿงช Offline testing with mock server
  • ๐Ÿ“š Auto-updating schemas from Ministry of Finance
  • ๐Ÿšจ GitHub Action for XML validation in CI/CD
  • ๐Ÿ“– Rich documentation and examples
  • ๐Ÿ” Full mypy and ruff support

๐Ÿ“ฆ Installation

Basic Installation

pip install ksef-py

Development Installation

# Clone the repository  
git clone https://github.com/Kamil-Dab/ksef-py.git
cd ksef-py

# Install with Poetry
poetry install

# Install pre-commit hooks
poetry run pre-commit install

Docker

# Run CLI in Docker
docker run --rm -v $(pwd):/workspace ksef-py:latest \
  ksef send /workspace/invoice.xml --nip 1234567890

๐Ÿ”ง Configuration

Environment Variables

export KSEF_NIP=1234567890
export KSEF_ENV=test  # or prod
export KSEF_TOKEN_PATH=~/.ksef/token.jwt

Configuration File

Create ~/.ksef/config.toml:

[default]
nip = "1234567890"
environment = "test"
token_path = "~/.ksef/token.jwt"

[test]
base_url = "https://ksef-test.mf.gov.pl/api"
timeout = 30

[prod]
base_url = "https://ksef.mf.gov.pl/api"
timeout = 60

๐Ÿ—๏ธ Architecture

graph TD
    A[Your Application] --> B[ksef-py SDK]
    B --> C[KsefClient]
    C --> D[REST API]
    C --> E[SOAP API]
    D --> F[KSeF Test]
    D --> G[KSeF Prod]
    E --> F
    E --> G
    
    H[CLI] --> B
    I[GitHub Action] --> H
    
    J[Schema Updates] --> K[XSD Files]
    K --> L[Pydantic Models]
    L --> B

๐Ÿ“š API Reference

KsefClient

The main client class for interacting with KSeF API.

Methods

__init__(nip, env="test", token_path=None, **kwargs)

Initialize the KSeF client.

  • nip (str): Company NIP number (10 digits)
  • env (str): Environment - "test" or "prod"
  • token_path (str, optional): Path to JWT token file
  • private_key_path (str, optional): Path to private key for signing
  • certificate_path (str, optional): Path to certificate
async send_invoice(xml_content, filename=None) -> str

Send an invoice to KSeF.

  • xml_content (str): Invoice XML content
  • filename (str, optional): Original filename
  • Returns: KSeF number assigned to the invoice
async get_status(ksef_number) -> InvoiceStatus

Get status of an invoice.

  • ksef_number (str): KSeF number to check
  • Returns: Current status (Accepted, Rejected, Pending, Error)
async download(ksef_number, format="pdf", output_path=None) -> Path

Download an invoice.

  • ksef_number (str): KSeF number to download
  • format (str): Download format - "pdf" or "xml"
  • output_path (str, optional): Where to save the file
  • Returns: Path to downloaded file

Models

Key Pydantic models for type safety:

from ksef.models import (
    KsefEnvironment,      # "test" | "prod"
    InvoiceStatus,        # "Accepted" | "Rejected" | "Pending" | "Error" 
    InvoiceFormat,        # "pdf" | "xml"
    KsefCredentials,      # Authentication configuration
    TokenResponse,        # JWT token response
    InvoiceSendRequest,   # Invoice submission data
    InvoiceStatusResponse # Status check response
)

๐Ÿงช Testing

Run the test suite:

# Run all tests
poetry run pytest

# Run with coverage
poetry run pytest --cov=ksef --cov-report=html

# Run specific test file
poetry run pytest tests/test_client.py

# Run integration tests (requires test environment)
poetry run pytest tests/integration/ --env=test

Using the Stub Server

For offline development and testing:

# Start stub server
poetry run ksef stub-server --port 8000

# In another terminal, use it for testing
export KSEF_BASE_URL=http://localhost:8000
poetry run pytest tests/

๐Ÿš€ GitHub Action

Add KSeF XML validation to your CI/CD pipeline:

# .github/workflows/validate-invoices.yml
name: Validate Invoices

on:
  pull_request:
    paths: ['invoices/**/*.xml']

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.11'
    
    - name: Install ksef-py
      run: pip install ksef-py
    
    - name: Validate invoices
      run: |
        find invoices/ -name "*.xml" -exec ksef validate {} \;

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

# Clone and setup
git clone https://github.com/Kamil-Dab/ksef-py.git
cd ksef-py
poetry install --with dev

# Run linting
poetry run ruff check .
poetry run ruff format .
poetry run mypy ksef/

# Run tests
poetry run pytest

Adding Features

  1. ๐Ÿด Fork the repository
  2. ๐ŸŒฟ Create a feature branch (git checkout -b feature/amazing-feature)
  3. ๐Ÿ’ซ Make your changes with tests
  4. โœ… Ensure all tests pass
  5. ๐Ÿ“ Update documentation
  6. ๐Ÿš€ Submit a pull request

๐Ÿ“‹ Roadmap

v0.1.0 (Current)

  • Basic REST API client
  • CLI with send/status/download commands
  • Token-based authentication
  • Pydantic models and validation
  • Comprehensive test suite
  • GitHub Actions integration

v0.2.0 (Next)

  • SOAP endpoint support with Zeep
  • Challenge-file authentication method
  • Advanced retry strategies
  • Reference data caching
  • Batch operations support

v0.3.0 (Future)

  • Full XSD โ†’ Pydantic model generation
  • WebSocket support for real-time updates
  • Plugin system for custom integrations
  • Advanced reporting and analytics
  • Desktop GUI application

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ†˜ Support

๐Ÿ™ Acknowledgments

  • Polish Ministry of Finance for the KSeF system and API documentation
  • The Python community for excellent async and HTTP libraries
  • Contributors and early adopters providing feedback

Made with โค๏ธ for the Polish business community

Get ready for mandatory e-invoicing in 2026! ๐Ÿ‡ต๐Ÿ‡ฑ

Project details


Download files

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

Source Distribution

ksef_py-0.0.1a1.tar.gz (18.0 kB view details)

Uploaded Source

Built Distribution

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

ksef_py-0.0.1a1-py3-none-any.whl (16.8 kB view details)

Uploaded Python 3

File details

Details for the file ksef_py-0.0.1a1.tar.gz.

File metadata

  • Download URL: ksef_py-0.0.1a1.tar.gz
  • Upload date:
  • Size: 18.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.2 CPython/3.12.3 Linux/6.8.0-60-generic

File hashes

Hashes for ksef_py-0.0.1a1.tar.gz
Algorithm Hash digest
SHA256 437b43a25d54f9760b0e4a080ca28335f925881244d6ba4aec61dd4c3987aceb
MD5 a583d5d49d56d6a584d2f4c6d9b327a0
BLAKE2b-256 882974ae8b0afe2f06fa50a9ac3b9d6104dcab7b97ad17fcad547168ff70f42a

See more details on using hashes here.

File details

Details for the file ksef_py-0.0.1a1-py3-none-any.whl.

File metadata

  • Download URL: ksef_py-0.0.1a1-py3-none-any.whl
  • Upload date:
  • Size: 16.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.2 CPython/3.12.3 Linux/6.8.0-60-generic

File hashes

Hashes for ksef_py-0.0.1a1-py3-none-any.whl
Algorithm Hash digest
SHA256 7a3b132a6c400b0a4a76f89e8f535b930a4db2992456c3292111c2975ae95624
MD5 9fc607bc3b3987db768c8cfdbf37278a
BLAKE2b-256 af4c7ab7cc49a9d7f5e3a5d4a3555633057153ef855635c6c308299db6fc8a7c

See more details on using hashes here.

Supported by

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