khaleejiapi 1.0.0
Official Python SDK for KhaleejiAPI - Middle East API Platform
License: MIT
Requires Python: >=3.9
Keywords: api, dubai, khaleejiapi, middle-east, sdk, uae

# KhaleejiAPI Python SDK

[![PyPI version](https://img.shields.io/pypi/v/khaleejiapi.svg)](https://pypi.org/project/khaleejiapi/)
[![Python](https://img.shields.io/pypi/pyversions/khaleejiapi.svg)](https://pypi.org/project/khaleejiapi/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

The official Python SDK for [KhaleejiAPI](https://khaleejiapi.dev) — the Middle East API platform providing 20+ production-ready APIs for validation, geolocation, finance, translation, and more.

## Installation

```bash
pip install khaleejiapi
```

## Quick Start

```python
from khaleejiapi import KhaleejiAPI

client = KhaleejiAPI("kapi_live_your_api_key")

# Validate an email
result = client.validation.validate_email("user@example.com")
print(result["valid"])  # True

# Look up an IP address
ip_data = client.geo.lookup_ip("8.8.8.8")
print(ip_data["country"]["name"])  # United States

client.close()
```

### Using a context manager

```python
with KhaleejiAPI("kapi_live_your_api_key") as client:
    rates = client.finance.get_exchange_rates("USD")
    print(rates["rates"]["AED"])
```

### Async usage

```python
import asyncio
from khaleejiapi import AsyncKhaleejiAPI

async def main():
    async with AsyncKhaleejiAPI("kapi_live_your_api_key") as client:
        result = await client.validation.validate_email("user@example.com")
        print(result["valid"])

asyncio.run(main())
```

## Configuration

```python
client = KhaleejiAPI(
    "kapi_live_your_api_key",
    base_url="https://khaleejiapi.dev/api",  # default
    timeout=30.0,                              # seconds (default)
    max_retries=2,                             # automatic retries on 429/5xx (default)
)
```

## API Reference

### Validation

```python
# Email validation (syntax, MX, disposable, role-account checks)
result = client.validation.validate_email("user@example.com")
# Returns: { valid, email, reason, checks: { syntax, disposable, mx, role }, domain, localPart, suggestion? }

# Phone validation (GCC countries with carrier detection)
result = client.validation.validate_phone("+971501234567")
# Returns: { valid, phone, e164, country: { code, name, nameAr, prefix }, type, nationalNumber, reason }

# VAT / TRN validation (UAE Tax Registration Number)
result = client.validation.validate_vat("100000000000003")
# Returns: { valid, trn, country, countryName, reason }

# IBAN validation (MENA region with bank identification)
result = client.validation.validate_iban("AE070331234567890123456")
# Returns: { valid, iban, countryCode, country, bank: { name, bic }, reason }

# Emirates ID validation
result = client.validation.validate_emirates_id("784-1990-1234567-1")
# Returns: { valid, emiratesId, formatted, components: { year, random, checkDigit } }
```

### Geolocation

```python
# IP geolocation (supports IPv4 and IPv6)
result = client.geo.lookup_ip("8.8.8.8")
# Returns: { ip, type, continent, country, region, city, postal, location, connection }

# Omit IP to look up the caller's IP
result = client.geo.lookup_ip()

# Timezone lookup by location name or coordinates
result = client.geo.get_timezone("Dubai")
result = client.geo.get_timezone(lat=25.2048, lon=55.2708)
# Returns: { timezone, utcOffset, dstOffset, localTime, isDST }

# Geocoding (forward and reverse)
result = client.geo.geocode(address="Burj Khalifa, Dubai")
result = client.geo.geocode(lat=25.1972, lon=55.2744)
# Returns: { formattedAddress, latitude, longitude, components }

# Weather
result = client.geo.get_weather(city="Dubai")
# Returns: { city, country, current: { temperature, humidity, description, ... } }
```

### Finance

```python
# Exchange rates (170+ currencies, base defaults to AED)
result = client.finance.get_exchange_rates("USD")
# Returns: { base, timestamp, rates: { AED: 3.6725, EUR: 0.92, ... } }

# Currency conversion
result = client.finance.get_exchange_rates("USD", target="AED", amount=100)
# Returns: { from, to, amount, rate, converted, timestamp }

# VAT calculator
result = client.finance.calculate_vat(1000, "AE")
# Returns: { amount, vatRate, vatAmount, total, country, inclusive }

# Public holidays (UAE and GCC)
result = client.finance.get_holidays("AE", year=2025)
# Returns: { country, year, holidays: [{ name, nameAr, date, type }] }
```

### Documents

```python
# Image processing (resize, crop, compress, convert)
with open("photo.jpg", "rb") as f:
    processed = client.documents.process_image(
        f.read(),
        operations={"width": 800, "format": "webp", "quality": 80},
    )
with open("output.webp", "wb") as f:
    f.write(processed)

# PDF generation from HTML
pdf_bytes = client.documents.generate_pdf(html="<h1>Invoice</h1><p>Amount: 500 AED</p>")
with open("invoice.pdf", "wb") as f:
    f.write(pdf_bytes)

# PDF generation from URL
pdf_bytes = client.documents.generate_pdf(url="https://example.com", options={"format": "A4"})
```

### Communication

```python
# Translation (Arabic ↔ English with auto-detection)
result = client.communication.translate("Hello, welcome to Dubai")
# Returns: { text, translated, detectedLanguage, wordsMatched, totalWords }

result = client.communication.translate("مرحبا", target="en")

# URL shortener
result = client.communication.shorten_url("https://example.com/very/long/url")
# Returns: { code, shortUrl, originalUrl, expiresInDays, createdAt }

result = client.communication.shorten_url("https://example.com", custom_alias="my-link")
```

### Utility

```python
# QR code generation
qr_bytes = client.utility.generate_qr("https://khaleejiapi.dev", size=400, format="png")
with open("qr.png", "wb") as f:
    f.write(qr_bytes)

# Fraud detection
result = client.utility.check_fraud(
    email="suspicious@tempmail.com",
    ip="185.220.101.42",
    phone="+1234567",
)
# Returns: { riskScore, riskLevel, signals: [{ field, risk, score, reason }], recommendation }
```

## Error Handling

The SDK raises typed exceptions for every error class:

```python
from khaleejiapi import (
    KhaleejiAPI,
    KhaleejiAPIError,       # Base class for all errors
    AuthenticationError,     # 401 — invalid or missing API key
    ForbiddenError,          # 403 — missing scope
    ValidationError,         # 400 — bad request parameters
    NotFoundError,           # 404 — resource not found
    RateLimitError,          # 429 — rate limit exceeded
    ConflictError,           # 409 — resource conflict
    ServerError,             # 5xx — server error
)

try:
    result = client.validation.validate_email("bad")
except RateLimitError as e:
    print(f"Rate limited! Retry after {e.retry_after}s")
except AuthenticationError:
    print("Check your API key")
except KhaleejiAPIError as e:
    print(f"API error {e.code}: {e.message} (HTTP {e.status_code})")
```

## Rate Limiting

Rate-limit headers are automatically parsed and available after every request:

```python
result = client.validation.validate_email("user@example.com")
rl = client.last_rate_limit
print(f"Remaining: {rl.get('remaining')} / {rl.get('limit')}")
```

The SDK automatically retries on HTTP 429 (and 5xx) with exponential backoff.
Configure with `max_retries` (default `2`).

## Type Safety

This SDK is fully typed and ships with a `py.typed` marker (PEP 561).
All response types are `TypedDict` subclasses for excellent IDE autocompletion:

```python
from khaleejiapi import EmailValidationResult

def process(result: EmailValidationResult) -> None:
    if result["valid"]:
        print(f"Domain: {result['domain']}")
```

## Development

```bash
# Clone the repository
git clone https://github.com/khaleejiapi/sdk-python.git
cd sdk-python

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

# Run tests
pytest

# Type checking
mypy src/

# Linting
ruff check src/ tests/
```

## License

MIT — see [LICENSE](./LICENSE) for details.