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.
Metadata
Release files for khaleejiapi 1.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| khaleejiapi-1.2.0.tar.gz | 19.7 kB | Without provenance | Details for khaleejiapi-1.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| khaleejiapi-1.2.0-py3-none-any.whl | Python 3 | none | any | Details for khaleejiapi-1.2.0-py3-none-any.whl |
Total release size: 43.0 kB
Release files / khaleejiapi-1.2.0.tar.gz
| Download URL | khaleejiapi-1.2.0.tar.gz |
|---|---|
| Size | 19.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
2ba2ae83bbe1e9c868b48bde71605b6e9d5144688fb0c123ed7e1e81d4c18b63
|
|
BLAKE2b-256 checksum How to use checksums |
733dfd7578b3325e0f9e000aa3f6a94b925a2dcec8dc6fdc6614039a7d2b5443
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.1
|
Release files / khaleejiapi-1.2.0-py3-none-any.whl
| Download URL | khaleejiapi-1.2.0-py3-none-any.whl |
|---|---|
| Size | 23.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
3e732bc71a70fee5bb07380f2977cd362b368c8f8e2742a4014b7e307b077baa
|
|
BLAKE2b-256 checksum How to use checksums |
e6db240f6ee39d89122ce95eaf7182ae3bc98cbda5740bc44235660d5384c6bc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.1
|
Security for khaleejiapi 1.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.