> ## Documentation Index
> Fetch the complete documentation index at: https://docs.knoxcall.com/llms.txt
> Use this file to discover all available pages before exploring further.

# KnoxCall AI Integration Guide

> Explicit implementation details for integrating APIs with KnoxCall. Covers routing, path concatenation, code changes, and common mistakes.

# KnoxCall AI Integration Guide

> **For AI Assistants:** This guide provides explicit implementation details for helping developers integrate their APIs with KnoxCall. Read this carefully to avoid common mistakes.

## What is KnoxCall?

KnoxCall is an **API proxy** that sits between your application and external APIs. It:

* Routes API calls through a central proxy
* Injects credentials/secrets automatically
* Logs all requests for monitoring
* Manages API keys across environments

## Critical Architecture Facts

**IMPORTANT:** Understanding how KnoxCall routing works is critical to correct implementation.

### Route Identification

* ✅ Routes are identified by the `x-knoxcall-route` header
* ❌ Routes are **NOT** identified by path matching or URL patterns
* **Code proof:** `const routeName = req.headers['x-knoxcall-route']`

### Path Concatenation

* KnoxCall concatenates: `target_base_url.pathname + client_request.path`
* **Implementation:** `combinedPath = targetBase.pathname.replace(/\/$/, '') + clientPath`
* The client path is **APPENDED as-is** to the target base path
* Paths are **NOT stripped, matched, or modified**

### What This Means

If a route's `target_base_url` is `https://api.example.com/v1/users`, and you send a request to `https://{slug}.knoxcall.com/123`:

* KnoxCall extracts the target base pathname: `/v1/users`
* KnoxCall takes your request path: `/123`
* KnoxCall concatenates them: `/v1/users` + `/123` = `/v1/users/123`
* Final upstream request: `https://api.example.com/v1/users/123`

## How KnoxCall Proxy Works (Step-by-Step)

**Example:** Route has `target_base_url: https://api.example.com/integration/patients`

1. **User sends:** `GET https://{slug}.knoxcall.com/123` with header `x-knoxcall-route: ROUTE_ID`
2. **KnoxCall looks up route:** Uses the `x-knoxcall-route` header to find the route configuration (NOT path matching!)
3. **KnoxCall extracts paths:**
   * Client path from request: `/123`
   * Target base path from route config: `/integration/patients`
4. **KnoxCall builds final URL:** Concatenates paths = `/integration/patients/123`
5. **KnoxCall injects:** the secret/API key from the route configuration
6. **KnoxCall forwards:** `GET https://api.example.com/integration/patients/123` with injected credentials
7. **Returns:** the response to the user

## Common Mistakes to AVOID

### ❌ Mistake #1: Duplicating the Base Path

**WRONG:**

```bash theme={"dark"}
# Route target_base_url: https://api.example.com/v1/users
# User sends:
curl https://{slug}.knoxcall.com/v1/users/123 \
  -H 'x-knoxcall-route: route-id'

# Result: https://api.example.com/v1/users/v1/users/123 (DUPLICATED!)
```

**CORRECT:**

```bash theme={"dark"}
# Route target_base_url: https://api.example.com/v1/users
# User sends:
curl https://{slug}.knoxcall.com/123 \
  -H 'x-knoxcall-route: route-id'

# Result: https://api.example.com/v1/users/123 (CORRECT!)
```

### ❌ Mistake #2: Assuming Path Matching

KnoxCall does **NOT** match paths or strip base paths. It simply concatenates:

* `target_base_url.pathname` + `your_request.path` = `final_url.pathname`

### ❌ Mistake #3: Including API Keys in Code

After integrating with KnoxCall, the API key should be **removed** from your code. KnoxCall injects it automatically.

## The 3 Code Changes Required

When integrating an API with KnoxCall, you need to make exactly 3 changes:

### 1. Replace the Base URL

Your KnoxCall proxy host is your tenant subdomain: `https://{slug}.knoxcall.com` (replace `{slug}` with your tenant slug; use `https://sandbox-{slug}.knoxcall.com` for the sandbox).

**Critical Path Calculation:**

* Original API call: `https://api.example.com/v1/users/123`
* Route's target\_base\_url: `https://api.example.com/v1/users`
* **Step 1:** Remove target\_base\_url from original → `/123`
* **Step 2:** KnoxCall URL = proxy domain + what's left → `https://{slug}.knoxcall.com/123`
* **Step 3:** Verify → KnoxCall receives `/123`, forwards to `target_base_url + /123` = `https://api.example.com/v1/users/123` ✅

**NEVER include ANY part of the target\_base\_url path in the KnoxCall URL!**

### 2. Add KnoxCall Headers

```http theme={"dark"}
x-knoxcall-key: <CLIENT_API_KEY>       # From KnoxCall dashboard
x-knoxcall-route: <ROUTE_ID>           # The route you configured
x-knoxcall-environment: production      # Optional; defaults to your tenant's default environment (usually 'production')
```

### 3. Remove the Old API Key/Secret

KnoxCall injects the API key automatically based on the route configuration. Remove it from:

* Request headers
* Query parameters
* Request body
* Authorization headers

## Complete Examples

### Example 1: Python with Query Parameter Auth

**Scenario:** Route target\_base\_url is `https://app.scrapingbee.com/api/v1/`

**Before:**

```python theme={"dark"}
import requests

response = requests.get(
    "https://app.scrapingbee.com/api/v1/",
    params={
        "api_key": SCRAPINGBEE_API_KEY,  # Secret in code
        "url": "https://example.com"
    }
)
```

**After:**

```python theme={"dark"}
import requests

# Route's target_base_url already contains /api/v1/
# So we only append what comes after (nothing in this case, so just "/")
response = requests.get(
    "https://{slug}.knoxcall.com/",
    headers={
        "x-knoxcall-key": KNOXCALL_API_KEY,
        "x-knoxcall-route": "abc-123-route-id"
    },
    params={
        "url": "https://example.com"
        # api_key removed - KnoxCall injects it
    }
)
```

### Example 2: cURL with Header Auth

**Scenario:** Route target\_base\_url is `https://api.stripe.com/v1/customers`, calling `/v1/customers/cus_123`

**Before:**

```bash theme={"dark"}
curl https://api.stripe.com/v1/customers/cus_123 \
  -H 'Authorization: Bearer sk_test_secret_key'
```

**After:**

```bash theme={"dark"}
# Original: https://api.stripe.com/v1/customers/cus_123
# Target base: https://api.stripe.com/v1/customers
# Path after base: /cus_123
# KnoxCall URL: proxy + /cus_123

curl https://{slug}.knoxcall.com/cus_123 \
  -H 'x-knoxcall-key: your-knoxcall-api-key' \
  -H 'x-knoxcall-route: abc-123-route-id'
# Authorization header removed - KnoxCall injects it
```

### Example 3: PHP with Complex Path

**Scenario:** Route target\_base\_url is `https://api.endoaxis.com/integration/patients`, calling patient ID 789

**Before:**

```php theme={"dark"}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.endoaxis.com/integration/patients/789");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $api_token
]);
$response = curl_exec($ch);
```

**After:**

```php theme={"dark"}
// Original: https://api.endoaxis.com/integration/patients/789
// Target base: https://api.endoaxis.com/integration/patients
// Path after base: /789
// KnoxCall URL: proxy + /789

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://{slug}.knoxcall.com/789");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'x-knoxcall-key: ' . $knoxcall_api_key,
    'x-knoxcall-route: abc-123-route-id'
    // Authorization removed - KnoxCall injects it
]);
$response = curl_exec($ch);
```

## Path Calculation Algorithm

When helping a developer convert their API call to KnoxCall, **always follow these steps:**

```text theme={"dark"}
Given:
- original_url = "https://api.example.com/v1/users/123/posts/456"
- target_base_url = "https://api.example.com/v1/users" (from route config)
- proxy_domain = "https://{slug}.knoxcall.com"

Step 1: Extract the path after target_base_url
  original_path = "/v1/users/123/posts/456"
  base_path = "/v1/users"
  remaining_path = original_path.replace(base_path, "") = "/123/posts/456"

Step 2: Build KnoxCall URL
  knoxcall_url = proxy_domain + remaining_path
  knoxcall_url = "https://{slug}.knoxcall.com/123/posts/456"

Step 3: Verify
  When KnoxCall receives: "/123/posts/456"
  It will forward to: target_base_url + "/123/posts/456"
  Result: "https://api.example.com/v1/users/123/posts/456" ✅
```

## Integration Patterns

### Pattern 1: Base Path Only (No Additional Path)

```text theme={"dark"}
Original: https://api.example.com/v1/endpoint
Route target: https://api.example.com/v1/endpoint
KnoxCall call: https://{slug}.knoxcall.com/
```

### Pattern 2: Base Path + Resource ID

```text theme={"dark"}
Original: https://api.example.com/v1/users/123
Route target: https://api.example.com/v1/users
KnoxCall call: https://{slug}.knoxcall.com/123
```

### Pattern 3: Base Path + Nested Resources

```text theme={"dark"}
Original: https://api.example.com/v1/users/123/orders/456
Route target: https://api.example.com/v1/users
KnoxCall call: https://{slug}.knoxcall.com/123/orders/456
```

### Pattern 4: Base Path + Query Parameters

```text theme={"dark"}
Original: https://api.example.com/v1/search?q=test&limit=10
Route target: https://api.example.com/v1/search
KnoxCall call: https://{slug}.knoxcall.com/?q=test&limit=10
```

## When to Create Routes

Create one route for each unique combination of:

* **API endpoint** (base URL)
* **Authentication method** (which secret/credentials to use)
* **HTTP method** (GET, POST, etc.) - if different methods need different config

You can use the same route for multiple resource IDs:

* ✅ One route for all Stripe customers: `/v1/customers/*`
* ❌ Don't create separate routes for each customer ID

## Environment Support

KnoxCall supports multiple environments (development, staging, production):

```bash theme={"dark"}
# Explicitly target the production environment
# (omit the header to use your tenant's default environment)
curl https://{slug}.knoxcall.com/123 \
  -H 'x-knoxcall-route: route-id' \
  -H 'x-knoxcall-environment: production'

# Use staging secrets
curl https://{slug}.knoxcall.com/123 \
  -H 'x-knoxcall-route: route-id' \
  -H 'x-knoxcall-environment: staging'
```

## Testing Your Integration

After making the 3 code changes:

1. **Check the logs** in KnoxCall dashboard to see the actual upstream request
2. **Verify the URL** in logs matches your expected API endpoint
3. **Check for auth errors** - if you see 401/403, the secret might not be injected correctly
4. **Look for path duplication** - if you see `/v1/users/v1/users`, you included the base path in your request

## Advanced: OAuth2 Token Management

For OAuth2 APIs, KnoxCall handles token refresh automatically:

```python theme={"dark"}
# You don't manage tokens - just make the call
response = requests.get(
    "https://{slug}.knoxcall.com/me",
    headers={
        "x-knoxcall-key": KNOXCALL_API_KEY,
        "x-knoxcall-route": "oauth-route-id"
    }
)
# KnoxCall automatically:
# 1. Checks if token is expired
# 2. Refreshes it if needed
# 3. Injects the valid token
# 4. Forwards your request
```

## Common Error Messages

### "Route not found"

* Check that `x-knoxcall-route` header contains the correct route ID
* Verify the route exists in your KnoxCall dashboard

### "Client not authorized"

* Check that `x-knoxcall-key` header contains your client API key
* Verify the client has access to this route

### "Secret not found for environment"

* The route's secret doesn't have a value for the requested environment
* Add the secret value for that environment or switch environments

### "404 Not Found" from upstream API

* Likely path duplication or incorrect path calculation
* Check KnoxCall logs to see the actual URL being forwarded
* Verify you're not including the base path in your request

## Best Practices for AI Assistants

When helping developers integrate with KnoxCall:

1. **Always work through the path calculation step-by-step** - don't guess
2. **Show before/after code diffs** - makes the changes crystal clear
3. **Explicitly point out the removed API key** - security win!
4. **Use the actual route ID** from the route they configured
5. **Verify the math** - trace through what KnoxCall will forward
6. **Don't invent features** - KnoxCall is a proxy, nothing more

## Summary

**KnoxCall is ONLY a proxy.** It:

* Identifies routes by `x-knoxcall-route` header
* Concatenates `target_base_url.pathname + request.path`
* Injects secrets automatically
* Forwards the request to the upstream API

**For the proxy data-plane, there is NO:**

* Path matching or pattern matching
* Path stripping or modification
* SDK or library required to make proxied calls — you just send the headers above
* Environment variable injection

(KnoxCall does ship official SDKs — Node, Go, PHP, Python, Ruby — and a management Secrets API for configuring routes and secrets, but the proxy data-plane itself needs none of them.)

When in doubt, remember: **Header-based routing + path concatenation = final URL**

***

*This guide is maintained by the KnoxCall team. For questions or issues, visit [https://docs.knoxcall.com](https://docs.knoxcall.com)*
