Skip to main content

Audit Trail SDK for Python

Official Python SDK for Audit Trail Universal.

Installation

pip install audit-trail-sdk

Quick Start

from audit_trail_sdk import (
    AuditTrailClient,
    Actor,
    Action,
    Resource,
    EventMetadata,
    Event,
)

# Create client
client = (
    AuditTrailClient.builder()
    .server_url("https://audit.example.com")
    .api_key("your-api-key")
    .build()
)

# Log an event (sync)
response = client.log(
    Event.create(
        actor=Actor.user("user-123", "John Doe"),
        action=Action.create("Created document"),
        resource=Resource.document("doc-456", "Q4 Report"),
        metadata=EventMetadata.create("web-app", "tenant-001"),
    )
)

print(f"Event logged: {response.id}")

Async Usage

import asyncio

async def main():
    client = (
        AuditTrailClient.builder()
        .server_url("https://audit.example.com")
        .api_key("your-api-key")
        .build()
    )

    event = Event.create(
        actor=Actor.user("user-123", "John Doe"),
        action=Action.create("Created document"),
        resource=Resource.document("doc-456", "Q4 Report"),
        metadata=EventMetadata.create("web-app", "tenant-001"),
    )

    response = await client.log_async(event)
    print(f"Event logged async: {response.id}")

asyncio.run(main())

Features

  • Python 3.10+ support
  • Full type hints with Pydantic
  • Sync and async API
  • Automatic retry with exponential backoff
  • Factory methods for common models
  • Builder pattern for client configuration

API Reference

Client Configuration

client = (
    AuditTrailClient.builder()
    .server_url("http://localhost:8080")  # Required
    .api_key("your-api-key")              # Optional
    .timeout(30.0)                        # Default: 30 seconds
    .retry_attempts(3)                    # Default: 3
    .retry_delay(1.0)                     # Default: 1 second
    .headers({"X-Custom": "value"})       # Optional custom headers
    .build()
)

Logging Events

Single Event

response = client.log(event)
# Response: EventResponse(id, timestamp, hash, status)

# Async version
response = await client.log_async(event)

Batch Events

response = client.log_batch([event1, event2, event3])
# Response: BatchEventResponse(total, succeeded, failed, events, errors)

# Async version
response = await client.log_batch_async([event1, event2, event3])

Building Events

Actor Types

# Factory methods
user = Actor.user("user-123", "John Doe")
system = Actor.system("cron-job")
service = Actor.service("payment-svc", "Payment Service")

# Full constructor
actor = Actor(
    id="user-123",
    type=ActorType.USER,
    name="John Doe",
    ip="192.168.1.1",
    user_agent="Mozilla/5.0...",
    attributes={"department": "IT"},
)

Action Types

# Factory methods
create = Action.create("Created resource")
read = Action.read("Viewed resource")
update = Action.update("Modified resource")
delete = Action.delete("Removed resource")
login = Action.login()
logout = Action.logout()

# Custom action
custom = Action.of("APPROVE", "Approved request", "WORKFLOW")

Resource Types

# Factory methods
doc = Resource.document("doc-123", "Report")
user = Resource.user("user-456", "John")
txn = Resource.transaction("txn-789", "Payment")
custom = Resource.of("id", "CUSTOM_TYPE", "Name")

# With before/after state
resource = (
    Resource.document("doc-123", "Report")
    .with_before({"status": "draft"})
    .with_after({"status": "published"})
)

Metadata

metadata = EventMetadata.create(
    source="web-app",           # Required
    tenant_id="tenant-001",     # Required
    correlation_id="corr-123",  # Optional
    session_id="sess-456",      # Optional
    tags={"env": "production"}, # Optional
)

Searching Events

Advanced Search

from audit_trail_sdk import SearchCriteria

criteria = SearchCriteria(
    tenant_id="tenant-001",      # Required
    actor_id="user-123",         # Optional
    actor_type="USER",           # Optional
    action_type="CREATE",        # Optional
    resource_id="doc-456",       # Optional
    resource_type="DOCUMENT",    # Optional
    from_date="2024-01-01",      # Optional
    to_date="2024-12-31",        # Optional
    query="search term",         # Optional
    page=0,                      # Default: 0
    size=20,                     # Default: 20
)

result = client.search(criteria)
# Result: SearchResult(items, total_count, page, size, total_pages)

# Async version
result = await client.search_async(criteria)

Quick Search

result = client.quick_search("search term", "tenant-001", page=0, size=20)

# Async version
result = await client.quick_search_async("search term", "tenant-001")

Retrieving Events

event = client.get_by_id("event-id")
# Returns None if not found

# Async version
event = await client.get_by_id_async("event-id")

Error Handling

from audit_trail_sdk import (
    AuditTrailError,
    AuditTrailConnectionError,
    AuditTrailApiError,
    AuditTrailValidationError,
)

try:
    response = client.log(event)
except AuditTrailConnectionError as e:
    print(f"Connection failed: {e}")
    print(f"Cause: {e.cause}")
except AuditTrailApiError as e:
    print(f"API error: {e.status_code}")
    print(f"Body: {e.body}")
except AuditTrailValidationError as e:
    print(f"Validation errors: {e.violations}")
except AuditTrailError as e:
    print(f"General error: {e}")

Development

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run linter
ruff check src/

# Type check
mypy src/

License

MIT

Metadata

Release files for audit-trail-sdk 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for audit-trail-sdk 1.0.0
File Size Uploaded Provenance
audit_trail_sdk-1.0.0.tar.gz 8.0 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for audit-trail-sdk 1.0.0
File Interpreter ABI Platform
audit_trail_sdk-1.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 18.2 kB

Release files / audit_trail_sdk-1.0.0.tar.gz

Download URL audit_trail_sdk-1.0.0.tar.gz
Size 8.0 kB
Tags Source
SHA-256 checksum
How to use checksums
243f4677a003d85cd7738cd3318e94e2a5c0cb5b20a21f0d9d6af0182415f40a
BLAKE2b-256 checksum
How to use checksums
f97003a6f77e20e3b04d7db83d640807b94639c8d3b162769e4cb36c41472669
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 29, 2025.

Transparency log

Release files / audit_trail_sdk-1.0.0-py3-none-any.whl

Download URL audit_trail_sdk-1.0.0-py3-none-any.whl
Size 10.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3e62f3abad2b832f8af2396f77c79df9827b2c1a4be9763dfae387f7ed9551f8
BLAKE2b-256 checksum
How to use checksums
8323c086dae9a03b9a744eaba71b9055d4a2b0cfceea7ae727f374ef67082b24
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 29, 2025.

Transparency log

Security for audit-trail-sdk 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for audit_trail_sdk-1.0.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 29, 2025.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page