Skip to content

Python SDK

The official Python SDK for Cohera provides a type-safe, async-ready interface to the Cohera API.

PyPI versionPython versionsLicense
Terminal window
pip install cohera
Terminal window
# Async support
pip install cohera[async]
# Pandas integration
pip install cohera[pandas]
# All extras
pip install cohera[all]
from cohera import Cohera
# Initialize the client
client = Cohera(api_key="ck_live_...")
# List certificates
certificates = client.certificates.list()
for cert in certificates:
print(f"{cert.name} - Expires: {cert.expiry_date}")
from cohera import Cohera
# Via environment variable (recommended)
import os
os.environ["COHERA_API_KEY"] = "ck_live_..."
client = Cohera()
# Via constructor
client = Cohera(api_key="ck_live_...")
from cohera import Cohera
client = Cohera(
api_key="ck_live_...",
base_url="https://api.cohera.io", # Custom base URL
timeout=30.0, # Request timeout in seconds
max_retries=3, # Retry failed requests
debug=True, # Enable debug logging
)
# List all certificates
certificates = client.certificates.list()
# List with filters
certificates = client.certificates.list(
supplier_id="sup_abc123",
status="active",
expires_before="2024-12-31"
)
# Paginate results
for page in client.certificates.list_pages(page_size=50):
for cert in page:
print(cert.name)
# Get a single certificate
cert = client.certificates.get("cert_abc123")
# Get with relationships
cert = client.certificates.get(
"cert_abc123",
include=["supplier", "components", "products"]
)
# Create a certificate
cert = client.certificates.create(
name="CoA - Batch 2024-001",
supplier_id="sup_abc123",
certificate_type="coa",
expiry_date="2025-06-30",
document_url="https://..."
)
# Update a certificate
cert = client.certificates.update(
"cert_abc123",
status="expired"
)
# Delete a certificate
client.certificates.delete("cert_abc123")
# List suppliers
suppliers = client.suppliers.list()
# Search suppliers
suppliers = client.suppliers.search("Acme")
# Get supplier with certificates
supplier = client.suppliers.get(
"sup_abc123",
include=["certificates", "components"]
)
# Create supplier
supplier = client.suppliers.create(
name="Acme Chemicals",
email="contact@acme.com",
status="approved"
)
# List components
components = client.components.list()
# Get component with full graph
component = client.components.get(
"comp_abc123",
include=["supplier", "certificates", "products", "bom"]
)
# Find components by certificate
components = client.components.list(certificate_id="cert_abc123")
# List products
products = client.products.list()
# Get product with BOM
product = client.products.get(
"prod_abc123",
include=["bom", "components", "certificates"]
)
# Impact analysis - find products affected by a certificate
products = client.products.list(affected_by_certificate="cert_abc123")

The SDK provides full async support for high-performance applications:

import asyncio
from cohera import AsyncCohera
async def main():
client = AsyncCohera(api_key="ck_live_...")
# Concurrent requests
certificates, suppliers = await asyncio.gather(
client.certificates.list(),
client.suppliers.list()
)
# Async iteration
async for cert in client.certificates.list_async():
print(cert.name)
# Async context manager
async with AsyncCohera() as client:
cert = await client.certificates.get("cert_abc123")
asyncio.run(main())

The SDK is fully typed with Pydantic models:

from cohera import Cohera
from cohera.types import Certificate, Supplier
client = Cohera()
# Full IDE autocomplete and type checking
cert: Certificate = client.certificates.get("cert_abc123")
print(cert.name) # str
print(cert.expiry_date) # datetime
print(cert.supplier) # Supplier
# Type hints for create/update
client.certificates.create(
name="Test", # Required
supplier_id="sup_...", # Required
status="active", # Literal["active", "expired", "pending"]
)

Export data directly to Pandas DataFrames:

from cohera import Cohera
client = Cohera()
# Get certificates as DataFrame
df = client.certificates.to_dataframe()
print(df.head())
# With filters
df = client.certificates.to_dataframe(
supplier_id="sup_abc123",
columns=["name", "expiry_date", "supplier.name"]
)
# Export to CSV
df.to_csv("certificates.csv", index=False)
from cohera import Cohera
from cohera.exceptions import (
CoheraError,
AuthenticationError,
NotFoundError,
RateLimitError,
ValidationError,
)
client = Cohera()
try:
cert = client.certificates.get("cert_invalid")
except NotFoundError as e:
print(f"Certificate not found: {e.message}")
except RateLimitError as e:
print(f"Rate limited. Retry after: {e.retry_after} seconds")
except AuthenticationError as e:
print(f"Auth failed: {e.message}")
except ValidationError as e:
print(f"Validation error: {e.errors}")
except CoheraError as e:
print(f"API error: {e.message}")

Verify and parse webhook payloads:

from cohera.webhooks import Webhook
webhook = Webhook(secret="whsec_...")
# Verify and parse
try:
event = webhook.construct_event(
payload=request.body,
signature=request.headers["X-Cohera-Signature"]
)
if event.type == "certificate.expiring":
cert = event.data
print(f"Certificate {cert.name} expires on {cert.expiry_date}")
except webhook.SignatureVerificationError:
print("Invalid signature")
import logging
from cohera import Cohera
# Enable debug logging
logging.basicConfig(level=logging.DEBUG)
client = Cohera(debug=True)
# Custom logger
logger = logging.getLogger("my_app")
client = Cohera(logger=logger)

Use the mock client for testing:

from cohera.testing import MockCohera
def test_certificate_processing():
client = MockCohera()
# Configure mock responses
client.certificates.mock_list([
{"id": "cert_1", "name": "Test Cert", "status": "active"}
])
# Test your code
certs = client.certificates.list()
assert len(certs) == 1
assert certs[0].name == "Test Cert"
from datetime import datetime, timedelta
from cohera import Cohera
client = Cohera()
# Find certificates expiring in 30 days
threshold = datetime.now() + timedelta(days=30)
expiring = client.certificates.list(
status="active",
expires_before=threshold.isoformat()
)
for cert in expiring:
days_left = (cert.expiry_date - datetime.now()).days
print(f"[{days_left} days] {cert.name} - {cert.supplier.name}")
from cohera import Cohera
client = Cohera()
# Get certificate with full impact graph
cert = client.certificates.get(
"cert_abc123",
include=["components", "products"]
)
print(f"Certificate: {cert.name}")
print(f"Affects {len(cert.components)} components:")
for component in cert.components:
print(f" - {component.name}")
for product in component.products:
print(f" -> {product.name} ({product.sku})")

For complete API documentation, see: