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

# Connecting Your API

## Connecting Your API

## Overview

This guide walks you through connecting your ML model API to Spartera.
The entire process takes 10-15 minutes.

## Prerequisites

Before you begin, ensure you have:

* A trained ML model deployed as an API
* HTTPS endpoint URL
* API authentication credentials
* Your API returns [Spartera response format](./response-schema-specifications.md)
* Spartera account (sign up at spartera.com)

## Step-by-Step Connection Guide

### Step 1: Access Connection Manager

1. Log in to your Spartera account
2. Navigate to **Analytics Platform** → **Connections**
3. Click **"Add New Connection"**

### Step 2: Select Connection Type

Choose **"API (External API)"** as your connection type.

**Why External API?**

* Your model stays on your infrastructure
* No data migration required
* Full control over scaling and security

### Step 3: Configure Basic Settings

Fill in the connection details:

#### Connection Name

```text
Example: "Fraud Detection Model API"
Example: "Customer Churn Predictor"
Example: "Price Optimization Engine"
```

**Best Practices:**

* Use descriptive names
* Include model purpose
* Avoid technical jargon (this name is visible to you only)

#### Description (Optional)

```text
Example: "Production fraud detection model trained on 5M transactions.
Achieves 94% accuracy with &lt;100ms latency."
```

### Step 4: Configure API Settings

#### API Endpoint URL

Enter your complete HTTPS endpoint URL:

```text
✅ Correct Examples:
https://fraud-detection-api.example.com/predict
https://my-model-api-12345.us-central1.run.app/predict
https://api.mycompany.com/v1/models/churn/predict

❌ Incorrect:
http://my-api.com/predict  (Not HTTPS)
my-api.com/predict  (Missing protocol)
https://localhost:8080/predict  (Not publicly accessible)
```

**Important:** Use the `/predict` endpoint if you're using direct routing
(Function ID blank). See [Function ID Routing](function-id-routing) for
advanced configurations.

#### HTTP Method

Select: **POST - Parameters in JSON body**

This is the required method for all Spartera integrations.

### Step 5: Configure Authentication

#### Credential Type

Select: **API Key**

This is the most common and recommended authentication method.

**Other Options:**

* OAuth 2.0 (for enterprise integrations)
* Custom Header (for specialized auth)
* Mutual TLS (for maximum security)

#### API Key Location

Select: **In Headers (Recommended)**

**Alternative:** In Query Parameters (not recommended for security)

#### API Key Parameter Name

Enter the header name your API expects:

```text
Common options:
X-API-Key  (recommended)
X-Api-Key
Authorization
Api-Key
```

**Match Your Implementation:**

If your API code looks like this:

```python
api_key = request.headers.get('X-API-Key')
```

Then enter: `X-API-Key`

#### API Key Value

Enter your actual API key:

```text
Example: sk_live_spartera_Z4TWsEILnBQCarKl3mpwoqxijSktJH0c
```

**Security Note:**

* This key is encrypted and stored securely
* Spartera uses it to authenticate requests to your API
* Never share this key publicly
* Rotate it periodically for security

### Step 6: Test Connection

Click **"Test Connection"** button.

Spartera will:

1. Send a test request to your API
2. Verify HTTPS connectivity
3. Check authentication
4. Validate response format

#### Successful Test

```text
✅ Connection Successful
Status: 200 OK
Response Time: 145ms
Response Format: Valid
```

#### Troubleshooting Failed Tests

#### Error: Connection Timeout

```text
❌ Error: Request timeout after 30 seconds
```

**Solution:**

* Check your API is publicly accessible
* Verify URL is correct
* Ensure no firewall blocking Spartera IPs

#### Error: SSL Certificate Invalid

```text
❌ Error: SSL certificate verification failed
```

**Solution:**

* Ensure using valid SSL certificate
* Check certificate isn't expired
* Use Let's Encrypt for free certificates

#### Error: 401 Unauthorized

```text
❌ Error: 401 Unauthorized
```

**Solution:**

* Verify API key is correct
* Check API key header name matches your code
* Ensure API key has necessary permissions

#### Error: Invalid Response Format

```text
❌ Error: Response missing required field 'timestamp'
```

**Solution:**

* Review [Response Schema Specification](response-schema-specification)
* Ensure all required fields present
* Check field types (number vs string)

### Step 7: Save Connection

Once the test succeeds, click **"Save Connection"**.

Your API is now connected to Spartera! 🎉

## Advanced Configuration

### Setting Timeout

Default: 30 seconds

**When to Adjust:**

* Your model needs >30s to generate predictions
* You want faster failure detection (<30s)

```text
Recommended Timeouts:
- Fast models (&lt;1s): 5 seconds
- Standard models: 30 seconds
- Complex models: 60 seconds
- Batch processing: 120 seconds
```

### IP Whitelisting

For additional security, whitelist Spartera's IP ranges in your firewall:

**Spartera IP Ranges:**

```text
(Contact Spartera support for current IP ranges)
```

**How to Whitelist:**

**Google Cloud:**

```bash
gcloud compute firewall-rules create allow-spartera \
  --allow tcp:443 \
  --source-ranges IP_RANGE_HERE
```

**AWS Security Group:**

```bash
aws ec2 authorize-security-group-ingress \
  --group-id sg-xxxxx \
  --protocol tcp \
  --port 443 \
  --cidr IP_RANGE_HERE
```

**nginx:**

```nginx
location /predict {
    allow IP_RANGE_HERE;
    deny all;
}
```

### Rate Limiting

Configure rate limits to prevent abuse:

**In Spartera (Recommended):**

* Set in Connection settings
* Applied before reaching your API
* Protects your infrastructure

**In Your API:**

```python
from flask_limiter import Limiter

limiter = Limiter(
    app,
    key_func=lambda: request.headers.get('X-API-Key')
)

@app.route('/predict')
@limiter.limit("100/minute")
def predict():
    # Your code
```

### Custom Headers

Add custom headers to all requests:

```text
Example Use Cases:
X-Spartera-Version: 1.0
X-Environment: production
X-Request-Source: marketplace
```

**Configuration:**

```text
Key: X-Custom-Header
Value: custom-value
```

## Multiple Endpoint Configuration

If you have multiple models, you can:

**Option 1: Separate Connections** (Simpler)

* Create one connection per model
* Each with unique endpoint URL
* Each with separate API key

**Option 2: Function ID Routing** (Advanced)

* One connection with base URL
* Different Function IDs for different models
* See [Function ID Routing](function-id-routing)

## Connection Management

### Viewing Connections

**Analytics Platform** → **Connections**

Shows all your active connections:

* Connection name
* Status (Active/Inactive/Error)
* Last tested
* Number of assets using connection

### Editing Connections

Click **Edit** next to any connection to:

* Update endpoint URL
* Change authentication credentials
* Modify timeout settings
* Update description

**Note:** Changes affect all assets using this connection.

### Testing Existing Connections

Click **Test** to verify connection still works:

* Useful after deploying model updates
* Checks if API still accessible
* Validates authentication still valid

### Deactivating Connections

Click **Deactivate** to temporarily disable:

* Assets using this connection become unavailable
* Useful for maintenance
* No data is deleted
* Can reactivate anytime

### Deleting Connections

Click **Delete** to permanently remove:

* ⚠️ **Warning:** Cannot be undone
* Assets using this connection will fail
* Only delete if migrating to new endpoint

## Monitoring & Health

### Connection Health Dashboard

View real-time connection health:

```text
Status: Healthy ✅
Uptime (7 days): 99.8%
Avg Response Time: 145ms
Success Rate: 99.9%
Last Check: 2 minutes ago
```

### Alerts

Configure alerts for:

* Connection failures
* High latency (>5s)
* Error rate spikes (>5%)
* SSL certificate expiration

**Setup:**

1. Navigate to connection settings
2. Click "Configure Alerts"
3. Add email/Slack webhook
4. Set thresholds

### Activity Logs

View detailed request logs:

* Request timestamp
* Response time
* Status code
* Error messages (if any)
* API key used (partial)

**Retention:** 30 days

## Security Best Practices

### API Key Rotation

Rotate API keys quarterly:

1. Generate new API key in your system
2. Update connection in Spartera
3. Test connection with new key
4. Invalidate old API key
5. Monitor for any failures

### Audit Trail

Review connection activity:

* Who created connection
* When last modified
* Configuration changes
* Test results

### Access Control

Control who can manage connections:

* **Admin:** Full access
* **Developer:** Can test and view
* **Viewer:** Read-only access

## Troubleshooting

### Connection Works in Test but Fails in Production

**Possible Causes:**

* Rate limiting triggered
* Different IP ranges
* SSL certificate issues
* Load balancer configuration

**Solution:**

* Check your API logs
* Review firewall rules
* Verify SSL certificate valid
* Test with actual prediction request

### Intermittent Failures

**Possible Causes:**

* Cold starts (serverless)
* Timeout too short
* Model loading delays
* Network instability

**Solution:**

* Increase timeout setting
* Keep models warm
* Add retries in your code
* Monitor response times

### High Latency

**Possible Causes:**

* Model inference slow
* Database queries
* Network distance
* Insufficient resources

**Solution:**

* Optimize model
* Cache frequent queries
* Use regional deployment
* Scale up infrastructure

## Next Steps

Now that your API is connected:

1. [Create Assets](creating-assets-from-apis) - Define input parameters
   and pricing
2. [Test Your Integration](testing-and-validation) - Validate end-to-end
   flow
3. [Publish to Marketplace](publishing-to-marketplace) - Make your model
   available to buyers
4. [Monitor Performance](best-practices#monitoring) - Track usage and
   earnings

## FAQs

**Q: Can I connect multiple models with one connection?**

A: Yes, using [Function ID Routing](function-id-routing). One connection,
multiple models accessible via different function IDs.

**Q: What happens if my API goes down?**

A: Buyers receive error messages. Your connection status shows "Unhealthy."
You receive alerts (if configured). No charges to buyers for failed requests.

**Q: Can I update my API without downtime?**

A: Yes, deploy new version alongside old, update connection URL when ready,
test thoroughly before switching.

**Q: How often does Spartera check my API health?**

A: Every 5 minutes for active connections. You can manually test anytime.

**Q: Can I see what requests Spartera sends to my API?**

A: Yes, in your API's logs. Also viewable in Spartera's activity logs
(sanitized for security).

**Q: Do I need a static IP address?**

A: No, as long as your API is accessible via domain name (HTTPS). Dynamic
IPs work fine.

**Q: Can I use the same API key for multiple connections?**

A: Technically yes, but not recommended. Use unique keys per connection for
better security and tracking.

**Need Help?**

* Email: <developers@spartera.com>
* Community Forum: community.spartera.com
* Documentation: docs.spartera.com