Skip to main content

Python SDK

Python client libraries for Staqr and Commerce APIs with full type hints, async support, and Pythonic interfaces.

Requirements

  • Python 3.9+
  • pip or poetry

Installation

SDKs are currently distributed as local packages. They will be published to PyPI in a future release.

# From your project root
pip install ./sdks/commerce-v1-python

Commerce API v0 (Legacy)

pip install ./sdks/commerce-v0-python

Staqr Platform API

pip install ./sdks/staqr-python

Using Poetry

poetry add ./sdks/commerce-v1-python

Quick Start

Basic Configuration

import os
import staqr_commerce_v1
from staqr_commerce_v1 import Configuration, ApiClient, CustomerManagementApi

# Create configuration
config = Configuration()
config.host = "https://commerce.staqr.com/api"
config.access_token = os.environ.get("COMMERCE_API_TOKEN")

# Use API client
with ApiClient(config) as client:
api = CustomerManagementApi(client)
customers = api.list_customers()
print(customers)

Environment-Based Configuration

import os
from staqr_commerce_v1 import Configuration, ApiClient

def get_config():
config = Configuration()
config.host = os.environ.get("COMMERCE_BASE_URL", "https://commerce.staqr.com/api")
config.access_token = os.environ.get("COMMERCE_API_TOKEN")

# Optional: Add custom headers
config.default_headers = {
"X-Tenant": os.environ.get("COMMERCE_TENANT", "PRVIDR")
}

return config

Examples

List Customers

import os
from staqr_commerce_v1 import Configuration, ApiClient, CustomerManagementApi

def list_all_customers():
config = Configuration()
config.host = "https://commerce.staqr.com/api"
config.access_token = os.environ.get("COMMERCE_API_TOKEN")

with ApiClient(config) as client:
api = CustomerManagementApi(client)

try:
response = api.list_customers()
print(f"Found {len(response)} customers")
return response
except Exception as e:
print(f"Failed to list customers: {e}")
raise

if __name__ == "__main__":
customers = list_all_customers()

Create a Customer

import os
from staqr_commerce_v1 import (
Configuration,
ApiClient,
CustomerManagementApi,
CustomerDto
)

def create_customer(code: str, description: str, seller: str = "PRVIDR"):
config = Configuration()
config.host = "https://commerce.staqr.com/api"
config.access_token = os.environ.get("COMMERCE_API_TOKEN")

with ApiClient(config) as client:
api = CustomerManagementApi(client)

customer = CustomerDto(
code=code,
description=description,
customer_category="DEFAULT",
seller=seller
)

response = api.create_customer(customer_dto=customer)
print(f"Customer created: {response.code}")
return response

# Usage
create_customer("CUST-001", "Example Customer")

Work with Subscriptions

from staqr_commerce_v1 import (
Configuration,
ApiClient,
SubscriptionApi,
SubscriptionDto
)

def create_subscription(
code: str,
user_account: str,
offer_template: str
):
config = Configuration()
config.host = "https://commerce.staqr.com/api"
config.access_token = os.environ.get("COMMERCE_API_TOKEN")

with ApiClient(config) as client:
api = SubscriptionApi(client)

subscription = SubscriptionDto(
code=code,
user_account=user_account,
offer_template=offer_template
)

response = api.create_subscription(subscription_dto=subscription)
return response

Handle Invoices

from staqr_commerce_v1 import Configuration, ApiClient, InvoiceApi

def get_invoice(invoice_number: str):
config = Configuration()
config.host = "https://commerce.staqr.com/api"
config.access_token = os.environ.get("COMMERCE_API_TOKEN")

with ApiClient(config) as client:
api = InvoiceApi(client)
response = api.get_invoice(invoice_number=invoice_number)
return response

def download_invoice_pdf(invoice_number: str, output_path: str):
config = Configuration()
config.host = "https://commerce.staqr.com/api"
config.access_token = os.environ.get("COMMERCE_API_TOKEN")

with ApiClient(config) as client:
api = InvoiceApi(client)
pdf_data = api.get_invoice_pdf(invoice_number=invoice_number)

with open(output_path, "wb") as f:
f.write(pdf_data)

print(f"Invoice saved to {output_path}")

Error Handling

Using Try/Except

from staqr_commerce_v1 import Configuration, ApiClient, CustomerManagementApi
from staqr_commerce_v1.rest import ApiException

def safe_api_call():
config = Configuration()
config.host = "https://commerce.staqr.com/api"
config.access_token = os.environ.get("COMMERCE_API_TOKEN")

with ApiClient(config) as client:
api = CustomerManagementApi(client)

try:
customers = api.list_customers()
return {"success": True, "data": customers}

except ApiException as e:
status = e.status

if status == 401:
print("Authentication failed - check API token")
elif status == 403:
print("Access denied - insufficient permissions")
elif status == 404:
print("Resource not found")
elif status == 429:
print("Rate limited - slow down requests")
else:
print(f"API error: {status} - {e.body}")

return {"success": False, "error": str(e)}

except Exception as e:
print(f"Network error: {e}")
return {"success": False, "error": str(e)}

Custom Exception Handling

from staqr_commerce_v1.rest import ApiException

class CommerceApiError(Exception):
def __init__(self, message: str, status_code: int, response_body: str):
super().__init__(message)
self.status_code = status_code
self.response_body = response_body

def api_call_with_custom_error():
try:
# ... API call
pass
except ApiException as e:
raise CommerceApiError(
message=f"API request failed: {e.reason}",
status_code=e.status,
response_body=e.body
)

Type Hints

The SDK includes full type hints for IDE support and type checking.

Using Models

from typing import List
from staqr_commerce_v1 import (
CustomerDto,
SubscriptionDto,
InvoiceDto,
BillingAccountDto
)

def process_customers(customers: List[CustomerDto]) -> None:
for customer in customers:
# IDE autocomplete works here
print(f"Customer: {customer.code} - {customer.description}")

def create_typed_customer() -> CustomerDto:
return CustomerDto(
code="CUST-001",
description="Typed Customer",
customer_category="DEFAULT",
seller="PRVIDR"
)

Type Checking with mypy

# Install mypy
pip install mypy

# Run type checking
mypy your_script.py

Configuration Options

from staqr_commerce_v1 import Configuration

config = Configuration()

# API base URL
config.host = "https://commerce.staqr.com/api"

# Authentication token
config.access_token = "your-api-token"

# Custom headers
config.default_headers = {
"X-Tenant": "PRVIDR",
"X-Request-ID": "unique-id"
}

# SSL verification (disable for self-signed certs in dev)
config.verify_ssl = True # Always True in production!

# Connection timeouts (seconds)
config.timeout = 30

# Proxy configuration
config.proxy = "http://proxy.example.com:8080"

# Debug mode (logs all requests/responses)
config.debug = False # Set True for troubleshooting

Async Support

For async/await support, use the async client:

import asyncio
from staqr_commerce_v1 import Configuration, ApiClient, CustomerManagementApi

async def list_customers_async():
config = Configuration()
config.host = "https://commerce.staqr.com/api"
config.access_token = os.environ.get("COMMERCE_API_TOKEN")

async with ApiClient(config) as client:
api = CustomerManagementApi(client)
customers = await api.list_customers_async()
return customers

# Run async function
customers = asyncio.run(list_customers_async())

Best Practices

1. Use Environment Variables

import os

# Never hardcode credentials
config.access_token = os.environ.get("COMMERCE_API_TOKEN")

# Or use dotenv for local development
from dotenv import load_dotenv
load_dotenv()

2. Use Context Managers

# Always use 'with' to properly close connections
with ApiClient(config) as client:
api = CustomerManagementApi(client)
# ... use api
# Connection automatically closed

3. Create Reusable Modules

# api/commerce.py
import os
from staqr_commerce_v1 import Configuration, ApiClient, CustomerManagementApi, InvoiceApi

def get_config() -> Configuration:
config = Configuration()
config.host = os.environ.get("COMMERCE_BASE_URL", "https://commerce.staqr.com/api")
config.access_token = os.environ.get("COMMERCE_API_TOKEN")
return config

def get_customer_api() -> CustomerManagementApi:
return CustomerManagementApi(ApiClient(get_config()))

def get_invoice_api() -> InvoiceApi:
return InvoiceApi(ApiClient(get_config()))

4. Handle Rate Limiting with Retry

import time
from staqr_commerce_v1.rest import ApiException

def with_retry(fn, max_retries=3):
for attempt in range(1, max_retries + 1):
try:
return fn()
except ApiException as e:
if e.status == 429 and attempt < max_retries:
retry_after = int(e.headers.get("Retry-After", 1))
print(f"Rate limited. Retrying in {retry_after}s...")
time.sleep(retry_after)
continue
raise
raise Exception("Max retries exceeded")

# Usage
customers = with_retry(lambda: api.list_customers())

Available API Classes

Commerce v1

ClassDescription
CustomerManagementApiCustomer CRUD, search, hierarchy
SubscriptionApiSubscription lifecycle management
InvoiceApiInvoice operations and PDF
PaymentApiPayment processing
OrderApiOrder management
BillingAccountApiBilling account operations
WalletApiWallet and balance operations

Commerce v0 (Legacy)

Contains 100+ API classes covering all legacy endpoints. See sdks/commerce-v0-python/docs/ for complete list.

Staqr Platform

ClassDescription
FlowsApiFlow management and execution
ConnectionsApiIntegration credentials
FoldersApiResource organization
UsersApiUser management

Troubleshooting

"ModuleNotFoundError: No module named 'staqr_commerce_v1'"

Cause: SDK not installed correctly.

Fix:

# Verify SDK exists
ls ./sdks/commerce-v1-python/

# Install with pip
pip install ./sdks/commerce-v1-python

# Verify installation
python -c "import staqr_commerce_v1; print('OK')"

"401 Unauthorized"

Cause: Invalid or expired API token.

Fix:

  1. Verify token in environment variable:
    echo $COMMERCE_API_TOKEN
  2. Check token has required permissions
  3. Ensure token is for correct environment

SSL Certificate Errors

Cause: Self-signed certificates or corporate proxy.

Fix (development only):

config.verify_ssl = False  # NEVER in production!

Better fix:

# Add corporate CA to Python's certificate store
export REQUESTS_CA_BUNDLE=/path/to/corporate-ca.crt

Next Steps