Ultimate Guide

Ultimate Guide to API Keys

Everything you need for API keys in one place: creation, authentication format, first-call setup, troubleshooting, and secure rotation.

API Key Connection Guide (Onboarding Audit)

Updated from onboarding audit T-1083 and support escalations. These checks incorporate fixes from PRs #5147, #5149, and #5145 so first-call setup is clearer and faster.

  1. Generate a new key and copy the full value before closing the creation dialog. Masked dashboard values are reference-only.
  2. For REST requests, send the Authorization header with the Bearer scheme exactly once per request.
  3. Use a known-good path first: /api/v1/email/[email protected].
  4. When using SDKs, use the per-language quickstart pages instead of mixing SDK constructors with raw REST header patterns.

Troubleshoot by error class:

  • 401: key is masked, incomplete, revoked, or missing the Bearer prefix.
  • 404: path must start with /api/v1/.
  • 429: check Usage API docs and rate-limit headers.

Quickstarts: TypeScript, Python, Go, Swift, Kotlin, and PHP.

Legacy docs note: older links to /docs/v1/translate map to the maintained alias at /docs/v1/utils/translate.

API Keys

KhaleejiAPI uses API keys to authenticate requests. You can view and manage your API keys in your dashboard.

Getting your API key

  1. Sign up for a free account at khaleejiapi.dev/signup
  2. Navigate to the API Keys section in your dashboard
  3. Click “Create new key” and give it a descriptive name
  4. Copy your full API key before closing the dialog — it starts with kapi_live_ and is shown only once

What the dashboard copy actions mean

  • Immediately after you create a key, the dashboard shows the full key, auto-copies it, and keeps a Copy API Key button available until you dismiss the dialog.
  • After that dialog closes, stored keys are shown masked for safety. These masked values are for reference only and cannot authenticate requests.
  • If you only see a masked key later, use the stored full key you copied earlier or create a new key and copy it before closing the dialog.

Authentication Method

Every request must include your API key in the Authorization header using the Bearer scheme. This is the canonical and recommended method for all new integrations. Legacy clients may still use x-api-key as a compatibility fallback, but Authorization: Bearer is the standard going forward.

Required

Authorization: Bearer <your-key>

bash
curl -X GET "https://khaleejiapi.dev/api/v1/ip/lookup?ip=8.8.8.8" \
-H "Authorization: Bearer YOUR_API_KEY"

REST clients

cURL, fetch, requests, Go, and raw PHP HTTP calls should send Authorization header shown above on every request.

Official SDKs

SDK constructors expect the raw key only. Do not prepend Bearer when you initialize the client — the SDK adds the header automatically.

Legacy fallback: x-api-key

x-api-key is accepted as a compatibility fallback for older clients, but Authorization: Bearer is the canonical method for new integrations. Avoid query-string auth or client-side browser calls with your real key.

Common Pitfalls

These are the most frequent mistakes that cause authentication errors on the first call.

Using x-api-key as your primary integration header

Legacy clients may still be accepted when they send x-api-key. We now treat it as a compatibility fallback when the Authorization header is malformed or uses a different auth scheme and x-api-key contains a valid kapi_ key. New integrations should always use the standard Authorization header format as the canonical method:

bash
curl -H "Authorization: Bearer kapi_live_your_key_here" \
https://khaleejiapi.dev/api/v1/ip/lookup

Sending the raw key without the Bearer prefix

The header value must be exactly Bearer <your-key>. Omitting Bearer or adding extra spaces returns 401.

✗ Wrong

text
Authorization: kapi_live_your_key_here

✓ Correct

text
Authorization: Bearer kapi_live_your_key_here

Wrong JS/TS SDK initialization — passing a bare string

The JavaScript/TypeScript SDK expects an options object with an apiKey property. Passing a bare string or including the Bearer prefix in the constructor value throws a runtime error.

✗ Wrong

javascript
// TypeError at runtime
const client = new KhaleejiAPI('kapi_live_...');

✓ Correct

javascript
const client = new KhaleejiAPI({
apiKey: 'kapi_live_your_key_here',
});

Exposing the key in client-side code

Bundling your API key into a browser or mobile app makes it visible in the network tab and public source maps. Anyone who finds it can exhaust your quota. Always call the API from your backend server or use the CORS & browser integration guide for the proxy pattern.

Using SDKs

Our official SDKs handle authentication automatically. Initialize the client once with your API key and every subsequent request is authenticated for you.

JavaScript / TypeScript

typescript
import { KhaleejiAPI } from '@khaleejiapi/sdk';
// Pass an options object — apiKey is a required named property
const client = new KhaleejiAPI({ apiKey: 'kapi_live_your_key_here' });
// All subsequent requests are automatically authenticated
const result = await client.geo.lookupIp({ ip: '8.8.8.8' });

Python

python
from khaleejiapi import KhaleejiAPI
# Initialize with your API key
client = KhaleejiAPI("kapi_live_your_key_here")
# All subsequent requests are automatically authenticated
result = client.geo.lookup_ip("8.8.8.8")

Go

go
package main
import (
"context"
"fmt"
khaleejiapi "github.com/khaleejiapi/sdk-go"
)
func main() {
client := khaleejiapi.New("kapi_live_your_key_here")
ctx := context.Background()
ip, _ := client.Geo.LookupIp(ctx, "8.8.8.8")
fmt.Println(ip.Country)
}

Swift (iOS / macOS)

swift
import KhaleejiAPI
let client = KhaleejiAPI(apiKey: "kapi_live_your_key_here")
let ip = try await client.geo.lookupIp("8.8.8.8")
print(ip.country)

Kotlin (Android / JVM)

kotlin
import dev.khaleejiapi.KhaleejiAPI
val client = KhaleejiAPI("kapi_live_your_key_here")
val ip = client.geo.lookupIp("8.8.8.8")
println(ip.country)

PHP

php
<?php
use KhaleejiAPI\KhaleejiAPI;
$client = new KhaleejiAPI('kapi_live_your_key_here');
$ip = $client->geo->lookupIp('8.8.8.8');
echo $ip['country'];

Best Practices

Use Environment Variables

Store your API key in environment variables instead of hardcoding it in source code.

bash
# .env.local (never commit this file)
KHALEEJI_API_KEY=kapi_live_your_key_here
typescript
// JavaScript / TypeScript — pass an options object
const client = new KhaleejiAPI({ apiKey: process.env.KHALEEJI_API_KEY! });
python
# Python
import os
client = KhaleejiAPI(os.environ["KHALEEJI_API_KEY"])

Use Different Keys for Each Environment

Create separate API keys for development, staging, and production. This limits blast radius if a key leaks and makes it easy to track usage per environment.

Rotate Keys Regularly

Periodically rotate your API keys, especially if you suspect they may have been compromised.

Use Server-Side Requests

Make API calls from your backend server, not directly from client-side code.

Authentication Errors

Status CodeErrorDescription
401UNAUTHORIZED / INVALID_API_KEY_FORMAT / INVALID_API_KEY / API_KEY_REVOKED / API_KEY_EXPIREDMissing or malformed auth header, invalid key format/value, or revoked/expired key (with targeted guidance in the response message)
403forbiddenAPI key doesn't have access to this resource
429rate_limitedToo many requests. Check rate limits.

Targeted 401 messages you may see

The snippets below are message prefixes from error.message. Compare using exact prefix matching (for example message.startsWith(...)) because the tail of the message can include extra context.

  • Missing Authorization header... → No auth header was sent. Add Authorization: Bearer <your-key> (or x-api-key as a compatibility fallback).
  • API key detected in the Authorization header without the required prefix... → You sent a raw kapi_ key without the expected scheme token.
  • KhaleejiAPI requires the Authorization: Bearer <your-key> header... → You sent a different auth scheme (for example: Basic/JWT) with no valid fallback key.
  • Authorization header is present but empty... → Header exists but value is blank or whitespace.
  • API key must start with kapi_live_ or kapi_test_... → Wrong provider key or malformed KhaleejiAPI key.
  • Invalid API key — no matching live (kapi_live_) key found... → The key format is correct, but it does not match an active key in that environment.
  • This API key has expired... → Rotate the key from the dashboard and update your integration.

Troubleshooting 401 Unauthorized

A 401 means we received your request but the API key was missing, malformed, or rejected. Walk this list top to bottom — most issues are caught in the first three checks.

Use Authorization: Bearer <your-key> exactly

Do not send custom auth headers, query params, or raw keys without the Bearer scheme. Use one header with one space between Bearer and your key. Legacy x-api-key fallback exists only for backward compatibility and should not be your default integration path.

No leading or trailing whitespace

When copy-pasting from the dashboard, a stray space or newline at the end of the value is the most common cause. In Bash use $KHALEEJI_API_KEY via export rather than pasting inline.

Key is active and not revoked

Open Dashboard → API Keys. The key's status badge must read Active. A revoked key returns 401 immediately and cannot be revived — create a new key instead.

Sandbox key vs live endpoint

Sandbox keys (created with the “Sandbox Mode” toggle) are limited to 10 req/min and 1,000/month against test fixtures. They will not authenticate against high-volume live data — create a non-sandbox key for production traffic.

Right project / environment

Teams often have separate keys per environment. Confirm the value in your .env matches the dashboard for this environment, not staging.

Capture the request id

Every response includes x-request-id. Include it when you contact support and we can pull the exact log line in seconds. See the troubleshooting guide for the full error catalog.

API Key Self-Test Tool

The Self-Test button in Dashboard → API Keys lets you verify a key end-to-end without leaving your browser. It fires a live authenticated request to /api/v1/auth/test, then displays the exact request headers sent, the response headers received, the response body, and the HTTP status code — all in one panel.

Use it to confirm a key works immediately after creation, or to isolate a 401 problem without writing any code.

Step 1 — Open the self-test dialog

In Dashboard → API Keys, click the Test button on any key row. A dialog prompts you to paste the raw key value. The dashboard only stores masked references for security, so you must supply the full key you saved at creation time.

Step 2 — Run the test

Click Run Test. The tool sends GET /api/v1/auth/test with your key in the Authorization: ******;your-key> header and waits for the response.

Step 3 — Inspect the results

The results panel shows four sections: Request Headers, Response Headers, Response Body, and the HTTP status. A 200 OK with {"authenticated": true} confirms the key is valid. Any other status code includes the full error payload so you can diagnose the problem immediately.

أداة الاختبار الذاتي لمفاتيح API

يتيح لك زر الاختبار الذاتي في لوحة التحكم ← مفاتيح API التحقق من صحة المفتاح بالكامل دون مغادرة المتصفح. تُرسِل الأداة طلبًا مباشرًا إلى /api/v1/auth/test وتعرض ترويسات الطلب وترويسات الاستجابة والنص الكامل للاستجابة ورمز الحالة HTTP — كل ذلك في لوحة واحدة.

  1. افتح لوحة التحكم ← مفاتيح API وانقر على زر اختبار في صف المفتاح المطلوب.
  2. الصق قيمة المفتاح الكاملة في مربع الحوار (القيمة المُخفاة في لوحة التحكم مرجعية فقط).
  3. انقر على تشغيل الاختبار وراجع النتائج. يُشير 200 OK مع {"authenticated": true} إلى أن المفتاح صالح وجاهز للاستخدام.

Revoke and rotate keys

Revoke a key the moment you suspect it has leaked — revocation is instant and irreversible. The full incident playbook is at /docs/security/leaked-keys. The short version:

  1. Open Dashboard → API Keys and create a replacement key first.
  2. Update your deployment's environment variable.
  3. Redeploy / restart the workers that hold the key.
  4. Click Revoke on the old key.
  5. Audit recent requests via the dashboard or GET /api/dashboard/api-keys/usage — an unfamiliar IP or country usually means the key was already abused.
  6. Add a pre-commit secret scanner (e.g. gitleaks) so the next leak is caught before it pushes.