> ## 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.

# AI-Powered Route Setup

> Paste your API request code and let AI extract the configuration automatically. Supports cURL, JavaScript, Python, PHP, and more.

# AI-Powered Route Setup

Paste your existing API code and let KnoxCall's AI extract the route configuration automatically.

## What is AI-Powered Route Setup?

Instead of manually filling in route details, **paste your existing API request code** (cURL, JavaScript, Python, etc.) and KnoxCall's AI will:

* 🔍 Extract URL and HTTP method
* 📋 Detect headers and content type
* 📦 Parse request body structure
* 🔐 Identify secrets (API keys, tokens)
* 💡 Suggest where secrets should be injected
* 🏷️ Recommend a route name
* ⚡ Generate the complete route configuration

**Perfect for:** Migrating existing API integrations to KnoxCall without rewriting configurations manually.

## Supported Languages

KnoxCall's AI parser supports code from:

* **cURL** (most common)
* **JavaScript** (fetch, axios, node-fetch)
* **Python** (requests, urllib, httpx)
* **PHP** (cURL, Guzzle, file\_get\_contents)
* **Ruby** (net/http, RestClient, HTTParty)
* **Go** (net/http, resty)
* **Java** (HttpClient, OkHttp, RestTemplate)
* **C#** (HttpClient, RestSharp)

Even if your language isn't perfectly recognized, the AI can often extract the important details.

## How It Works

```text theme={"dark"}
1. Navigate to Routes → Create Route → Automated Setup
     ↓
2. Paste your API request code
     ↓
3. AI analyzes the code:
   - Detects programming language
   - Extracts URL, method, headers, body
   - Identifies secrets (API keys, tokens)
   - Suggests secret injection locations
     ↓
4. Review detected configuration:
   - Route name suggestion
   - URL and method
   - Headers and body
   - Detected secrets (optional to save)
     ↓
5. Customize if needed → Create route
```

## Step-by-Step Guide

### Step 1: Open Create Route Modal

1. Navigate to **Routes**
2. Click **Create Route** button
3. Choose **Automated Setup**

### Step 2: Paste Your Code

Copy your existing API request code and paste it:

**Example 1: cURL Command**

```bash theme={"dark"}
curl -X POST "https://api.stripe.com/v1/charges" \
  -H "Authorization: Bearer sk_live_abc123xyz789def456" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "amount=1000&currency=usd"
```

**Example 2: JavaScript (fetch)**

```javascript theme={"dark"}
const stripeApiKey = "sk_live_abc123xyz789def456";

fetch("https://api.stripe.com/v1/charges", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${stripeApiKey}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    amount: 1000,
    currency: "usd",
    source: "tok_visa"
  })
});
```

**Example 3: Python (requests)**

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

api_key = "sk_live_abc123xyz789def456"
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}
payload = {
    "amount": 1000,
    "currency": "usd"
}

response = requests.post(
    "https://api.stripe.com/v1/charges",
    headers=headers,
    json=payload
)
```

**Example 4: PHP (cURL)**

```php theme={"dark"}
$apiKey = "sk_live_abc123xyz789def456";
$ch = curl_init("https://api.stripe.com/v1/charges");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer " . $apiKey,
    "Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    "amount" => 1000,
    "currency" => "usd"
]));
$response = curl_exec($ch);
```

### Step 3: Click "Parse & Continue"

AI begins analyzing your code. You'll see progress messages:

```text theme={"dark"}
🔍 Analyzing code structure...
📝 Detecting programming language...
🌐 Extracting API endpoint...
📊 Parsing request headers...
🔐 Detecting secrets and credentials...
📦 Analyzing request body...
💡 Generating configuration suggestions...
✅ Analysis complete!
```

This takes 3-5 seconds.

### Step 4: Review Detected Configuration

AI shows what it extracted:

#### Route Name

```text theme={"dark"}
Suggested: stripe-charges
```

*Based on URL path and detected service*

You can edit this before creating the route.

#### Target URL

```text theme={"dark"}
https://api.stripe.com/v1/charges
```

#### HTTP Method

```text theme={"dark"}
POST
```

#### Headers

```json theme={"dark"}
{
  "Content-Type": "application/json"
}
```

*Non-secret headers are shown here*

#### Request Body

```json theme={"dark"}
{
  "amount": 1000,
  "currency": "usd",
  "source": "tok_visa"
}
```

*Formatted and ready for injection configuration*

### Step 5: Review Detected Secrets (Optional)

If AI found secrets in your code:

**Detected: `sk_live_abc123xyz789def456`**

| Property              | Value                                                                   |
| --------------------- | ----------------------------------------------------------------------- |
| **Original Variable** | `stripeApiKey`                                                          |
| **Suggested Name**    | `stripe-api-key`                                                        |
| **Type**              | Bearer Token                                                            |
| **AI Suggestion**     | Inject in **Header**: `Authorization: Bearer {{secret:stripe-api-key}}` |

**Options:**

* ☑️ **Create this secret** (checked by default)
* 📝 **Edit secret name** (click to customize)
* 👁️ **Show/hide value** (for verification)

<Warning>
  **Secret values are visible during setup!** Make sure nobody is watching your screen. After clicking "Create Route", the value is encrypted and never shown again.
</Warning>

#### AI Insertion Suggestions

For each secret, AI recommends:

**🤖 AI Suggestion:**

* **Location:** Header (or Body)
* **Header Name:** `Authorization` (if header)
* **JSON Path:** `credentials.token` (if body)
* **Description:** "Stripe API authentication token"

You don't need to manually configure this - KnoxCall will apply it automatically!

### Step 6: Select Clients (Optional)

Choose which client IP addresses can use this route:

* [ ] Production Server (52.123.45.67)
* [ ] Office Network (192.168.1.0/24)
* [x] My Development Machine (203.45.67.89)

Or skip and assign clients later.

### Step 7: Create Route

Click **Create Route**

KnoxCall will:

1. Create the route with extracted configuration
2. Save detected secrets (if selected)
3. Configure header/body injection per AI suggestions
4. Assign selected clients
5. Enable the route

Done! 🎉

## Advanced Features

### Multi-Route Detection

If you paste code with **multiple API calls**, AI detects them all:

**Example: Multiple endpoints in one script**

```javascript theme={"dark"}
// Create customer
fetch("https://api.stripe.com/v1/customers", {
  method: "POST",
  headers: { "Authorization": `Bearer ${stripeKey}` },
  body: JSON.stringify({ email: "customer@example.com" })
});

// Create charge
fetch("https://api.stripe.com/v1/charges", {
  method: "POST",
  headers: { "Authorization": `Bearer ${stripeKey}` },
  body: JSON.stringify({ amount: 1000, currency: "usd" })
});
```

**AI Result: 2 routes detected**

1. `stripe-customers` → POST to `/v1/customers`
2. `stripe-charges` → POST to `/v1/charges`

**Shared secrets detected:**

* `stripe-api-key` (used by both routes)

You can:

* ✅ Select which routes to create
* ✅ Create shared secrets once (available to all routes)
* ✅ Create all routes in batch

<Note>
  **Batch route creation** automatically creates all detected routes with one click. Perfect for migrating entire integrations!
</Note>

### Secret Reuse

If a secret **already exists** in KnoxCall:

```text theme={"dark"}
✓ Secret "stripe-api-key" already exists
```

AI won't create a duplicate. It will use the existing secret in the route configuration.

### Fallback to Manual Parsing

If AI can't extract all details (e.g., URL is a variable):

```text theme={"dark"}
⚠️ Could not detect URL
```

You'll be prompted to enter missing details manually before creating the route.

**AI still provides:**

* Headers
* Body structure
* Secrets detection

You just fill in the URL.

### Language Detection Confidence

AI shows confidence level:

```text theme={"dark"}
🔍 Detected: JavaScript (High Confidence)
```

**High confidence:**

* Standard library usage (fetch, requests, curl)
* Clear syntax
* Complete request structure

**Medium confidence:**

* Custom HTTP library
* Partial code snippet
* Unusual formatting

**Low confidence:**

* Ambiguous code
* Multiple languages mixed
* Very short snippet

Even at low confidence, AI usually extracts useful details!

## Example Use Cases

### Use Case 1: Migrate cURL to KnoxCall

**Scenario:** You have a cURL command from API documentation

**Code:**

```bash theme={"dark"}
curl -X POST "https://api.sendgrid.com/v3/mail/send" \
  -H "Authorization: Bearer SG.abc123xyz789" \
  -H "Content-Type: application/json" \
  -d '{
    "personalizations": [{"to": [{"email": "recipient@example.com"}]}],
    "from": {"email": "sender@example.com"},
    "subject": "Test Email",
    "content": [{"type": "text/plain", "value": "Hello!"}]
  }'
```

**AI Extracts:**

* Route name: `sendgrid-mail-send`
* URL: `https://api.sendgrid.com/v3/mail/send`
* Method: POST
* Secret: `sendgrid-api-key` → `SG.abc123xyz789`
* Injection: `Authorization: Bearer {{secret:sendgrid-api-key}}`

**Result:** Route ready to use immediately!

### Use Case 2: Import Production Code

**Scenario:** You're proxying an existing JavaScript API integration

**Code:**

```javascript theme={"dark"}
async function createCustomer(email) {
  const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

  const customer = await stripe.customers.create({
    email: email,
    description: 'New customer'
  });

  return customer;
}
```

**AI Extracts:**

* Route name: `stripe-customers-create`
* URL: `https://api.stripe.com/v1/customers` (AI knows Stripe SDK)
* Method: POST
* Secret: `stripe-secret-key` (from environment variable)
* Body structure:
  ```json theme={"dark"}
  {
    "email": "{{var:email}}",
    "description": "New customer"
  }
  ```

**Bonus:** AI suggests using `{{var:email}}` for the email parameter!

### Use Case 3: Reverse Engineering API Calls

**Scenario:** You found API request in browser DevTools

**Code (copied from Network tab):**

```text theme={"dark"}
POST /api/v2/orders HTTP/1.1
Host: internal-api.company.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json

{"product_id": 123, "quantity": 5, "customer_id": 456}
```

**AI Extracts:**

* Route name: `orders-create`
* URL: `https://internal-api.company.com/api/v2/orders`
* Method: POST
* Secret: `jwt-token` → `eyJhbGci...`
* Body structure: `{"product_id": 123, "quantity": 5, "customer_id": 456}`

Perfect for setting up proxies to internal APIs!

### Use Case 4: Python Script Migration

**Scenario:** Migrating Python script to run through KnoxCall

**Code:**

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

twilio_account_sid = os.getenv("TWILIO_ACCOUNT_SID")
twilio_auth_token = os.getenv("TWILIO_AUTH_TOKEN")

url = f"https://api.twilio.com/2010-04-01/Accounts/{twilio_account_sid}/Messages.json"
auth = (twilio_account_sid, twilio_auth_token)

data = {
    "From": "+15551234567",
    "To": "+15559876543",
    "Body": "Hello from KnoxCall"
}

response = requests.post(url, auth=auth, data=data)
```

**AI Extracts:**

* Route name: `twilio-messages`
* URL: `https://api.twilio.com/2010-04-01/Accounts/{{secret:twilio-account-sid}}/Messages.json`
* Method: POST
* Secrets:
  * `twilio-account-sid`
  * `twilio-auth-token`
* Authentication: Basic Auth (both secrets)
* Body: Form data with From/To/Body

**Note:** AI even detects Basic Auth pattern!

## Secret Detection Patterns

AI recognizes secrets in many forms:

### Variable Assignments

```javascript theme={"dark"}
const apiKey = "sk_live_abc123";
const token = "Bearer xyz789";
```

### Environment Variables

```python theme={"dark"}
api_key = os.getenv("STRIPE_KEY")
```

```javascript theme={"dark"}
const key = process.env.API_KEY;
```

```php theme={"dark"}
$key = $_ENV['API_KEY'];
```

### Headers

```bash theme={"dark"}
-H "Authorization: Bearer sk_live_abc123"
-H "X-API-Key: xyz789"
```

### URL Parameters

```text theme={"dark"}
https://api.service.com?api_key=abc123
```

### Basic Auth

```bash theme={"dark"}
-u username:password
```

```python theme={"dark"}
auth=('username', 'password')
```

### Hardcoded Values

```javascript theme={"dark"}
fetch("https://api.example.com", {
  headers: { "Authorization": "Bearer sk_live_abc123" }
});
```

## Customizing After AI Analysis

You can edit any detected field before creating the route:

### Edit Route Name

Click the route name field and type a new name:

```text theme={"dark"}
AI: stripe-charges
You: production-stripe-payment-api
```

### Edit Target URL

Update the URL if needed:

```text theme={"dark"}
AI: https://api.stripe.com/v1/charges
You: https://api.eu.stripe.com/v1/charges
```

### Edit Secret Names

Click secret name to customize:

```text theme={"dark"}
AI: stripe-api-key
You: stripe-production-key-2025
```

### Toggle Secret Creation

Uncheck secrets you don't want to create:

* ☑️ stripe-api-key (create)
* ☐ webhook-secret (skip - I'll add later)

### Edit Headers

Add or remove headers from the detected set:

```json theme={"dark"}
{
  "Content-Type": "application/json",
  "X-Custom-Header": "my-value"
}
```

### Edit Body Structure

Modify the request body before creating:

```json theme={"dark"}
{
  "amount": 1000,
  "currency": "usd",
  "metadata": {
    "order_id": "{{var:order_id}}"
  }
}
```

Add `{{var:param}}` for dynamic values!

## Troubleshooting

### Issue: "Could not detect language"

**Causes:**

* Very short code snippet
* Unusual syntax
* Multiple languages mixed

**Fix:**

1. Include more context (e.g., full function, not just URL)
2. Add comments indicating language:
   ```javascript theme={"dark"}
   // JavaScript
   fetch("https://api.example.com")
   ```
3. Use **Manual Setup** instead

### Issue: "URL not detected"

**Symptoms:** AI couldn't find the API endpoint

**Common causes:**

```javascript theme={"dark"}
// URL is a variable
const url = buildApiUrl(); // AI can't resolve this
fetch(url);
```

**Fix:**

1. Paste code where URL is defined:
   ```javascript theme={"dark"}
   const baseUrl = "https://api.example.com";
   const url = baseUrl + "/endpoint";
   fetch(url);
   ```
2. Or enter URL manually in the form

### Issue: "Secrets detected but values wrong"

**Symptoms:** AI detected a secret but the value is incorrect

**Example:**

```javascript theme={"dark"}
const key = getKeyFromVault(); // AI sees "getKeyFromVault()" as value
```

**Fix:**

1. Edit the secret value after AI analysis
2. Or uncheck and create secret manually later

### Issue: "Too many false positive secrets"

**Symptoms:** AI flagged non-secret values as secrets

**Example:**

```javascript theme={"dark"}
const customerId = "cus_abc123"; // Detected as secret (not actually)
```

**Fix:**

1. Uncheck secrets you don't want to create
2. Only select actual secrets (API keys, tokens)

### Issue: "Request body not formatted"

**Symptoms:** Body appears as one long line

**Fix:**
AI auto-formats JSON. If it's not formatted:

1. Check if body is valid JSON
2. Try pasting just the JSON object:
   ```json theme={"dark"}
   {
     "key": "value"
   }
   ```
3. Or manually format in the body textarea after creation

## Best Practices

### 1. Include Full Context

✅ **Good:**

```javascript theme={"dark"}
const stripeKey = "sk_live_abc123";
fetch("https://api.stripe.com/v1/charges", {
  method: "POST",
  headers: { "Authorization": `Bearer ${stripeKey}` },
  body: JSON.stringify({ amount: 1000 })
});
```

*Complete request with variable definitions*

❌ **Bad:**

```javascript theme={"dark"}
fetch(url, options);
```

*Not enough context*

### 2. Paste Real Values (During Setup)

AI needs to see actual secrets to detect them:

✅ **Use:**

```javascript theme={"dark"}
const key = "sk_live_abc123xyz789";
```

❌ **Don't use:**

```javascript theme={"dark"}
const key = "YOUR_API_KEY_HERE";
```

*Placeholders won't be detected as secrets*

**Remember:** You can delete the value after route creation!

### 3. Clean Up Comments

Remove unnecessary comments that might confuse AI:

✅ **Good:**

```python theme={"dark"}
api_key = "sk_live_abc123"
response = requests.get(url, headers={"Authorization": f"Bearer {api_key}"})
```

❌ **Bad:**

```python theme={"dark"}
# TODO: Replace this with your key
api_key = "sk_live_abc123" # Don't commit this!
# This is just for testing
response = requests.get(url, headers={"Authorization": f"Bearer {api_key}"}) # Fix later
```

### 4. One API Endpoint Per Paste (Usually)

For single route creation:

* Paste code for ONE endpoint
* Remove unrelated code

For multi-route creation:

* Paste multiple endpoints if they're related
* AI will detect and offer batch creation

### 5. Verify AI Suggestions

Always review:

* ✓ URL is correct
* ✓ Secrets are real secrets (not placeholder strings)
* ✓ Headers look right
* ✓ Body structure matches your needs

**Don't blindly accept everything!** AI is smart but not perfect.

### 6. Test After Creation

1. Create route with AI setup
2. Immediately test with Route Tester
3. Verify secrets injected correctly
4. Check backend receives proper requests

See [Testing Routes](/essentials/routes/testing-routes) for details.

## Limitations

### Cannot Detect Dynamic URLs

If URL is built programmatically:

```javascript theme={"dark"}
const url = buildUrl(config.apiEndpoint, params);
```

AI can't resolve this. You'll need to manually enter the URL.

### Cannot Resolve Environment Variables

If secret is in environment:

```python theme={"dark"}
key = os.getenv("API_KEY")
```

AI detects that a secret is needed but doesn't know the actual value. You'll need to manually create the secret.

### Limited SDK Support

If using high-level SDKs:

```javascript theme={"dark"}
const stripe = new Stripe(apiKey);
await stripe.customers.create({ email });
```

AI might not know the exact API endpoint being called. It tries to infer but may need manual correction.

### Arrays in Body Not Always Detected

Complex nested arrays:

```json theme={"dark"}
{
  "items": [
    {"id": 1, "nested": {"deep": {"array": [1, 2, 3]}}}
  ]
}
```

May not parse perfectly. Review and adjust body structure after AI analysis.

### No Support for GraphQL Yet

GraphQL queries aren't currently supported:

```graphql theme={"dark"}
query {
  user(id: 123) {
    name
    email
  }
}
```

Use Manual Setup for GraphQL endpoints.

## Related Features

* **Manual Route Setup**: Traditional step-by-step route creation
* **Visual Body Editor**: Drag-and-drop configuration for complex JSON
* **Route Testing**: Test AI-generated routes before going live
* **Secret Management**: Manage detected secrets after creation

## Next Steps

<CardGroup cols={2}>
  <Card title="Test Your Route" icon="flask" href="/essentials/routes/testing-routes">
    Test AI-generated routes
  </Card>

  <Card title="Manage Secrets" icon="key" href="/getting-started/first-secret">
    Configure detected secrets
  </Card>

  <Card title="Visual Body Editor" icon="wand-magic-sparkles" href="/advanced/visual-body-editor">
    Refine body injection visually
  </Card>

  <Card title="Manual Setup" icon="pen-to-square" href="/getting-started/first-route">
    Create routes manually
  </Card>
</CardGroup>

***

<CardGroup cols={2}>
  <Card title="📊 Statistics" icon="chart-line">
    * **Level**: beginner to intermediate
    * **Time**: 5 minutes
  </Card>

  <Card title="🏷️ Tags" icon="tags">
    `ai`, `automation`, `setup`, `code-parsing`, `migration`
  </Card>
</CardGroup>
