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

# Python SDK

> Async Python client and FastAPI middleware for Cred Protocol

## Installation

```bash theme={null}
# Core client
pip install cred-protocol

# With FastAPI integration
pip install cred-protocol[fastapi]
```

## Quick Start

```python theme={null}
import asyncio
from cred_protocol import CredClient

async def main():
    async with CredClient(api_key="cred_sk_...") as cred:
        result = await cred.evaluate(
            wallet_address="0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
            policy="standard",
        )

        print(result.trust_score)   # 75
        print(result.trust_tier)    # TrustTier.VERIFIED
        print(result.all_passed)    # True

asyncio.run(main())
```

## Evaluate Options

### Using a Policy Template

```python theme={null}
result = await cred.evaluate(
    wallet_address="0x...",
    policy="standard",
)
```

### Using Custom Gates

```python theme={null}
result = await cred.evaluate(
    wallet_address="0x...",
    gates=["human", "verified", "established"],
    operator="WEIGHTED",
    weights={"human": 0.4, "verified": 0.35, "established": 0.25},
    composite_threshold=60,
)
```

### With Dynamic Pricing

```python theme={null}
result = await cred.evaluate(
    wallet_address="0x...",
    policy="reputation",
    include_pricing=True,
    base_price_usdc=0.01,
)

print(result.price_multiplier)      # 0.25
print(result.suggested_price_usdc)  # 0.0025
```

## TrustResult Fields

| Field                  | Type                       | Description                                              |
| ---------------------- | -------------------------- | -------------------------------------------------------- |
| `wallet_address`       | `str`                      | The evaluated wallet                                     |
| `trust_score`          | `int`                      | 0–100 composite score                                    |
| `trust_tier`           | `TrustTier`                | `TRUSTED`, `VERIFIED`, `LIMITED`, `UNTRUSTED`, `BLOCKED` |
| `confidence`           | `float`                    | 0.0–1.0 data confidence                                  |
| `all_passed`           | `bool`                     | Whether all gates passed                                 |
| `gate_results`         | `list[GateScoreBreakdown]` | Per-gate breakdown                                       |
| `price_multiplier`     | `float \| None`            | Dynamic pricing multiplier                               |
| `suggested_price_usdc` | `float \| None`            | Computed price                                           |
| `reputation`           | `WalletReputation \| None` | Behavioral history                                       |
| `cached`               | `bool`                     | Whether this was a cache hit                             |
| `request_id`           | `str`                      | Unique request ID                                        |
| `challenge`            | `dict \| None`             | 402 challenge body (if gates failed)                     |

## Error Handling

```python theme={null}
from cred_protocol import CredClient, CredAPIError

try:
    result = await cred.evaluate(wallet_address="0x...", policy="standard")
except CredAPIError as e:
    print(e.status)  # 401, 429, etc.
    print(e.body)    # Error details
```

## FastAPI Integration

The `require_trust()` dependency gates endpoints with a single line:

```python theme={null}
import os
from fastapi import Depends, FastAPI
from cred_protocol.fastapi import require_trust
from cred_protocol import TrustResult

app = FastAPI()

@app.get("/resource")
async def get_resource(
    trust: TrustResult = Depends(require_trust(
        api_key=os.environ["CRED_API_KEY"],
        policy="standard",
    )),
):
    return {
        "data": "...",
        "wallet": trust.wallet_address,
        "score": trust.trust_score,
        "tier": trust.trust_tier.value,
    }
```

### FastAPI Configuration

```python theme={null}
require_trust(
    api_key="cred_sk_...",           # Or set CRED_API_KEY env var
    base_url="https://...",          # Defaults to production
    policy="standard",               # Named template
    # gates=["human", "verified"],   # Or custom gates
    # operator="AND",
    include_pricing=False,
    base_price_usdc=None,
    on_fail="deny",                  # "deny" (403), "challenge" (402), "pass"
)
```

### Wallet Extraction

The FastAPI dependency checks (in order):

1. `X-Wallet-Address` request header
2. `?wallet=` query parameter

Override with a custom extractor:

```python theme={null}
from fastapi import Request
from cred_protocol.fastapi import CredTrustDependency

trust_dep = CredTrustDependency(
    api_key=os.environ["CRED_API_KEY"],
    policy="standard",
    extract_wallet=lambda req: req.headers.get("x-agent-wallet"),
)

@app.get("/resource")
async def get_resource(trust: TrustResult = Depends(trust_dep)):
    ...
```

### Failure Responses

| Response | When                                                       |
| -------- | ---------------------------------------------------------- |
| `400`    | No wallet address found on the request                     |
| `402`    | Gates failed, `on_fail="challenge"`                        |
| `403`    | Gates failed with `on_fail="deny"`, or wallet is `blocked` |
| `429`    | Cred API rate limit exceeded                               |
| `502`    | Upstream gate provider error                               |

## Using Without FastAPI

The core `CredClient` works with any async Python code:

```python theme={null}
from cred_protocol import CredClient

# As async context manager (recommended)
async with CredClient(api_key="cred_sk_...") as cred:
    result = await cred.evaluate(wallet_address="0x...", policy="standard")

# Or manage lifecycle manually
cred = CredClient(api_key="cred_sk_...")
result = await cred.evaluate(wallet_address="0x...", policy="standard")
await cred.close()
```
