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

# Authentication and configuration

> API key setup, authentication headers, and HTTP client configuration for the SofIA Codify API

## Authorization token

All API calls require a **Bearer token** in the `Authorization` header.

### Format

```http theme={null}
Authorization: Bearer YOUR_TOKEN_HERE
```

### How to get your token?

After service contracting, you will receive:

<Columns cols={3}>
  <Card title="Production token" />

  <Card title="Development token">
    For testing
  </Card>

  <Card title="Corresponding endpoints" />
</Columns>

### Token security

<Warning>
  **Never** expose your token in client-side code (browser JavaScript). Store it as an environment variable or secret, rotate it periodically, and use different tokens for development and production.
</Warning>

***

## Optional headers (recommended)

### Doctor and patient identifiers

For traceability and regulatory compliance:

```http theme={null}
x-doctor: dr_123
x-patient: pt_456
```

**Usage:**

* Access auditing
* Debugging and technical support
* GDPR/HIPAA compliance
* Usage analytics

**Note:** These identifiers are logged for auditing purposes but **do not affect** request processing.

### Note

These identifiers should be sent as HTTP headers, not in the request body. The Codify API uses headers for tracking metadata to keep the request body focused on the medical content.

***

## Available environments

### Development

**URL:** Provided upon direct request

**Features:**

<Columns cols={2}>
  <Card title="More relaxed rate limits" icon="check" />

  <Card title="Do not use for real patient data" icon="xmark" />

  <Card title="More verbose logs for debugging" icon="check" />

  <Card title="No SLA guarantees" icon="xmark" />

  <Card title="No per-request costs" icon="check" />
</Columns>

**Recommended usage:**

<Columns cols={4}>
  <Card title="Development and initial integration" />

  <Card title="JSON schema testing" />

  <Card title="Workflow validation" />

  <Card title="Automated testing" />
</Columns>

### Production

**URL:** Provided after deployment (customized per client)

**Features:**

<Columns cols={2}>
  <Card title="High availability (99.9% SLA)" icon="check" />

  <Card title="Guaranteed processing" icon="check" />

  <Card title="24/7 support" icon="check" />

  <Card title="Metrics and monitoring" icon="check" />
</Columns>

**Recommended usage:**

<Columns cols={3}>
  <Card title="HIS/EHR system integration" />

  <Card title="Real data processing" />

  <Card title="Production workflows" />
</Columns>

***

## HTTP client configuration

### Timeouts and retries

For timeout configuration and retry strategies with exponential backoff, see [Retry strategy](/sofia/en/api/operations#retry-strategy).

**Basic recommendations:**

* Timeout: 600 seconds (10 minutes) for Codify API
* Retries: 3 attempts for 5xx and 429 errors
* Exponential backoff: 1s, 2s, 4s...

***

## Additional headers

### Content-Type

Should always be `application/json`:

```http theme={null}
Content-Type: application/json
```

### User-Agent (optional)

Recommended to identify your application:

```http theme={null}
User-Agent: MyHIS/1.0 (XYZ Hospital)
```

***

## Complete configuration example

### Python

```python theme={null}
import os
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

# Configuration
API_URL = os.getenv('OMNISCRIBE_API_URL')  # Provided after contracting
API_TOKEN = os.getenv('OMNISCRIBE_API_TOKEN')

# Client with retries
session = requests.Session()
retry = Retry(
    total=3,
    backoff_factor=1,
    status_forcelist=[429, 500, 502, 503, 504]
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)

# Default headers
session.headers.update({
    'Authorization': f'Bearer {API_TOKEN}',
    'Content-Type': 'application/json',
    'User-Agent': 'MyHIS/1.0'
})

# Usage
def codify(medical_note, doctor_id=None, patient_id=None, model=None):
    payload = {
        'medical_note': medical_note
    }
    
    if model:
        payload['model'] = model
    
    headers = {}
    if doctor_id:
        headers['x-doctor'] = doctor_id
    if patient_id:
        headers['x-patient'] = patient_id
    
    response = session.post(
        f'{API_URL}/v1/codify',
        json=payload,
        headers=headers,
        timeout=600  # 10-minute timeout for Codify
    )
    response.raise_for_status()
    return response.json()

# Example usage
result = codify(
    medical_note="Patient with Type 2 Diabetes...",
    doctor_id="dr_123",
    patient_id="pt_456",
    model="balanced"
)

print(f"Codes found: {len(result['final_code_assessments'])}")
for assessment in result['final_code_assessments']:
    print(f"  {assessment['code']}: {assessment['description']}")
```

### JavaScript (Node.js)

```javascript theme={null}
const axios = require('axios');
const axiosRetry = require('axios-retry');

// Configuration
const API_URL = process.env.OMNISCRIBE_API_URL;  // Provided after contracting
const API_TOKEN = process.env.OMNISCRIBE_API_TOKEN;

// Client with retries
const client = axios.create({
  baseURL: API_URL,
  timeout: 600000,  // 10-minute timeout for Codify
  headers: {
    'Authorization': `Bearer ${API_TOKEN}`,
    'Content-Type': 'application/json',
    'User-Agent': 'MyHIS/1.0'
  }
});

axiosRetry(client, {
  retries: 3,
  retryDelay: axiosRetry.exponentialDelay,
  retryCondition: (error) => {
    return axiosRetry.isNetworkOrIdempotentRequestError(error) ||
           error.response?.status === 429 ||
           error.response?.status >= 500;
  }
});

// Usage
async function codify(medicalNote, doctorId, patientId, model) {
  const headers = {};
  if (doctorId) headers['x-doctor'] = doctorId;
  if (patientId) headers['x-patient'] = patientId;

  const payload = {
    medical_note: medicalNote
  };
  
  if (model) payload.model = model;

  const response = await client.post('/v1/codify', payload, { headers });

  return response.data;
}

// Example usage
const result = await codify(
  "Patient with Type 2 Diabetes...",
  "dr_123",
  "pt_456",
  "balanced"
);

console.log(`Codes found: ${result.final_code_assessments.length}`);
result.final_code_assessments.forEach(assessment => {
  console.log(`  ${assessment.code}: ${assessment.description}`);
});

module.exports = { codify };
```

***

## Security and best practices

<Columns cols={2}>
  <Card title="Use environment variables for tokens" icon="check" />

  <Card title="Hardcode tokens in source code" icon="xmark" />

  <Card title="Implement appropriate timeouts" icon="check" />

  <Card title="Expose tokens in client (browser)" icon="xmark" />

  <Card title="Configure automatic retries" icon="check" />

  <Card title="Share tokens between environments" icon="xmark" />

  <Card title="Always use HTTPS" icon="check" />

  <Card title="Disable SSL certificate validation" icon="xmark" />

  <Card title="Include doctor/patient identifiers for auditing" icon="check" />

  <Card title="Ignore authentication errors" icon="xmark" />
</Columns>

***

## Next steps

<Columns cols={3}>
  <Card title="Request/response structure" icon="clipboard" href="/sofia/en/api/request-response" />

  <Card title="View examples" icon="lightbulb" href="/sofia/en/api/examples" />

  <Card title="Error handling" icon="gear" href="/sofia/en/api/operations" />
</Columns>
