Python SDK
The official Python SDK for Cohera provides a type-safe, async-ready interface to the Cohera API.
Installation
Section titled “Installation”pip install coheraWith Optional Dependencies
Section titled “With Optional Dependencies”# Async supportpip install cohera[async]
# Pandas integrationpip install cohera[pandas]
# All extraspip install cohera[all]Quick Start
Section titled “Quick Start”from cohera import Cohera
# Initialize the clientclient = Cohera(api_key="ck_live_...")
# List certificatescertificates = client.certificates.list()
for cert in certificates: print(f"{cert.name} - Expires: {cert.expiry_date}")Configuration
Section titled “Configuration”Authentication
Section titled “Authentication”from cohera import Cohera
# Via environment variable (recommended)import osos.environ["COHERA_API_KEY"] = "ck_live_..."client = Cohera()
# Via constructorclient = Cohera(api_key="ck_live_...")from cohera import Cohera
client = Cohera(access_token="eyJ...")Client Options
Section titled “Client Options”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)Resources
Section titled “Resources”Certificates
Section titled “Certificates”# List all certificatescertificates = client.certificates.list()
# List with filterscertificates = client.certificates.list( supplier_id="sup_abc123", status="active", expires_before="2024-12-31")
# Paginate resultsfor page in client.certificates.list_pages(page_size=50): for cert in page: print(cert.name)
# Get a single certificatecert = client.certificates.get("cert_abc123")
# Get with relationshipscert = client.certificates.get( "cert_abc123", include=["supplier", "components", "products"])
# Create a certificatecert = 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 certificatecert = client.certificates.update( "cert_abc123", status="expired")
# Delete a certificateclient.certificates.delete("cert_abc123")Suppliers
Section titled “Suppliers”# List supplierssuppliers = client.suppliers.list()
# Search supplierssuppliers = client.suppliers.search("Acme")
# Get supplier with certificatessupplier = client.suppliers.get( "sup_abc123", include=["certificates", "components"])
# Create suppliersupplier = client.suppliers.create( name="Acme Chemicals", email="contact@acme.com", status="approved")Components
Section titled “Components”# List componentscomponents = client.components.list()
# Get component with full graphcomponent = client.components.get( "comp_abc123", include=["supplier", "certificates", "products", "bom"])
# Find components by certificatecomponents = client.components.list(certificate_id="cert_abc123")Products
Section titled “Products”# List productsproducts = client.products.list()
# Get product with BOMproduct = client.products.get( "prod_abc123", include=["bom", "components", "certificates"])
# Impact analysis - find products affected by a certificateproducts = client.products.list(affected_by_certificate="cert_abc123")Async Support
Section titled “Async Support”The SDK provides full async support for high-performance applications:
import asynciofrom 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())Type Safety
Section titled “Type Safety”The SDK is fully typed with Pydantic models:
from cohera import Coherafrom cohera.types import Certificate, Supplier
client = Cohera()
# Full IDE autocomplete and type checkingcert: Certificate = client.certificates.get("cert_abc123")print(cert.name) # strprint(cert.expiry_date) # datetimeprint(cert.supplier) # Supplier
# Type hints for create/updateclient.certificates.create( name="Test", # Required supplier_id="sup_...", # Required status="active", # Literal["active", "expired", "pending"])Pandas Integration
Section titled “Pandas Integration”Export data directly to Pandas DataFrames:
from cohera import Cohera
client = Cohera()
# Get certificates as DataFramedf = client.certificates.to_dataframe()print(df.head())
# With filtersdf = client.certificates.to_dataframe( supplier_id="sup_abc123", columns=["name", "expiry_date", "supplier.name"])
# Export to CSVdf.to_csv("certificates.csv", index=False)Error Handling
Section titled “Error Handling”from cohera import Coherafrom 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}")Webhooks
Section titled “Webhooks”Verify and parse webhook payloads:
from cohera.webhooks import Webhook
webhook = Webhook(secret="whsec_...")
# Verify and parsetry: 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")Logging
Section titled “Logging”import loggingfrom cohera import Cohera
# Enable debug logginglogging.basicConfig(level=logging.DEBUG)
client = Cohera(debug=True)
# Custom loggerlogger = logging.getLogger("my_app")client = Cohera(logger=logger)Testing
Section titled “Testing”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"Examples
Section titled “Examples”Certificate Expiry Monitor
Section titled “Certificate Expiry Monitor”from datetime import datetime, timedeltafrom cohera import Cohera
client = Cohera()
# Find certificates expiring in 30 daysthreshold = 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}")Impact Analysis
Section titled “Impact Analysis”from cohera import Cohera
client = Cohera()
# Get certificate with full impact graphcert = 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})")API Reference
Section titled “API Reference”For complete API documentation, see: