Metadata-Version: 2.5
Name: apisense
Version: 0.1.0
Summary: Lightweight, privacy-first API observability Python SDK
Project-URL: Homepage, https://apisense.co.in
Project-URL: Documentation, https://github.com/Sourav0174/apisense-backend#readme
Project-URL: Repository, https://github.com/Sourav0174/apisense-backend.git
Project-URL: Issues, https://github.com/Sourav0174/apisense-backend/issues
Author-email: APISense Team <info@apisense.co.in>
License: MIT License
        
        Copyright (c) 2026 APISense
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: api,asgi,fastapi,metrics,monitoring,observability,telemetry
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Monitoring
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: build>=1.0.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: ruff>=0.16.0; extra == 'dev'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.100.0; extra == 'fastapi'
Requires-Dist: starlette>=0.27.0; extra == 'fastapi'
Description-Content-Type: text/markdown

# APISense Python SDK

**Lightweight, privacy-first API observability for Python backend applications.**

---

## Overview

The APISense Python SDK provides a strongly typed, production-grade telemetry delivery layer for collecting and streaming request execution metadata to the APISense observability platform.

---

## Installation

Install the package directly from PyPI:

```bash
pip install apisense
```

Or install with FastAPI extras:

```bash
pip install "apisense[fastapi]"
```

### Local Development Installation

For local development from the repository:

```bash
pip install -e .
```

---

## Architecture & Telemetry Delivery

```text
FastAPI / Starlette Application
             │
             ▼
   APISenseMiddleware (ASGI)
             │ (captures latency, method, endpoint, status_code)
             ▼
      TelemetryEvent (Schema-validated, privacy-enforced)
             │
             ▼
    TelemetryCollector (Enabled/Disabled check)
             │
             ▼
  BoundedTelemetryBuffer (Thread-safe FIFO, O(1), Drop-Newest on full)
             │
             ▼
  BackgroundTelemetryWorker (Periodic batch draining & flush loop)
             │
             ▼
     TelemetryHTTPTransport (httpx with connection pooling & retries)
             │
             ▼
  APISense Backend Ingestion API (POST /api/v1/ingest)
```

### Non-Blocking & Reliability Principles
- **Zero application blocking:** Telemetry collection on the request path is a pure $O(1)$ memory insertion (~50ns). All networking runs asynchronously in a dedicated background worker task.
- **Strictly bounded memory:** The in-memory buffer enforces `max_buffer_size` to prevent unbounded memory growth.
- **Drop-Newest on full:** Under heavy traffic spikes or downstream backend downtime, new events are gracefully dropped without raising exceptions.
- **FastAPI failure isolation:** Telemetry capture errors or transport failures are isolated internally and can never modify, delay, or crash your API responses.

---

## Developer Integration with FastAPI

### Standard Integration (Recommended)

```python
from contextlib import asynccontextmanager
from fastapi import FastAPI
from apisense import APISense, APISenseMiddleware

# 1. Initialize the client
apisense = APISense(
    api_key="aps_live_your_project_api_key_here",
    environment="production",
)


# 2. Manage worker lifecycle with FastAPI's modern lifespan
@asynccontextmanager
async def lifespan(app: FastAPI):
    async with apisense:
        yield


# 3. Attach lifespan and middleware
app = FastAPI(lifespan=lifespan)
app.add_middleware(APISenseMiddleware, client=apisense)


@app.get("/users/{user_id}")
async def get_user(user_id: int):
    return {"id": user_id, "name": "Alice"}
```

Alternatively, supply the API key via the `APISENSE_API_KEY` environment variable:

```bash
export APISENSE_API_KEY="aps_live_your_project_api_key_here"
```

```python
apisense = APISense()
```

---

## Configuration Reference

The SDK configuration is strongly typed and immutable (`APISenseConfig`):

| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `api_key` | `str` | *Required* | APISense project API key (must begin with `aps_live_`). |
| `base_url` | `str` | `https://api.apisense.co.in` | Ingestion endpoint URL. |
| `environment` | `str` | `production` | Deployment environment name (`production`, `staging`, `development`). |
| `enabled` | `bool` | `True` | Master switch to toggle telemetry collection on or off. |
| `batch_size` | `int` | `100` | Maximum number of events per ingestion batch. |
| `flush_interval_seconds` | `float` | `5.0` | Time in seconds before buffered events are flushed. |
| `request_timeout_seconds` | `float` | `5.0` | HTTP read/request timeout in seconds. |
| `connect_timeout_seconds` | `float` | `2.0` | HTTP connection timeout in seconds. |
| `max_buffer_size` | `int` | `10000` | In-memory event buffer capacity limit. |
| `max_retries` | `int` | `3` | Maximum retry attempts for transient transmission failures. |
| `retry_backoff_factor` | `float` | `0.5` | Exponential backoff multiplier for retries. |
| `shutdown_timeout_seconds` | `float` | `3.0` | Maximum time to wait for buffer flush during shutdown. |
| `sampling_rate` | `float` | `1.0` | Sampling rate between `0.0` (0%) and `1.0` (100%). |
| `debug` | `bool` | `False` | Enable diagnostic logging for troubleshooting. |

### Security & Secret Masking

- The API key is **never displayed in plain text** in `repr()`, `str()`, or log messages.
- Outbound requests use connection pooling and sanitized error logging.

---

## Telemetry Contract & Privacy Boundary

APISense enforces a strict, privacy-by-design data model. Telemetry events only capture runtime observability metrics.

### Canonical Event Schema (`TelemetryEvent`)

```python
from datetime import UTC, datetime
from apisense import TelemetryEvent

event = TelemetryEvent(
    timestamp=datetime.now(UTC),
    method="GET",
    endpoint="/api/v1/users/{user_id}",
    status_code=200,
    latency_ms=14.5,
    request_id="req_01h8abc123",
    environment="production",
)
```

### Privacy Guarantee

The `TelemetryEvent` data model strictly rejects all sensitive payload fields at the schema layer (`extra="forbid"`):

- ❌ **No request bodies**
- ❌ **No response bodies**
- ❌ **No authorization headers / tokens**
- ❌ **No cookies**
- ❌ **No passwords or secret keys**
- ❌ **No database credentials**
- ❌ **No environment variables**
- ❌ **No arbitrary metadata dictionaries**

---

## Exceptions

The SDK uses a focused exception hierarchy rooted at `APISenseError`:

```text
APISenseError
├── ConfigurationError   # Raised on invalid or missing configuration parameters
└── TelemetryError       # Raised on invalid telemetry event construction or validation
```
