> ## Documentation Index
> Fetch the complete documentation index at: https://developer.keverd.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> keverd — verify and webhooks

# Python SDK

```bash theme={null}
pip install keverd
```

Python 3.9+. Zero runtime dependencies.

## Initialize + verify

```python theme={null}
import os
from keverd import Keverd

keverd = Keverd(secret_key=os.environ["KEVERD_SECRET_KEY"])  # kv_sk_…
result = keverd.verify(event_id)

if result.get("action") == "block":
    ...
elif result.get("action") == "allow":
    ...
```

HTTP under the hood:

```http theme={null}
POST https://api.keverd.com/v2/verify
X-Secret-API-Key: kv_sk_…
Content-Type: application/json
```

```json theme={null}
{
  "event_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}
```

## Verify response (JSON)

`keverd.verify()` returns a dict matching [POST /v2/verify](https://developer.keverd.com/api-reference/verify.md):

```json theme={null}
{
  "event_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "fingerprint": "kvd_…",
  "visitor_id": "kvd_…",
  "risk_score": 42,
  "recommendation": "allow",
  "action": "allow",
  "reason": ["VPN_DETECTED"],
  "reasons": [
    {
      "code": "VPN_DETECTED",
      "explanation": "The connection appears to route through a VPN.",
      "evidence": {}
    }
  ],
  "score": 0.42,
  "trust_score": 70,
  "reputation_score": null,
  "signals": {},
  "detection": {
    "vpn": { "detected": true, "confidence": 0.72, "method": "ip_mismatch" },
    "riskScore": 0.48,
    "riskLevel": "MEDIUM"
  },
  "smart_signals": {
    "vpn_detected": true,
    "action": "allow",
    "risk_score": 42
  },
  "created_at": "2026-07-25T12:00:00Z",
  "country_code": "KE",
  "country_name": "Kenya",
  "page_url": "https://example.com/login",
  "page_origin": "https://example.com",
  "location": { "ip": "203.0.113.10", "country_code": "KE" },
  "ip_info": { "asn": "13335", "asn_name": "Example ISP", "datacenter": false },
  "times_seen": 3,
  "first_seen": "2026-07-01T09:00:00Z",
  "last_seen": "2026-07-25T12:00:00Z",
  "is_new": false,
  "device_history": {
    "times_seen": 3,
    "first_seen": "2026-07-01T09:00:00Z",
    "last_seen": "2026-07-25T12:00:00Z",
    "is_new": false,
    "unique_ip_count": 2,
    "unique_country_count": 1,
    "last_seen_events": []
  }
}
```

## FastAPI

Client → your API (JSON body):

```json theme={null}
{
  "event_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "email": "user@example.com",
  "password": "…"
}
```

```python theme={null}
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from keverd import Keverd

app = FastAPI()
keverd = Keverd(secret_key=os.environ["KEVERD_SECRET_KEY"])


class LoginBody(BaseModel):
    event_id: str
    email: str
    password: str


@app.post("/login")
def login(body: LoginBody):
    risk = keverd.verify(body.event_id)
    if risk.get("action") == "block":
        raise HTTPException(
            status_code=403,
            detail={"error": "Blocked", "reasons": risk.get("reasons")},
        )
    return {
        "ok": True,
        "visitor_id": risk.get("visitor_id"),
        "times_seen": risk.get("times_seen"),
        "is_new": risk.get("is_new"),
    }
```

## Webhooks

Inbound body is the [webhook envelope](https://developer.keverd.com/server/webhooks) (JSON). Verify signature on **raw bytes** first.

```python theme={null}
import os
from fastapi import Request, Response

@app.post("/webhooks/keverd")
async def keverd_webhook(request: Request):
    raw = await request.body()  # raw bytes — do not parse first
    event = keverd.webhooks.construct_event(
        raw,
        request.headers.get("x-keverd-signature", ""),
        os.environ["KEVERD_WEBHOOK_SECRET"],
    )
    if event["type"] == "verification.completed":
        verification = event["data"]["object"]  # same JSON as verify()
    return Response(status_code=200)
```

## Errors

All SDK failures subclass `KeverdError`. Catch the specific type when you need different handling.

### `KeverdError`

Base exception for client-side failures before a successful API response, or when the request never completes.

**Raised when**

* Missing config (e.g. no `secret_key`)
* Invalid arguments (e.g. empty `event_id`)
* Network failures
* Request timeouts

**Attributes:** `args` / message, `code` (`str | None`), `status_code` (`int | None`)

### `KeverdAPIError`

Raised when the API returns a **non-2xx** HTTP status. Subclasses `KeverdError`.

**Raised when**

* Auth fails (`401` / `403`)
* Bad request (`400`)
* Quota exceeded (`402`)
* Server errors (`5xx`)

**Attributes:** `status_code`, `code`, `body` (parsed JSON when available)

```python theme={null}
from keverd import KeverdAPIError

try:
    keverd.verify(event_id=event_id)
except KeverdAPIError as err:
    if err.status_code == 402:
        # Workspace quota exceeded — upgrade plan or wait for reset
        raise
    raise
```

### `KeverdSignatureError`

Raised by `keverd.webhooks.construct_event(...)` when webhook signature verification fails. Subclasses `KeverdError` with `code="invalid_signature"`.

**Raised when**

* Missing `X-Keverd-Signature` or webhook secret
* Malformed signature header
* Timestamp outside the 300s tolerance
* HMAC mismatch (wrong secret, or body was parsed/modified before verify)
* Payload is not valid JSON

Treat these as **untrusted requests** — return `400` and do not process the event. See [Webhooks](https://developer.keverd.com/server/webhooks).

```python theme={null}
from keverd import Keverd, KeverdAPIError, KeverdError, KeverdSignatureError
```

| Class | Typical cause |
| - | - |
| `KeverdError` | Validation, network, timeout |
| `KeverdAPIError` | Non-2xx from API (`status_code`, `body`) — `402` = quota |
| `KeverdSignatureError` | Bad or missing webhook signature |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.