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)
โ ๏ธ 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
httpxfor 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 fileprivate_key_path(str, optional): Path to private key for signingcertificate_path(str, optional): Path to certificate
async send_invoice(xml_content, filename=None) -> str
Send an invoice to KSeF.
xml_content(str): Invoice XML contentfilename(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 downloadformat(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
- ๐ด Fork the repository
- ๐ฟ Create a feature branch (
git checkout -b feature/amazing-feature) - ๐ซ Make your changes with tests
- โ Ensure all tests pass
- ๐ Update documentation
- ๐ 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
- ๐ Issues: https://github.com/Kamil-Dab/ksef-py/issues
- ๐ฌ Discussions: https://github.com/Kamil-Dab/ksef-py/discussions
๐ 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
437b43a25d54f9760b0e4a080ca28335f925881244d6ba4aec61dd4c3987aceb
|
|
| MD5 |
a583d5d49d56d6a584d2f4c6d9b327a0
|
|
| BLAKE2b-256 |
882974ae8b0afe2f06fa50a9ac3b9d6104dcab7b97ad17fcad547168ff70f42a
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7a3b132a6c400b0a4a76f89e8f535b930a4db2992456c3292111c2975ae95624
|
|
| MD5 |
9fc607bc3b3987db768c8cfdbf37278a
|
|
| BLAKE2b-256 |
af4c7ab7cc49a9d7f5e3a5d4a3555633057153ef855635c6c308299db6fc8a7c
|