Skip to main content

Official Python SDK for KhaleejiAPI - Middle East API Platform

Project description

KhaleejiAPI Python SDK

PyPI version Python License: MIT

The official Python SDK for KhaleejiAPI — the Middle East API platform providing 20+ production-ready APIs for validation, geolocation, finance, translation, and more.

Installation

pip install khaleejiapi

Quick Start

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

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

Async usage

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

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

# 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

# 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

# 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

# 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

# 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

# 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:

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:

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:

from khaleejiapi import EmailValidationResult

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

Development

# 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 for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

khaleejiapi-1.1.0.tar.gz (18.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

khaleejiapi-1.1.0-py3-none-any.whl (22.1 kB view details)

Uploaded Python 3

File details

Details for the file khaleejiapi-1.1.0.tar.gz.

File metadata

  • Download URL: khaleejiapi-1.1.0.tar.gz
  • Upload date:
  • Size: 18.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.1

File hashes

Hashes for khaleejiapi-1.1.0.tar.gz
Algorithm Hash digest
SHA256 ee7702cbffc434c0f2a3d11aece68cb464bcb7e0473973bb758e860623486f47
MD5 896f5db659aac1aa514888c11c22cd90
BLAKE2b-256 92ba75a7267ee1dd4599b2b34328eee5ed8e04924beb8836838e6a59b5acb7b0

See more details on using hashes here.

File details

Details for the file khaleejiapi-1.1.0-py3-none-any.whl.

File metadata

  • Download URL: khaleejiapi-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 22.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.1

File hashes

Hashes for khaleejiapi-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fa25166fa079346fe709d08cf43a89dfbe14b48c831af1f1e4b81f97d79f00df
MD5 7c9578c299140742ffef3fb3e9fe3af4
BLAKE2b-256 a89ed5c855cda8c0be77cf67d4ef6cf93c418a47a0347990a7723300e5294821

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page