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

# Requirements & Standards

## Requirements & Standards

To integrate with Spartera, your API must meet specific technical requirements. This page
outlines mandatory and recommended standards for successful integration.

## Mandatory Requirements

### 1. HTTPS Endpoint

Your API **must** be accessible via HTTPS (not HTTP).

```text
✅ https://your-api.example.com/predict
❌ http://your-api.example.com/predict
```

**Why:** All data transmission must be encrypted. Spartera enforces TLS 1.2+ for security compliance.

**How to Implement:**

* Use a valid SSL/TLS certificate (Let's Encrypt is free)
* Cloud platforms (GCP, AWS, Azure) provide HTTPS by default
* Self-hosted: Configure reverse proxy (nginx, Apache) with SSL

### 2. POST Method Support

Your API must accept `POST` requests with JSON body.

```http
POST /predict HTTP/1.1
Host: your-api.example.com
Content-Type: application/json
X-API-Key: your-secret-key

{
  "parameter1": "value1",
  "parameter2": 123
}
```

**Why:** POST supports complex input parameters and is standard for API operations with data payloads.

### 3. JSON Input/Output

**Request Format:** JSON
**Response Format:** JSON

```json
{
  "age": 35,
  "income": 75000,
  "credit_score": 720
}
```

### 4. Authentication

You must provide an authentication method. Supported types:

#### API Key Authentication (Recommended for Simplicity)

```http
X-API-Key: your-secret-api-key-here
```

**Pros:** Simple to implement, works everywhere
**Cons:** Keys should be rotated periodically

#### OAuth 2.0 (Recommended for Enterprise)

```http
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
```

**Pros:** Industry standard, token expiration
**Cons:** More complex implementation

### 5. Spartera Response Format

Your API **must** return this exact structure:

```json
{
  "timestamp": "ISO-8601 datetime string",
  "answer_value": 123.45,
  "asset_id": "string or null"
}
```

**Field Specifications:**

* `timestamp` (String, Required) - ISO-8601 format datetime (UTC)
* `answer_value` (Number, Required) - Your prediction result (float or int)
* `asset_id` (String, Optional) - Asset identifier from request

**Examples:**

```json
{
  "timestamp": "2026-01-30T19:30:00.000000+00:00",
  "answer_value": 1,
  "asset_id": "fraud-check-001"
}
```

## Recommended Requirements

### Performance Standards

* **Response Time:** < 2 seconds (target), < 5 seconds (acceptable)
* **Availability:** 99.9% (target), 99% (acceptable)
* **Error Rate:** < 0.1% (target), < 1% (acceptable)
* **Timeout:** 30 seconds (default), 60 seconds (max)

### Error Handling

Return appropriate HTTP status codes:

* `200` - Success (Prediction completed successfully)
* `400` - Bad Request (Missing parameters, invalid values)
* `401` - Unauthorized (Missing or invalid API key)
* `403` - Forbidden (Valid key but insufficient permissions)
* `429` - Too Many Requests (Rate limit exceeded)
* `500` - Internal Server Error (Model prediction failed)
* `503` - Service Unavailable (Temporary downtime, maintenance)

**Error Response Format:**

```json
{
  "error": "Missing required parameter: age",
  "details": "The 'age' field is required for prediction",
  "error_code": "MISSING_PARAMETER"
}
```

### Input Validation

Validate all inputs before processing:

```python
def validate_input(data):
    required = ['age', 'income', 'credit_score']
    missing = [f for f in required if f not in data]
    if missing:
        return {"error": f"Missing fields: {missing}"}, 400
    
    if not isinstance(data['age'], int):
        return {"error": "Age must be an integer"}, 400
    
    if data['age'] < 18 or data['age'] > 100:
        return {"error": "Age must be between 18 and 100"}, 400
    
    return None, 200
```

### Logging & Monitoring

Implement comprehensive logging:

```python
import logging

logging.info({
    'timestamp': datetime.now(timezone.utc).isoformat(),
    'api_key': api_key[:8] + '...',
    'endpoint': request.path,
    'input_params': list(request.json.keys()),
    'response_time_ms': response_time,
    'status_code': 200
})
```

**What to Log:**

* Request timestamp
* API key (partial, for identification)
* Input parameter names (not values if sensitive)
* Response time
* Status code
* Error messages (if any)

**What NOT to Log:**

* Complete API keys
* Sensitive input data (PII, financial info)
* Complete prediction details (unless required for compliance)

### Health Check Endpoint

Implement a public health check endpoint:

```http
GET /health HTTP/1.1
Host: your-api.example.com
```

**Response:**

```json
{
  "status": "healthy",
  "model": "your-model-name-v1",
  "version": "1.0",
  "timestamp": "2026-01-30T19:30:00Z"
}
```

**Why:** Spartera can monitor your API's availability and alert you to issues.

## Request/Response Patterns

### Pattern 1: Direct Parameter Format

Spartera sends parameters directly in the request body:

```http
POST /predict
X-API-Key: your-key
Content-Type: application/json

{
  "age": 35,
  "income": 75000,
  "credit_score": 710
}
```

### Pattern 2: Function ID Format

Spartera sends parameters wrapped with a function identifier:

```http
POST /
X-API-Key: your-key
Content-Type: application/json

{
  "function_id": "predict",
  "params": {
    "age": 35,
    "income": 75000,
    "credit_score": 720
  }
}
```

**You must support BOTH patterns.**

## Asset ID Handling

Spartera may send an `X-Asset-ID` header with requests:

```http
X-Asset-ID: abc-123-def-456
```

**Your API should:**

1. Extract this header value
2. Include it in the response's `asset_id` field
3. Use it for logging/tracking (optional)

**Implementation:**

```python
asset_id = request.headers.get('X-Asset-ID')

return {
    'timestamp': datetime.now(timezone.utc).isoformat(),
    'answer_value': prediction,
    'asset_id': asset_id
}
```

## Security Best Practices

### API Key Management

**DO:**

* Generate cryptographically random keys (32+ characters)
* Store keys in environment variables, not code
* Rotate keys periodically (quarterly recommended)
* Use different keys for different environments (dev, prod)

**DON'T:**

* Commit keys to version control
* Reuse keys across multiple services
* Share keys via email or chat
* Use predictable keys (no "test123" or "password")

### IP Whitelisting (Optional)

For extra security, whitelist Spartera's IP ranges. Configure in your firewall or load balancer.

## Platform-Specific Considerations

### Google Cloud Run

* HTTPS automatically provided
* Scales to zero (cost-effective)
* Built-in logging
* Cold starts (first request slower)

### AWS Lambda + API Gateway

* Serverless (no infrastructure management)
* Pay per request
* 29-second timeout limit
* Requires API Gateway configuration

### Azure Functions

* Multiple language support
* Auto-scaling
* Cold starts on consumption plan
* Easy integration with Azure ML

### Self-Hosted

* Complete control
* No vendor lock-in
* You manage SSL certificates
* You handle scaling

## Pre-Launch Checklist

Before connecting to Spartera, verify:

* [ ] API accessible via HTTPS
* [ ] POST method works with JSON body
* [ ] Returns exact Spartera response format
* [ ] Authentication implemented and tested
* [ ] Handles both direct and function\_id request patterns
* [ ] Input validation prevents bad requests
* [ ] Error responses include helpful messages
* [ ] Response time < 5 seconds for 95% of requests
* [ ] Logging implemented for debugging
* [ ] Health check endpoint working (recommended)

## Next Steps

* Review [Response Schema Specification](./response-schema-specifications.md) for detailed format requirements
* Learn about [Function ID Routing](./function_id-routing.md) to support multiple models
* See [Connecting Your API](./connecting-api.md) to register your endpoint