Metadata-Version: 2.4
Name: sendafrica
Version: 1.1.0
Summary: Official Python SDK for the SendAfrica SMS Infrastructure-as-a-Service API
Author: CamelTech
License: MIT
Keywords: sms,sendafrica,africa,tanzania,sdk
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.28
Provides-Extra: async
Requires-Dist: httpx>=0.24; extra == "async"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: responses; extra == "dev"

# SendAfrica Python SDK

[![Python](https://img.shields.io/pypi/pyversions/sendafrica)](https://pypi.org/project/sendafrica/)
[![Version](https://img.shields.io/pypi/v/sendafrica)](https://pypi.org/project/sendafrica/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

Official Python client for the [SendAfrica](https://sendafrica.online) SMS
Infrastructure-as-a-Service API. Designed to feel like Stripe's Python library:
simple for a first integration, enough control for production use.

---

## What You Get

- **Fail-fast validation** -- phone numbers are normalized to E.164 and
  validated locally *before* any network call. Bad input never hits the wire.
- **Automatic retries** -- exponential backoff on 429/5xx/connection errors,
  with `Retry-After` header respect. No retry loops in your code.
- **Phone number normalization** -- pass `0712345678`, `+255 712 345 678`, or
  `255712345678` and it all works. The SDK handles the conversion.
- **Server-side bulk send** -- `client.sms.bulk()` sends to up to 100
  recipients in a single API call with per-recipient failure handling.
- **SMS message logs** -- `client.sms.logs()` lists sent messages with
  status filtering and pagination.
- **International rate card** -- `client.rates.list()` and `client.rates.get()`
  show per-country SMS pricing (public, no auth required).
- **Sender ID management** -- `client.sender_ids.*` for registering,
  listing, and checking requirements for custom sender IDs.
- **SMS cost estimation** -- `client.sms.analyze()` tells you encoding
  (GSM-7 vs UCS-2), segment count, and credit cost with zero network calls.
- **Stripe-like error hierarchy** -- every error inherits from
  `SendAfricaError`. Catch the base class or get specific with
  `InsufficientCreditsError`, `RateLimitError`, etc.
- **Bulk SMS with partial failure handling** -- `send_many()` sends
  sequentially, collects per-message failures, and never aborts the batch
  on a single bad number.
- **Async support** -- `AsyncSendAfrica` for FastAPI, asyncio, and
  other async frameworks (requires `pip install sendafrica[async]`).
- **CLI** -- quick balance checks and SMS sending from the terminal without
  writing any code.

---

## Install

```bash
pip install sendafrica
```

For the async client (built on `httpx`):

```bash
pip install "sendafrica[async]"
```

For development (testing, coverage):

```bash
pip install -e ".[dev,async]"
```

**Requirements:** Python 3.9+

---

## Quickstart

```python
from sendafrica import SendAfrica

client = SendAfrica(api_key="SA-xxxxx")

result = client.sms.send(to="0712345678", message="Welcome to SendAfrica")
print(result.message_id, result.status, result.credits_used)
```

The API key can also be set via the `SENDAFRICA_API_KEY` environment
variable, in which case `SendAfrica()` needs no arguments:

```bash
export SENDAFRICA_API_KEY="SA-xxxxx"
```

---

## Authentication

The SDK resolves your API key in this order:

1. Explicit argument: `SendAfrica(api_key="SA-xxxxx")`
2. Environment variable: `SENDAFRICA_API_KEY`
3. If neither is set, `AuthenticationError` is raised

Every request includes an `X-API-Key` header (with `Authorization: Bearer`
sent as a fallback for backward compatibility with keys issued before the
`SA-` prefix era). The SDK also attaches a `User-Agent: sendafrica-python/1.1`
header and a unique `X-Request-Id` UUID per request for tracing.

---

## Configuration

```python
client = SendAfrica(
    api_key="SA-xxxxx",   # or set SENDAFRICA_API_KEY env var
    base_url="https://api.sendafrica.online/v1",  # default
    timeout=10,                # seconds per request, default 10
    max_retries=3,             # retries on 429/5xx/connection errors
    environment="production",  # label, default "production"
    debug=False,               # True prints [sendafrica] logs to stdout
    webhook_secret=None,       # HMAC secret for webhook signature verification
)
```

| Parameter | Default | Description |
|---|---|---|
| `api_key` | `None` | API key, or falls back to `SENDAFRICA_API_KEY` env var |
| `base_url` | `"https://api.sendafrica.online/v1"` | API base URL |
| `timeout` | `10` | Request timeout in seconds |
| `max_retries` | `3` | Max retry attempts on 429/5xx/connection errors |
| `environment` | `"production"` | Label (read-only, for logging/display) |
| `debug` | `False` | Print request/response logs to stdout |
| `webhook_secret` | `None` | HMAC-SHA256 secret for webhook verification |

---

## Resources

| Resource | Methods |
|---|---|
| `client.sms` | `send`, `send_many`, `bulk`, `logs`, `analyze` |
| `client.credits` | `balance`, `history` |
| `client.payments` | `create`, `rate` |
| `client.webhooks` | `parse` |
| `client.rates` | `list`, `get` |
| `client.sender_ids` | `requirements`, `usable`, `list`, `create`, `get` |

### SMS

#### `client.sms.send(to, message, *, sender=None)`

Send a single SMS. Phone numbers are normalized locally to E.164 before
any network call.

```python
result = client.sms.send(
    to="0712345678",
    message="Your OTP is 123456",
    sender="MyBrand",  # optional, max 11 chars
)

print(result.message_id)    # "SA-abc123..."
print(result.status)        # "queued"
print(result.credits_used)  # 1
```

**Returns:** `SMSResult` dataclass

| Field | Type | Description |
|---|---|---|
| `message_id` | `str` | Server-assigned unique ID |
| `status` | `str` | Delivery status (e.g. `"queued"`) |
| `credits_used` | `int` | Credits consumed |
| `cost` | `str \| None` | Cost string if provided |
| `to` | `str \| None` | Recipient phone number |

**Raises:** `InvalidPhoneError`, `ValidationError`, `InsufficientCreditsError`

#### `client.sms.send_many(messages, *, sender=None, rate_limit_per_sec=10.0)`

Send multiple SMS. Each failure is collected individually -- the batch
does not abort on a single bad number.

```python
results = client.sms.send_many([
    {"to": "0711111111", "message": "Hello John"},
    {"to": "0722222222", "message": "Hello Mary"},
    {"to": "+255733333333", "message": "Hello Alex"},
], sender="MyBrand")

print(results.sent_count)   # 2
print(results.failed_count) # 1

for failure in results.failed:
    print(failure["index"], failure["to"], failure["error"])
```

Each item in `messages` is a dict with:

| Key | Required | Description |
|---|---|---|
| `"to"` | yes | Phone number (any format) |
| `"message"` | yes | SMS body text |
| `"sender"` | no | Overrides the default `sender` for this message |

**Returns:** `BulkSMSResult` dataclass

| Field / Property | Type | Description |
|---|---|---|
| `results` | `List[SMSResult]` | Successfully sent messages |
| `failed` | `List[Dict]` | `{"index": int, "to": str, "error": str}` |
| `.sent_count` | `int` | Number of successfully sent messages |
| `.failed_count` | `int` | Number of failed messages |

The `rate_limit_per_sec` parameter paces requests with a client-side
delay (`1.0 / rate_limit_per_sec` seconds between sends). Default is
10 requests per second.

#### `client.sms.analyze(message)`

Preview encoding, segment count, and credit cost **without any network
call**. Useful for showing users the cost before they confirm sending.

```python
analysis = client.sms.analyze("Habari, how are you?")
print(analysis.encoding)   # "GSM-7"
print(analysis.characters) # 22
print(analysis.parts)      # 1
print(analysis.credits)    # 1

emoji_analysis = client.sms.analyze("Habari 😊")
print(emoji_analysis.encoding)   # "UCS-2"
print(emoji_analysis.characters) # 8
print(emoji_analysis.parts)      # 1
print(emoji_analysis.credits)    # 1
```

**Returns:** `SMSAnalysis` dataclass

| Field | Type | Description |
|---|---|---|
| `encoding` | `str` | `"GSM-7"` or `"UCS-2"` |
| `characters` | `int` | `len(message)` |
| `parts` | `int` | Number of SMS segments |
| `credits` | `int` | Estimated credits (1 per segment) |

Segmentation rules:
- **GSM-7** (basic Latin + limited symbols): 160 chars/single, 153 when
  concatenated
- **UCS-2** (emoji, accented characters outside GSM-7): 70 chars/single,
  67 when concatenated

> **Note:** `credits` is an estimate for UI display. The authoritative
> number is `credits_used` on the `SMSResult` from `client.sms.send()`.
> The server normalizes smart punctuation and performs the authoritative
> part/credit calculation; the SDK's `analyze()` mirrors this as closely as
> possible client-side.

#### `client.sms.bulk(to, message, *, sender=None)`

Send a single message to many recipients in one API call (server-side bulk).
Unlike `send_many` (which makes one request per recipient), `bulk` is a single
round trip — faster but capped at 100 recipients per call.

```python
result = client.sms.bulk(
    to=["0711111111", "0722222222", "0733333333"],
    message="Group message!",
    sender="MyBrand",
)

print(result.total)    # 3
print(result.sent)     # 2
print(result.failed)   # 1

for recipient in result.results:
    if recipient.error:
        print(f"Failed: {recipient.to} — {recipient.error}")
    else:
        print(f"Sent: {recipient.to} — {recipient.message_id}")
```

Each item in `to` is a phone number in any format (normalized locally to E.164).

**Returns:** `BulkSendResult` dataclass

| Field | Type | Description |
|---|---|---|
| `total` | `int` | Total recipients |
| `sent` | `int` | Successfully sent |
| `failed` | `int` | Failed (refunded individually) |
| `results` | `List[BulkSMSRecipient]` | Per-recipient outcomes |

**Raises:** `ValidationError` if `to` is empty or exceeds 100 recipients

#### `client.sms.logs(*, page=1, per_page=25, status=None, search=None, date_from=None)`

List sent-message log entries for the authenticated account.

```python
logs = client.sms.logs(status="delivered", per_page=50)

for log in logs.items:
    print(log.id, log.to_phone, log.status, log.credits_used)

print(f"Page {logs.page}/{logs.total_pages} of {logs.total} entries")
```

**Parameters:**

| Parameter | Default | Description |
|---|---|---|
| `page` | `1` | Page number (1-indexed) |
| `per_page` | `25` | Items per page (max 200) |
| `status` | `None` | Filter by `pending`, `sent`, `delivered`, `failed` |
| `search` | `None` | Substring search |
| `date_from` | `None` | ISO 8601 UTC datetime string |

**Returns:** `MessageLogListResponse` dataclass

| Field | Type | Description |
|---|---|---|
| `items` | `List[MessageLog]` | Log entries for this page |
| `total` | `int` | Total matching entries |
| `page` | `int` | Current page |
| `per_page` | `int` | Page size |
| `total_pages` | `int` | Total pages available |

### Credits

#### `client.credits.balance()`

```python
balance = client.credits.balance()
print(balance.account_id)  # "acc_abc123"
print(balance.balance)     # 4820
```

**Returns:** `CreditBalance` dataclass

| Field | Type | Description |
|---|---|---|
| `account_id` | `str` | Account identifier |
| `balance` | `int` | Current credit balance |

#### `client.credits.history(*, page=1, per_page=25)`

List credit transactions with page-based pagination.

```python
transactions = client.credits.history(page=1, per_page=50)

for tx in transactions:
    print(tx.id, tx.type, tx.amount, tx.balance_after, tx.created_at)
```

**Parameters:**

| Parameter | Default | Description |
|---|---|---|
| `page` | `1` | Page number (1-indexed) |
| `per_page` | `25` | Items per page (max 200) |

**Returns:** `List[CreditTransaction]`

| Field | Type | Description |
|---|---|---|
| `id` | `str` | Transaction ID |
| `type` | `str` | `"debit"` or `"credit"` |
| `amount` | `int` | Amount in credits |
| `balance_after` | `int` | Balance after this transaction |
| `description` | `str \| None` | Human-readable description |
| `created_at` | `str \| None` | Timestamp |

### Payments

Credit top-ups are pay-as-you-go: you specify any TZS amount (above
the minimum) and the API converts it to credits at the current tiered
rate.

#### `client.payments.create(*, amount, provider="manual", phone=None)`

```python
# Manual top-up
payment = client.payments.create(amount=50000)
print(payment.id, payment.status, payment.credit_amount)

# Mobile money top-up (phone is required)
payment = client.payments.create(
    amount=50000,
    provider="snippe",
    phone="0712345678",
)
```

**Parameters:**

| Parameter | Required | Default | Description |
|---|---|---|---|
| `amount` | yes | -- | Top-up amount in TZS (must be positive) |
| `provider` | no | `"manual"` | Payment provider (`"manual"`, `"snippe"`, etc.) |
| `phone` | no | `None` | Required for mobile-money providers, ignored for `"manual"` |

**Returns:** `Payment` dataclass

| Field | Type | Description |
|---|---|---|
| `id` | `str` | Payment/order ID |
| `status` | `str` | Payment status |
| `amount` | `int \| None` | Amount in TZS |
| `credit_amount` | `int \| None` | Credits to be credited |
| `currency` | `str` | `"TZS"` |
| `provider` | `str \| None` | Payment provider used |
| `source` | `str \| None` | Payment source |
| `created_at` | `str \| None` | Timestamp |

#### `client.payments.rate()`

Fetch the current pricing schedule: minimum top-up amount and the
tiered TZS-per-credit rate table.

```python
rate = client.payments.rate()
print(f"Minimum top-up: {rate.min_amount_tzs} TZS")

for tier in rate.tiers:
    print(f"  Up to {tier.max_amount_tzs} TZS: {tier.rate_tzs_per_credit} TZS/credit")
```

**Returns:** `VoucherRate` dataclass

| Field | Type | Description |
|---|---|---|
| `min_amount_tzs` | `int` | Minimum top-up amount in TZS |
| `tiers` | `List[RateTier]` | Pricing tiers |

Where each `RateTier` is:

| Field | Type | Description |
|---|---|---|
| `max_amount_tzs` | `int` | Upper bound (0 = unbounded/top tier) |
| `rate_tzs_per_credit` | `int` | Price per credit in TZS |

Use this to validate an amount client-side before calling `create()`:

```python
rate = client.payments.rate()
amount_tzs = 30000

if amount_tzs < rate.min_amount_tzs:
    print(f"Minimum is {rate.min_amount_tzs} TZS")
```

### Rates

Public rate card — no authentication required. Shows the per-SMS price (`rate_tzs`)
for each supported destination country, plus an optional reference snapshot of
Africa's Talking's provider pricing.

#### `client.rates.list()`

```python
rates = client.rates.list()

for r in rates:
    print(f"{r.name} ({r.iso2}): {r.rate_tzs} TZS per part")
    if r.provider_bulk_sms:
        print(f"  Provider ref: {r.provider_bulk_sms.provider}")
```

**Returns:** `List[RateInfo]`

| Field | Type | Description |
|---|---|---|
| `name` | `str` | Country name |
| `iso2` | `str` | ISO 3166-1 alpha-2 code |
| `dial_code` | `str` | E.164 dial code (e.g. `+255`) |
| `rate_tzs` | `float` | SendAfrica customer price per SMS part (TZS) |
| `provider_bulk_sms` | `ProviderBulkSMSRate \| None` | Provider reference pricing (additive) |

#### `client.rates.get(country)`

Fetch the rate for a single country by ISO2 code or name.

```python
rate = client.rates.get("NG")
print(rate.name, rate.rate_tzs)
```

**Raises:** `NotFoundError` if the country is not supported.

### Sender IDs

Sender ID registration and management via a master SwalaSMS integration.
Registration is free — no credits are charged.

#### `client.sender_ids.requirements()`

Fetch registration requirements: eligibility, supported countries, required
document types, naming rules, and allowed purposes.

```python
reqs = client.sender_ids.requirements()

if reqs.eligibility.can_request:
    print(f"Eligible with {reqs.eligibility.purchased_units} units")
for rule in reqs.sender_id_rules.reserved_names:
    print(f"Reserved: {rule}")
```

**Returns:** `SenderIDRequirements` dataclass

| Field | Type | Description |
|---|---|---|
| `eligibility` | `SenderIDEligibility \| None` | Whether the account can request a sender ID |
| `countries` | `List[SenderIDCountry]` | Supported countries |
| `documents` | `List[SenderIDDocumentRequirement]` | Required document types |
| `purposes` | `List[str]` | Allowed purpose values |
| `sender_id_rules` | `SenderIDRules \| None` | Naming rules (length, pattern, reserved names) |
| `sample_message_rules` | `Dict \| None` | Sample message constraints |

#### `client.sender_ids.usable(*, provider=None)`

List all sender IDs available for sending (system defaults + approved custom IDs).

```python
usable = client.sender_ids.usable()
for sid in usable:
    marker = " (default)" if sid.is_default else ""
    print(f"{sid.name}{marker} — {sid.description}")
```

**Returns:** `List[UsableSenderID]`

#### `client.sender_ids.list()`

List sender IDs registered by the authenticated account.

```python
sids = client.sender_ids.list()
for sid in sids:
    print(f"{sid.name}: {sid.status} (usable={sid.is_usable})")
    if sid.rejection_reason:
        print(f"  Rejected: {sid.rejection_reason}")
```

**Returns:** `List[SenderID]`

#### `client.sender_ids.create(*, name, country, purpose, sample_message, documents=None)`

Submit a new Sender ID registration request. Status starts as `pending`
until an admin reviews and submits to Swala, then sync worker reconciles the
final status.

```python
sid = client.sender_ids.create(
    name="MYBRAND",
    country="TZ",
    purpose="Transactional",
    sample_message="Your verification code is 123456.",
    documents=[
        {
            "requirement_uid": "req-doc-1",
            "filename": "license.pdf",
            "content_base64": base64_data,
        }
    ],
)
print(sid.id, sid.status)  # pending
```

**Returns:** `SenderID`

**Raises:** `ValidationError` for reserved names or invalid purposes;
`ConflictError` if the name is already registered.

#### `client.sender_ids.get(sender_id)`

Fetch a single registered Sender ID by ID.

```python
sid = client.sender_ids.get("550e8400-e29b-41d4-a716-446655440000")
print(sid.status, sid.is_usable)
```

**Returns:** `SenderID`

> **Note:** Admin-only endpoints (`/v1/admin/sender-ids/*`) are intentionally
> not exposed in this SDK. This SDK is for developers only.

### Webhooks

> **Status:** speculative. The SendAfrica API does not yet forward signed
> events to customer endpoints. This resource is ready for when that
> ships server-side.

#### `client.webhooks.parse(payload, *, signature=None, secret=None)`

Parse and optionally verify an incoming webhook payload using
HMAC-SHA256.

```python
from fastapi import Request

@app.post("/webhooks/sendafrica")
async def webhook(request: Request):
    event = client.webhooks.parse(
        await request.body(),
        signature=request.headers.get("X-SendAfrica-Signature"),
    )

    if event.type == "sms.delivered":
        print(f"Message {event.message_id} delivered")
```

**Parameters:**

| Parameter | Required | Description |
|---|---|---|
| `payload` | yes | Raw webhook body (`str` or `bytes`) |
| `signature` | no | Value from `X-SendAfrica-Signature` header |
| `secret` | no | Overrides the client-level `webhook_secret` |

**Returns:** `WebhookEvent` dataclass

| Field | Type | Description |
|---|---|---|
| `type` | `str` | Event type (e.g. `"sms.delivered"`) |
| `message_id` | `str \| None` | Associated message ID |
| `data` | `Dict` | Full raw event data |

**Raises:** `WebhookSignatureError` on signature mismatch

---

## Phone Number Handling

The SDK normalizes phone numbers to E.164 format locally, before any
network call. These formats all work:

| Input | Output |
|---|---|
| `0712345678` | `+255712345678` |
| `712345678` | `+255712345678` |
| `255712345678` | `+255712345678` |
| `+255712345678` | `+255712345678` |
| `+255 712 345 678` | `+255712345678` |

The default country code is `255` (Tanzania). Numbers that cannot be
confidently normalized raise `InvalidPhoneError` without hitting the API.

The SDK is deliberately permissive beyond Tanzania: any digit string of
plausible length (9-15 digits) that already has a country code will
normalize fine. The API's own validator is the source of truth -- the
local check exists to catch typos early.

---

## Error Handling

All errors inherit from `SendAfricaError`. Catch the base class for
generic handling, or catch specific subtypes for finer-grained control:

```python
from sendafrica import SendAfrica
from sendafrica.exceptions import (
    SendAfricaError,
    InsufficientCreditsError,
    RateLimitError,
    InvalidPhoneError,
)

client = SendAfrica()

try:
    client.sms.send(to="0712345678", message="Hello")
except InsufficientCreditsError:
    print("Not enough credits -- top up first")
except RateLimitError as e:
    print(f"Rate limited -- retry after {e.retry_after}s")
except InvalidPhoneError as e:
    print(f"Bad phone number: {e.message}")
except SendAfricaError as e:
    print(f"API error: {e} (status={e.status_code}, request_id={e.request_id})")
```

### Exception hierarchy

```
SendAfricaError (base)
├── AuthenticationError        (HTTP 401)
├── ValidationError            (HTTP 400, 422)
│   └── InvalidPhoneError      (local or server-side phone validation)
├── InsufficientCreditsError   (HTTP 402)
├── RateLimitError             (HTTP 429, has .retry_after)
├── NotFoundError              (HTTP 404)
├── ServerError                (HTTP 5xx)
├── APIConnectionError         (network/timeout)
└── WebhookSignatureError      (HMAC mismatch)
```

### Attributes on every exception

| Attribute | Type | Description |
|---|---|---|
| `.message` | `str` | Human-readable error message |
| `.status_code` | `int \| None` | HTTP status code (if applicable) |
| `.request_id` | `str \| None` | Request ID from response headers |
| `.response_body` | `Any` | Raw response payload |

`RateLimitError` also has `.retry_after: float | None` (seconds from
the `Retry-After` header).

### Retry behavior

The SDK automatically retries on:

| Status | Behavior |
|---|---|
| `429` | Respects `Retry-After` header, then exponential backoff |
| `500`, `502`, `503`, `504` | Exponential backoff |
| Connection errors | Exponential backoff |

Backoff formula: `min(0.5 * 2^(attempt-1), 8.0)` seconds. Default max
retries: 3. Total max wait per request: ~15 seconds.

---

## CLI

The SDK installs a `sendafrica` command for quick operations:

```bash
# Set your API key
export SENDAFRICA_API_KEY="SA-xxxxx"

# Check your credit balance
sendafrica balance
# Credits: 4820

# Send a single SMS
sendafrica sms send --to 0712345678 --message "Hello from SendAfrica"
# Sent: SA-abc123 (status=queued, credits=1)

# Send with a sender ID
sendafrica sms send --to 0712345678 --message "OTP: 4829" --sender MyBrand

# List SMS message logs
sendafrica sms logs --status delivered --page 1

# View international rate card
sendafrica rates

# List registered sender IDs
sendafrica sender-ids list
sendafrica sender-ids requirements
```

---

## Async

For FastAPI, asyncio, or other async frameworks:

```python
import asyncio
from sendafrica import AsyncSendAfrica

async def main():
    client = AsyncSendAfrica(api_key="SA-xxxxx")
    try:
        result = await client.sms.send(to="0712345678", message="Hello async!")
        print(result.message_id)
    finally:
        await client.aclose()

asyncio.run(main())
```

In FastAPI:

```python
from sendafrica import AsyncSendAfrica

client = AsyncSendAfrica()  # uses SENDAFRICA_API_KEY env var

@app.on_event("shutdown")
async def shutdown():
    await client.aclose()

@app.post("/send-sms")
async def send_sms(to: str, message: str):
    result = await client.sms.send(to=to, message=message)
    return {"message_id": result.message_id}
```

> **Note:** Async support requires `pip install sendafrica[async]` (adds
> `httpx>=0.24`). The async transport and retry logic are fully
> implemented. Resource-level async wiring is being finalized in Phase 2.

---

## Lessons: Using the SDK Effectively

These are practical patterns for getting the most out of the SDK.

### Lesson 1: Check balance before sending

Avoid `InsufficientCreditsError` by checking first:

```python
balance = client.credits.balance()
if balance.balance < 10:
    print(f"Low balance: {balance.balance} credits remaining")
    # prompt user to top up
```

### Lesson 2: Preview cost with analyze()

`analyze()` makes zero network calls -- it's pure local computation.
Use it to show users the cost before they confirm:

```python
analysis = client.sms.analyze(message)
cost = analysis.credits
# Show "This message will cost {cost} credit(s)" in your UI
```

### Lesson 3: Handle partial failures in bulk sends

`send_many()` never aborts on a single failure. Always check
`failed_count`:

```python
results = client.sms.send_many(messages)
if results.failed_count > 0:
    for f in results.failed:
        print(f"Message to {f['to']} failed: {f['error']}")
```

### Lesson 4: Phone numbers just work

Don't preprocess phone numbers in your code. Pass whatever format
you have:

```python
# All of these work:
client.sms.send(to="0712345678", message="Hello")
client.sms.send(to="+255712345678", message="Hello")
client.sms.send(to="255712345678", message="Hello")
client.sms.send(to="+255 712 345 678", message="Hello")
```

### Lesson 5: Catch specific errors

Don't catch `SendAfricaError` for everything -- use specific exceptions
for better UX:

```python
try:
    client.sms.send(to="0712345678", message="Hello")
except InvalidPhoneError:
    # Show "Please check the phone number"
except InsufficientCreditsError:
    # Show "Please top up your credits"
except RateLimitError:
    # Show "Please wait a moment and try again"
```

### Lesson 6: Use the CLI for quick tests

Verify your API key works without writing any code:

```bash
export SENDAFRICA_API_KEY="SA-xxxxx"
sendafrica balance
```

If that returns your balance, your setup is correct.

### Lesson 7: Retry is built in

Don't implement your own retry logic. The SDK handles 429 and 5xx
automatically with exponential backoff:

```python
# This is safe -- the SDK retries transient failures internally
result = client.sms.send(to="0712345678", message="Hello")
```

### Lesson 8: Webhooks are ready but not live

You can write your webhook handler now, but don't depend on receiving
events yet:

```python
# This code is ready -- it just won't receive events until
# SendAfrica ships outbound webhooks server-side
event = client.webhooks.parse(payload, signature=signature)
```

---

## Project Layout

```
sendafrica/
├── __init__.py          # Public API exports, __version__
├── client.py            # SendAfrica, AsyncSendAfrica
├── http.py              # HTTPTransport, AsyncHTTPTransport
├── auth.py              # API key resolution
├── exceptions.py        # Error hierarchy
├── models.py            # Response dataclasses
├── cli.py               # `sendafrica` command
├── resources/
│   ├── __init__.py      # Exports all resource classes
│   ├── sms.py           # send, send_many, bulk, logs, analyze
│   ├── credits.py       # balance, history
│   ├── payments.py      # create, rate
│   ├── rates.py         # list, get (public rate card)
│   ├── senderids.py     # requirements, usable, list, create, get
│   └── webhooks.py      # parse, signature verify
└── utils/
    ├── __init__.py      # Exports normalize_phone, analyze_sms, etc.
    ├── phone.py         # E.164 normalization
    ├── sms.py           # GSM-7/UCS-2 encoding + segment analysis
    └── validators.py    # Input validators (require, sender_id, amount)
```

---

## Roadmap

- **Phase 1 (done):** Client, auth with `X-API-Key` header, SMS send/bulk/logs,
  credit balance/history, payments create/rate, error hierarchy, response
  models, CLI, phone normalization, retry/backoff, public rate card, sender
  ID management
- **Phase 2:** Finish async resource wiring, CLI expansion (payments, send_many)
- **Phase 3:** Campaigns, contacts, templates, scheduling

---

## Contributing

Internal developer notes live in the subdirectory READMEs:

- [`sendafrica/resources/README.md`](sendafrica/resources/README.md) --
  implementation notes for each resource, how to add new ones
- [`sendafrica/utils/README.md`](sendafrica/utils/README.md) -- design
  rationale for phone/SMS/validators, how to add new validators
- [`tests/README.md`](tests/README.md) -- test coverage, how to mock
  the API envelope, what's not covered yet

Run tests:

```bash
pip install -e ".[dev,async]"
pytest -q
```
