Official Python SDK for KhaleejiAPI - Middle East API Platform
Project description
KhaleejiAPI Python SDK
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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file khaleejiapi-1.2.0.tar.gz.
File metadata
- Download URL: khaleejiapi-1.2.0.tar.gz
- Upload date:
- Size: 19.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2ba2ae83bbe1e9c868b48bde71605b6e9d5144688fb0c123ed7e1e81d4c18b63
|
|
| MD5 |
e761a11382865a416d0fd5aef757b857
|
|
| BLAKE2b-256 |
733dfd7578b3325e0f9e000aa3f6a94b925a2dcec8dc6fdc6614039a7d2b5443
|
File details
Details for the file khaleejiapi-1.2.0-py3-none-any.whl.
File metadata
- Download URL: khaleejiapi-1.2.0-py3-none-any.whl
- Upload date:
- Size: 23.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3e732bc71a70fee5bb07380f2977cd362b368c8f8e2742a4014b7e307b077baa
|
|
| MD5 |
bd1f8b0054f277610ed041adf0f21b82
|
|
| BLAKE2b-256 |
e6db240f6ee39d89122ce95eaf7182ae3bc98cbda5740bc44235660d5384c6bc
|