@khaleejiapi/sdk
v1.2.0
Published
Official TypeScript/JavaScript SDK for KhaleejiAPI - Middle East API Platform
Maintainers
Readme
@khaleejiapi/sdk
Official TypeScript/JavaScript SDK for KhaleejiAPI — the Middle East API Platform.
- Zero dependencies — uses native
fetch - Works everywhere — Node.js 18+, Deno, Bun, browsers
- Fully typed — first-class TypeScript support with complete type definitions
- Automatic retries — exponential backoff on 429 and 5xx responses
- Rate limit aware — parsed rate limit headers available after every request
Installation
# npm
npm install @khaleejiapi/sdk
# yarn
yarn add @khaleejiapi/sdk
# pnpm
pnpm add @khaleejiapi/sdk
# bun
bun add @khaleejiapi/sdkQuick Start
import { KhaleejiAPI } from '@khaleejiapi/sdk';
const client = new KhaleejiAPI({
apiKey: 'kapi_live_...', // Get yours at https://khaleejiapi.dev/dashboard/api-keys
});
// Validate an email
const email = await client.validation.validateEmail({ email: '[email protected]' });
console.log(email.valid, email.checks);
// Look up an IP
const ip = await client.geo.lookupIp({ ip: '8.8.8.8' });
console.log(ip.country, ip.city);
// Get exchange rates
const rates = await client.finance.getExchangeRates({ base: 'AED', symbols: 'USD,EUR,GBP' });
console.log(rates.rates);Configuration
const client = new KhaleejiAPI({
apiKey: 'kapi_live_...', // Required
baseUrl: 'https://khaleejiapi.dev/api', // Default
timeout: 30000, // Request timeout in ms (default: 30s)
retries: 2, // Retry count on 429/5xx (default: 2)
retryDelay: 1000, // Initial retry delay in ms (default: 1s)
});API Reference
Validation
validateEmail
Validate an email address with syntax, domain, MX record, and disposable checks.
const result = await client.validation.validateEmail({ email: '[email protected]' });
// {
// valid: true,
// email: '[email protected]',
// checks: { format: true, mx: true, disposable: false, role: false },
// domain: 'example.com',
// mx_records: ['mx.example.com']
// }validatePhone
Validate an international phone number with carrier and line type detection.
const result = await client.validation.validatePhone({
phone: '+971501234567',
country: 'AE',
});
// { valid: true, formatted: '+971 50 123 4567', carrier: 'Etisalat', line_type: 'mobile' }validateVat
Validate a VAT/TRN number and look up company information.
const result = await client.validation.validateVat({
vat_number: '100123456700003',
country_code: 'AE',
});
// { valid: true, company_name: 'Example Trading LLC', ... }validateIban
Validate an IBAN and retrieve bank and branch information.
const result = await client.validation.validateIban({
iban: 'AE070331234567890123456',
});
// { valid: true, bank_name: 'ADCB', country_code: 'AE', ... }validateEmiratesId
Validate a UAE Emirates ID number.
const result = await client.validation.validateEmiratesId({
id: '784-1990-1234567-1',
});
// { valid: true, formatted: '784-1990-1234567-1', check_digit: '1' }Geolocation
lookupIp
Get geolocation data for an IP address. Omit ip to use the caller's IP.
const result = await client.geo.lookupIp({ ip: '8.8.8.8' });
// { country: 'United States', city: 'Mountain View', isp: 'Google', ... }getTimezone
Get timezone information by location name or coordinates.
const result = await client.geo.getTimezone({ location: 'Dubai' });
// { timezone: 'Asia/Dubai', utc_offset: '+04:00', current_time: '...' }geocode
Convert addresses to coordinates or coordinates to addresses.
// Forward geocoding
const result = await client.geo.geocode({ address: 'Burj Khalifa, Dubai' });
// { latitude: 25.1972, longitude: 55.2744, formatted_address: '...' }
// Reverse geocoding
const result2 = await client.geo.geocode({ lat: 25.1972, lon: 55.2744 });getWeather
Current weather and forecast for a city or coordinates.
const result = await client.geo.getWeather({ city: 'Dubai' });
// { temperature: 35, humidity: 60, conditions: 'Clear', forecast: [...] }Finance
getExchangeRates
Real-time exchange rates for 170+ currencies. Defaults to AED base.
const result = await client.finance.getExchangeRates({
base: 'AED',
symbols: 'USD,EUR,GBP,SAR',
});
// { base: 'AED', rates: { USD: 0.2723, EUR: 0.2514, ... } }calculateVat
Calculate VAT for amounts with automatic rate detection.
const result = await client.finance.calculateVat({
amount: 100,
country_code: 'AE',
});
// { net_amount: 100, vat_amount: 5, gross_amount: 105, vat_rate: 5 }
// Inclusive VAT (extract VAT from total)
const result2 = await client.finance.calculateVat({
amount: 105,
country_code: 'AE',
inclusive: true,
});
// { net_amount: 100, vat_amount: 5, gross_amount: 105, vat_rate: 5 }getHolidays
Public holidays for UAE and GCC countries with Islamic calendar support.
const result = await client.finance.getHolidays({ country: 'AE', year: 2026 });
// { holidays: [{ date: '2026-01-01', name: "New Year's Day", type: 'public' }, ...] }Documents
processImage
Resize, crop, format-convert, and optimize images. Returns an ArrayBuffer.
import { readFileSync, writeFileSync } from 'node:fs';
const imageBuffer = readFileSync('photo.jpg');
const result = await client.documents.processImage({
image: imageBuffer,
operations: {
resize: { width: 800, height: 600, fit: 'cover' },
format: 'webp',
quality: 80,
},
});
writeFileSync('photo-optimized.webp', Buffer.from(result));generatePdf
Generate PDFs from HTML or URLs. Returns an ArrayBuffer.
import { writeFileSync } from 'node:fs';
const pdf = await client.documents.generatePdf({
html: '<h1>Invoice #1234</h1><p>Total: AED 500.00</p>',
options: {
format: 'A4',
margin: { top: '20mm', bottom: '20mm' },
},
});
writeFileSync('invoice.pdf', Buffer.from(pdf));Communication
translate
Translate text between languages. Arabic and regional languages are fully supported.
const result = await client.communication.translate({
text: 'Hello, how are you?',
target: 'ar',
});
// { translated_text: 'مرحباً، كيف حالك؟', confidence: 0.98 }shortenUrl
Shorten URLs with optional custom aliases.
const result = await client.communication.shortenUrl({
url: 'https://example.com/very/long/path',
custom_alias: 'my-link',
});
// { short_url: 'https://klj.to/my-link', alias: 'my-link' }Utility
generateQr
Generate QR code images. Returns an ArrayBuffer.
import { writeFileSync } from 'node:fs';
const qr = await client.utility.generateQr({
data: 'https://khaleejiapi.dev',
size: 512,
format: 'png',
});
writeFileSync('qr.png', Buffer.from(qr));checkFraud
Detect fraud signals across email, IP, phone, and name.
const result = await client.utility.checkFraud({
email: '[email protected]',
ip: '185.234.218.0',
});
// {
// risk_score: 85,
// risk_level: 'high',
// signals: [{ type: 'disposable_email', description: '...', severity: 'high' }]
// }Error Handling
All errors extend KhaleejiAPIError which includes code, statusCode, and message:
import { KhaleejiAPI, KhaleejiAPIError, RateLimitError, AuthenticationError } from '@khaleejiapi/sdk';
const client = new KhaleejiAPI({ apiKey: 'kapi_live_...' });
try {
await client.validation.validateEmail({ email: '[email protected]' });
} catch (err) {
if (err instanceof RateLimitError) {
console.log(`Rate limited. Retry after ${err.retryAfter}s`);
} else if (err instanceof AuthenticationError) {
console.log('Invalid API key');
} else if (err instanceof KhaleejiAPIError) {
console.log(`API error: ${err.code} — ${err.message} (HTTP ${err.statusCode})`);
}
}Error Classes
| Class | Status Code | Description |
|-------|-------------|-------------|
| AuthenticationError | 401, 403 | Invalid or missing API key |
| ValidationError | 400 | Invalid request parameters |
| NotFoundError | 404 | Endpoint or resource not found |
| RateLimitError | 429 | Rate limit exceeded |
| InternalError | 5xx | Server error |
| ConnectionError | — | Network or timeout error |
| KhaleejiAPIError | any | Base class for all API errors |
Rate Limits
Rate limit information is available after every request:
await client.validation.validateEmail({ email: '[email protected]' });
console.log(client.rateLimit);
// { limit: 1000, remaining: 999, reset: 1700000000 }The SDK automatically retries on 429 responses using the Retry-After header value.
TypeScript Support
The SDK is written in TypeScript and ships with complete type definitions. All request parameters and response types are fully typed:
import type {
ValidateEmailParams,
ValidateEmailData,
LookupIpData,
GetExchangeRatesData,
} from '@khaleejiapi/sdk';Requirements
- Node.js 18.0.0 or later
- Deno 1.28 or later
- Bun 0.5 or later
- Modern browsers with
fetchsupport
Contributing
- Clone the repository
- Install dependencies:
pnpm install - Run tests:
pnpm test - Build:
pnpm build
License
Built with ❤️ for the Middle East developer community by KhaleejiAPI.
