Python SDK Documentation
Sharokey Python SDK for secure secret sharing with Zero Knowledge encryption. Async/await support with CLI-compatible method naming.
Installation
# Install via pip
pip install sharokey
# Test installation and connectivity
python -c "
import asyncio
from sharokey import SharokeyClient
client = SharokeyClient(token='your_api_token_here')
asyncio.run(client.test())
"
Commands
Method | CLI Equivalent | Description | Example |
---|---|---|---|
create() | sharokey create | Create secret | await client.create("password", 24, 1) |
list() | sharokey list | List secrets | await client.list(limit=10, status='active') |
get() | sharokey get | Get secret details | await client.get('ABC123') |
delete() | sharokey delete | Expire secret (clears content) | await client.delete('ABC123') |
stats() | sharokey stats | Show statistics | await client.stats() |
test() | sharokey test | Test connectivity | await client.test() |
Secret Requests
Method | CLI Equivalent | Description | Example |
---|---|---|---|
create_request() | sharokey create-request | Create request | await client.create_request(message="Share credentials", secret_expiration_hours=24, request_expiration_hours=48, maximum_views=1, locale="fr") |
list_requests() | sharokey list-requests | List requests | await client.list_requests(status='active', limit=10) |
get_request() | sharokey get-request | Get request details | await client.get_request('abc123token456') |
delete_request() | sharokey delete-request | Expire request (cancels) | await client.delete_request('abc123token456') |
request_stats() | sharokey request-stats | Request statistics | await client.request_stats() |
Parameters
Create Secret
Parameter | Description | Example |
---|---|---|
content | Secret content (255 chars max) | "Database password: admin123" |
hours | Expiration hours (1-8760) | 24 |
views | Maximum views (1-1000) | 1 |
description | Secret description (255 chars max) | description="DB credentials" |
message | Viewer message (255 chars max) | message="Use carefully" |
password | Additional protection (4-100 chars) | password="secret123" |
captcha | Enable CAPTCHA verification | captcha=True |
otp_email | OTP via email (valid format) | otp_email="[email protected]" |
otp_phone | OTP via SMS (international format) | otp_phone="+33674747474" |
ip_whitelist | Allowed IPs (255 chars max) | ip_whitelist="203.0.113.5,198.51.100.10" |
geolocation | Allowed countries (255 chars max) | geolocation="FR,US,DE" |
attachments | File paths list (10 files, 10MB max) | attachments=["file1.pdf", "file2.docx"] |
Security Priority
If multiple security options are specified, only the highest level is applied:captcha
< password
< otp_email
< otp_phone
(highest)
Example: password="secret", captcha=True, otp_phone="+33123456789"
→ Only OTP phone will be used
Configuration
Parameter | Description | Example |
---|---|---|
token | API token (required) | SharokeyClient(token='abcd1234...') |
timeout | Request timeout in seconds | SharokeyClient(timeout=60) |
Output Format
All methods return JSON objects (same structure as CLI JSON output).
Examples
Basic Usage
import asyncio
from sharokey import SharokeyClient
async def main():
client = SharokeyClient(token='your-token')
# Simple secret
secret = await client.create("Database password: admin123", 24, 1)
print('Share URL:', secret['data']['share_url'])
# With description and message
secret2 = await client.create(
"API credentials",
48, # hours
3, # views
description="Production API access",
message="Valid until project end"
)
# CAPTCHA protection
secret3 = await client.create(
"Server access",
12, # Expiration hours
1, # Maximum views
captcha=True
)
# Password protection
secret4 = await client.create(
"Sensitive data",
6, # Expiration hours
2, # Maximum views
password="mySecretPass123"
)
# OTP email protection (higher priority than password)
secret5 = await client.create(
"Bank details",
24, # Expiration hours
1, # Maximum views
password="backup",
otp_email="[email protected]"
)
# OTP SMS protection (highest priority - will override all others)
secret6 = await client.create(
"Critical access",
2, # Expiration hours
1, # Maximum views
password="backup",
captcha=True,
otp_email="[email protected]",
otp_phone="+33674747474"
)
# IP restriction
secret7 = await client.create(
"External access",
48, # Expiration hours
10, # Maximum views
ip_whitelist="203.0.113.5,198.51.100.10"
)
# Geolocation restriction
secret8 = await client.create(
"EU only data",
72, # Expiration hours
5, # Maximum views
geolocation="FR,DE,BE,IT,ES"
)
# Combined restrictions
secret9 = await client.create(
"Restricted access",
24, # Expiration hours
2, # Maximum views
password="secure123",
ip_whitelist="203.0.113.100",
geolocation="FR,US"
)
asyncio.run(main())
File Attachments
import asyncio
from pathlib import Path
from sharokey import SharokeyClient
async def share_files():
client = SharokeyClient(token='your-token')
# Single attachment
secret = await client.create(
"Contract files",
48, # Expiration hours
5, # Maximum views
description="Client XYZ documents",
attachments=["contract.pdf"]
)
# Multiple attachments
secret2 = await client.create(
"Project bundle",
72, # Expiration hours
3, # Maximum views
description="Complete project files",
attachments=[
"contract.pdf",
"terms.pdf",
"specifications.docx",
"budget.xlsx"
]
)
# Multiple attachments with security
secret3 = await client.create(
"Confidential reports",
168, # Expiration hours (1 week)
3, # Maximum views
attachments=[
"report.pdf",
"data.xlsx",
"summary.docx"
],
password="reports2024",
ip_whitelist="203.0.113.50,198.51.100.25"
)
print(f"Files shared: {secret['data']['share_url']}")
print(f"Attachments: {secret['data']['attachments_count']} files")
asyncio.run(share_files())
Secret Requests
import asyncio
from sharokey import SharokeyClient
async def request_workflow():
client = SharokeyClient(token='your-token')
# Create request with email delivery (JSON output by default - direct API response)
request = await client.create_request(
message="Please share VPN credentials",
email_to="[email protected]",
email_reply="[email protected]",
request_expiration_hours=48,
secret_expiration_hours=24,
maximum_views=3,
locale="fr"
)
print('Request URL:', request['data']['request']['url'])
# Get request details by token (JSON by default - direct API response)
request_details = await client.get_request('abc123token456')
# List requests with filters (JSON by default - direct API response)
requests = await client.list_requests(
status='active',
limit=20
)
# Expire request by token (cancels and makes it inactive)
await client.delete_request('abc123token456')
# View request statistics (JSON only - direct API response)
stats = await client.request_stats()
# Request parameters: secret_expiration_hours (1-8760), request_expiration_hours (1-8760), maximum_views (1-1000)
# Email fields: email_to and email_reply (valid email format required)
# Locale: "en" or "fr" - sets email language when sending notifications
asyncio.run(request_workflow())
Management
import asyncio
from sharokey import SharokeyClient
async def management_examples():
client = SharokeyClient(token='your-token')
# List all secrets
all_secrets = await client.list()
# List with filters
filtered = await client.list(
status='active',
creator='[email protected]',
limit=20
)
# JSON output (default)
secrets = await client.list(limit=5)
# Output: {"success": true, "data": {"items": [{"slug": "ABC123", "maximum_views": 1, ...}]}}
# Get secret details
secret = await client.get('ABC123')
# Expire secret (clears content, forces expiration)
await client.delete('ABC123')
# Statistics
stats = await client.stats()
print(f"Total secrets: {stats['data']['total_secrets']}")
print(f"Active: {stats['data']['active_secrets']}")
asyncio.run(management_examples())
Limits & Constraints
Content & Text
- Secret content: 255 characters max (before encryption)
- Description: 255 characters max
- Message: 255 characters max
- Password: 4-100 characters
- IP whitelist: 255 characters max (public IPs only, comma-separated)
- Geolocation: 255 characters max (ISO country codes)
Attachments
- Maximum files: 10 per secret
- Total size: 10MB across all files
- Supported formats: Documents, Images, Audio, Video, Archives
- Encryption: Files encrypted client-side before upload
Time & Access
- Expiration: 1-8760 hours
- Maximum views: 1-1000 views
Security
Zero Knowledge Architecture
- Client-side encryption: AES-GCM-256 with PBKDF2 (10,000 iterations)
- Split keys: KeyA (sent to server) + KeyB (in URL fragment)
- No server access: Server cannot decrypt secrets
- Perfect Forward Secrecy: Keys never stored server-side
Best Practices
- Use short expiration times for sensitive data
- Limit view counts appropriately
- Choose appropriate security level: OTP phone (highest) > OTP email > password > CAPTCHA
- Combine with IP restrictions and geo restrictions for access control
- Only the highest security level will be applied if multiple are specified
Python Requirements
- Python: 3.7+
- aiohttp: For async HTTP requests
- cryptography: For encryption operations
Utilities
Connectivity Test
import asyncio
from sharokey import SharokeyClient
async def test_examples():
client = SharokeyClient(token='your-token')
# Simple test (boolean)
is_connected = await client.test_connection()
print('Connected:', is_connected)
# Detailed test (like CLI)
results = await client.test()
print(f"Tests passed: {results['passed']}/{results['total']}")
for detail in results['details']:
status = "✅" if detail['success'] else "❌"
print(f" {status} {detail['name']}: {detail['message']}")
# Health check
health = await client.health()
print('API Status:', health.get('status', 'unknown'))
# Configuration info
config = client.get_config()
print(f"API URL: {config['api_url']}")
print(f"Timeout: {config['timeout']}s")
print(f"Has token: {config['has_token']}")
asyncio.run(test_examples())
Error Handling
import asyncio
from sharokey import (
SharokeyClient,
SharokeyError,
AuthenticationError,
ValidationError,
NotFoundError,
AttachmentError,
NetworkError
)
async def error_examples():
client = SharokeyClient(token='your-token')
try:
secret = await client.create("test secret", 24, 1)
print('Success:', secret['data']['slug'])
except ValidationError as e:
print(f"Validation error: {e}")
# Invalid parameters (empty content, hours/views out of range, etc.)
except AuthenticationError as e:
print(f"Authentication error: {e}")
# Invalid token or authentication failed
except AttachmentError as e:
print(f"File error: {e}")
# File not found, too large, processing failed
except NotFoundError as e:
print(f"Not found error: {e}")
# Secret or request not found
except NetworkError as e:
print(f"Network error: {e}")
# Timeout, rate limit, server errors
except SharokeyError as e:
print(f"Sharokey error: {e}")
# Any other API errors
# Validation examples
async def validation_examples():
client = SharokeyClient(token='your-token')
try:
await client.create("", 24, 1) # Empty content
except ValidationError:
print("Empty content not allowed")
try:
await client.create("test", 0, 1) # Invalid hours
except ValidationError:
print("Hours must be between 1 and 8760")
try:
await client.create("test", 24, 0) # Invalid views
except ValidationError:
print("Views must be between 1 and 1000")
asyncio.run(error_examples())
Test & Diagnostics
Connectivity Test
The test()
method performs comprehensive client-side diagnostics:
# Full connectivity test (6 tests)
results = await client.test()
# Quick health check
health = await client.health()
Test Details:
- Configuration - Validates API token presence
- Network - Tests server connectivity via health endpoint
- Authentication - Verifies token validity with API
- Read Access - Tests secrets listing permissions
- Write Access - Verifies secret creation capabilities
- Statistics - Tests analytics endpoint access
Output Format:
- JSON response with detailed test results
- Boolean success indicators for each test
Test Method Details
The test()
method performs comprehensive client-side diagnostics including server health verification, authentication validation, and permission checks. This goes beyond a simple server status check to ensure full functionality.
Troubleshooting
Common issues and solutions:
- "Token is required": Initialize with
SharokeyClient(token='your-token')
- "ValidationError: Content is required": Provide non-empty content string
- "ValidationError: Hours must be between 1 and 8760": Use valid expiration hours
- "AttachmentError: File not found": Verify file paths exist and are readable
- "AttachmentError: Total attachments size too large": Keep files under 10MB total
- "AuthenticationError: Invalid token": Check your API token is correct and active
- "NetworkError: Request timeout": Increase timeout or check network connection
Related Resources
- CLI Documentation - Command-line interface reference
- JavaScript CDN - Lightweight browser version
- Response Structures - Complete JSON response documentation
- Feature Comparison - Compare all Sharokey libraries
Sharokey provides the most comprehensive Python SDK for secure secret sharing with full async/await support and Zero Knowledge encryption. 🔐