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

# Best Practices

> Rate limits, retry with exponential backoff, the error envelope and its status codes, credential handling, and the tests to write before you go live.

## Building Production-Ready Integrations

You've got the basics down. Now let's make your integration bulletproof with proper error handling, performance optimization, and security best practices that will scale with your practice.

## Environment Configuration

### API Endpoints

| Environment | Base URL | Credentials |
| - | - | - |
| Staging | `https://api-staging.openloophealth.com/v0.1` | Build here first |
| Production | `https://api.openloophealth.com/v0.1` | Separate credential, issued at go-live |

### Authentication

Every request carries an OAuth 2.0 access token obtained through the client-credentials flow. Exchange your `client_id` / `client_secret` for a short-lived token, then send it as a Bearer token. Cache the token and refresh it before `expires_in` elapses rather than requesting one per call.

This is the service token used for machine-to-machine calls. For the sequence that registers and authenticates an individual user, see the [User Registration](https://openloop.mintlify.site/api-reference/user-registration-guide.md) guide.

```javascript JavaScript theme={null}
// 1. Exchange credentials for a short-lived access token
const { data } = await fetch('https://api.openloophealth.com/v0.1/auth/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    grant_type: 'client_credentials',
    client_id: process.env.OPENLOOP_CLIENT_ID,
    client_secret: process.env.OPENLOOP_CLIENT_SECRET,
    audience: 'https://api.openloophealth.com',
  }),
}).then(r => r.json());

// 2. Send it as a Bearer token on every request
const patients = await fetch('https://api.openloophealth.com/v0.1/patients', {
  headers: { Authorization: `Bearer ${data.access_token}` },
}).then(r => r.json());
```

```python Python theme={null}
import os, requests

# 1. Exchange credentials for a short-lived access token
token = requests.post(
    'https://api.openloophealth.com/v0.1/auth/token',
    json={
        'grant_type': 'client_credentials',
        'client_id': os.environ['OPENLOOP_CLIENT_ID'],
        'client_secret': os.environ['OPENLOOP_CLIENT_SECRET'],
        'audience': 'https://api.openloophealth.com',
    },
).json()['data']['access_token']

# 2. Send it as a Bearer token on every request
patients = requests.get(
    'https://api.openloophealth.com/v0.1/patients',
    headers={'Authorization': f'Bearer {token}'},
).json()
```

```bash cURL theme={null}
# 1. Exchange credentials for a short-lived access token
curl --request POST \
  --url https://api.openloophealth.com/v0.1/auth/token \
  --header 'content-type: application/json' \
  --data '{
    "grant_type": "client_credentials",
    "client_id": "YOUR_CLIENT_ID",
    "client_secret": "YOUR_CLIENT_SECRET",
    "audience": "https://api.openloophealth.com"
  }'

# 2. Send the returned access_token as a Bearer token
curl -H "Authorization: Bearer <access_token>" \
     https://api.openloophealth.com/v0.1/patients
```

## Rate Limits & Performance

> [!NOTE]
>
> These limits are not independently verified against staging.

### Current Limits

* **Rate Limit**: 1,000 requests per hour per client
* **Burst Limit**: 100 requests per minute
* **Concurrent Requests**: 10 simultaneous requests

### Implementing Rate Limiting

```javascript JavaScript theme={null}
class RateLimiter {
  constructor(requestsPerMinute = 100) {
    this.requests = [];
    this.limit = requestsPerMinute;
  }

  async waitIfNeeded() {
    const now = Date.now();
    const oneMinuteAgo = now - 60000;
    
    // Remove requests older than 1 minute
    this.requests = this.requests.filter(time => time > oneMinuteAgo);
    
    if (this.requests.length >= this.limit) {
      const oldestRequest = Math.min(...this.requests);
      const waitTime = 60000 - (now - oldestRequest);
      await new Promise(resolve => setTimeout(resolve, waitTime));
    }
    
    this.requests.push(now);
  }

  async makeRequest(url, options = {}) {
    await this.waitIfNeeded();
    
    const response = await fetch(url, {
      ...options,
      headers: {
        'Authorization': 'Bearer <access_token>',
        'Content-Type': 'application/json',
        ...options.headers
      }
    });
    
    return response;
  }
}

// Usage example
const limiter = new RateLimiter(100);
const response = await limiter.makeRequest('https://api.openloophealth.com/v0.1/patients');
```

```python Python theme={null}
import time
import asyncio
from typing import List
import aiohttp

class RateLimiter:
    def __init__(self, requests_per_minute: int = 100):
        self.requests: List[float] = []
        self.limit = requests_per_minute

    async def wait_if_needed(self):
        now = time.time()
        one_minute_ago = now - 60
        
        # Remove requests older than 1 minute
        self.requests = [req_time for req_time in self.requests if req_time > one_minute_ago]
        
        if len(self.requests) >= self.limit:
            oldest_request = min(self.requests)
            wait_time = 60 - (now - oldest_request)
            await asyncio.sleep(wait_time)
        
        self.requests.append(now)

    async def make_request(self, url: str, **kwargs):
        await self.wait_if_needed()
        
        headers = {
            'Authorization': 'Bearer <access_token>',
            'Content-Type': 'application/json',
            **kwargs.get('headers', {})
        }
        
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=headers) as response:
                return await response.json()

# Usage example
limiter = RateLimiter(100)
data = await limiter.make_request('https://api.openloophealth.com/v0.1/patients')
```

## Error Handling

### HTTP Status Codes

The API uses standard HTTP status codes with detailed error responses:

> [card] 2xx Success
>
> * `200` - OK (GET, PUT)
> * `201` - Created (POST)
> * `204` - No Content (DELETE)

> [card] 4xx Client Errors
>
> * `400` - Bad Request
> * `401` - Unauthorized
> * `404` - Not Found
> * `422` - Validation Error

### Error Response Format

All error responses follow a consistent format. The `details` array is only present for validation errors:

```json Validation Error theme={null}
{
  "error": "ValidationError",
  "message": "Invalid input data",
  "details": [
    {
      "field": "email",
      "issue": "Invalid email format"
    }
  ]
}
```

```json Unauthorized Error theme={null}
{
  "error": "Unauthorized",
  "message": "Authentication token missing or invalid"
}
```

```json Not Found Error theme={null}
{
  "error": "NotFound",
  "message": "Resource not found"
}
```

```json Bad Request Error theme={null}
{
  "error": "BadRequest",
  "message": "Invalid request data"
}
```

**Error Types:**

* `BadRequest` - Invalid request data
* `Unauthorized` - Missing or invalid authentication
* `Forbidden` - Access denied
* `NotFound` - Resource does not exist
* `ValidationError` - Input validation failed (includes `details` array)
* `InternalServerError` - Server error
* `ServiceUnavailable` - Service temporarily unavailable

### Implementing Robust Error Handling

```javascript JavaScript theme={null}
async function handleApiCall(apiFunction) {
  try {
    const response = await apiFunction();
    return { success: true, data: response };
  } catch (error) {
    if (error.response) {
      // API returned an error response
      const { status, data } = error.response;
      
      switch (status) {
        case 401:
          // Handle authentication errors
          throw new Error('Invalid API credentials');
        case 422:
          // Handle validation errors
          return { 
            success: false, 
            errors: data.details,
            message: data.message 
          };
        case 429:
          // Handle rate limiting
          throw new Error('Rate limit exceeded. Please retry later.');
        default:
          throw new Error(`API Error: ${data.message || 'Unknown error'}`);
      }
    } else {
      // Network or other error
      throw new Error('Network error. Please check your connection.');
    }
  }
}
```

```python Python theme={null}
import requests
from typing import Dict, Any, Optional

def handle_api_call(api_function):
    try:
        response = api_function()
        return {"success": True, "data": response}
    except requests.exceptions.HTTPError as error:
        # API returned an error response
        status = error.response.status_code
        data = error.response.json()
        
        if status == 401:
            # Handle authentication errors
            raise Exception("Invalid API credentials")
        elif status == 422:
            # Handle validation errors
            return {
                "success": False,
                "errors": data.get("details", []),
                "message": data.get("message", "")
            }
        elif status == 429:
            # Handle rate limiting
            raise Exception("Rate limit exceeded. Please retry later.")
        else:
            raise Exception(f"API Error: {data.get('message', 'Unknown error')}")
    except requests.exceptions.RequestException:
        # Network or other error
        raise Exception("Network error. Please check your connection.")
```

## Integration Patterns

### Retry Logic with Exponential Backoff

> [!NOTE]
>
> Webhook delivery is configured per customer and is not self-serve yet. Until it is enabled for you, apply this pattern to your synchronous status reads.

These samples show retrying **your own** outbound calls. OpenLoop's own webhook delivery policy — attempts, backoff and timeout — is documented on [Events](https://openloop.mintlify.site/events.md) and does not match the values below.

```javascript JavaScript theme={null}
// Generic retry function
async function retryApiCall(apiFunction, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await apiFunction();
    } catch (error) {
      if (attempt === maxRetries) throw error;
      
      // Don't retry on client errors (4xx)
      if (error.response?.status >= 400 && error.response?.status < 500) {
        throw error;
      }
      
      // Exponential backoff: 1s, 2s, 4s
      const delay = Math.pow(2, attempt - 1) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}

// Webhook retry implementation
class WebhookRetryHandler {
  constructor(maxRetries = 5, baseDelay = 1000) {
    this.maxRetries = maxRetries;
    this.baseDelay = baseDelay;
  }

  async sendWebhook(url, payload, headers = {}) {
    const sendWebhook = async () => {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...headers
        },
        body: JSON.stringify(payload)
      });

      if (!response.ok) {
        throw new Error(`Webhook failed: ${response.status} ${response.statusText}`);
      }

      return response;
    };

    return await retryApiCall(sendWebhook, this.maxRetries);
  }

  async processWebhookEvent(event) {
    try {
      // Process the webhook event
      console.log('Processing webhook event:', event.type);
      
      // Your webhook processing logic here
      await this.handleEvent(event);
      
      return { success: true, eventId: event.id };
    } catch (error) {
      console.error('Webhook processing failed:', error);
      throw error;
    }
  }

  async handleEvent(event) {
    // Implement your webhook event handling logic
    switch (event.type) {
      case 'invoice.paid':
        // Handle a settled invoice
        break;
      case 'intake.completed':
        // Handle a completed intake
        break;
      default:
        console.log('Unhandled event type:', event.type);
    }
  }
}

// Usage example
const webhookHandler = new WebhookRetryHandler();
await webhookHandler.processWebhookEvent({
  id: 'dd8b2b068d57c2a1dfc6f33e9e4b3b3eabe64fe1f12b5ee9e44bb881e18ec1ad',
  type: 'invoice.paid',
  data: { provider_invoice_id: 'in_000000000000' }
});
```

```python Python theme={null}
import asyncio
import time
import json
from typing import Callable, Any, Dict
import aiohttp

# Generic retry function
async def retry_api_call(api_function: Callable, max_retries: int = 3) -> Any:
    for attempt in range(1, max_retries + 1):
        try:
            return await api_function()
        except Exception as error:
            if attempt == max_retries:
                raise error
            
            # Don't retry on client errors (4xx)
            if hasattr(error, 'response') and error.response.status_code >= 400 and error.response.status_code < 500:
                raise error
            
            # Exponential backoff: 1s, 2s, 4s
            delay = 2 ** (attempt - 1)
            await asyncio.sleep(delay)

# Webhook retry implementation
class WebhookRetryHandler:
    def __init__(self, max_retries: int = 5, base_delay: int = 1000):
        self.max_retries = max_retries
        self.base_delay = base_delay

    async def send_webhook(self, url: str, payload: Dict, headers: Dict = None) -> aiohttp.ClientResponse:
        if headers is None:
            headers = {}
        
        async def _send():
            async with aiohttp.ClientSession() as session:
                async with session.post(
                    url,
                    json=payload,
                    headers={'Content-Type': 'application/json', **headers}
                ) as response:
                    if not response.ok:
                        raise Exception(f"Webhook failed: {response.status} {response.reason}")
                    return response

        return await retry_api_call(_send, self.max_retries)

    async def process_webhook_event(self, event: Dict) -> Dict:
        try:
            # Process the webhook event
            print(f"Processing webhook event: {event['type']}")
            
            # Your webhook processing logic here
            await self.handle_event(event)
            
            return {"success": True, "eventId": event["id"]}
        except Exception as error:
            print(f"Webhook processing failed: {error}")
            raise error

    async def handle_event(self, event: Dict) -> None:
        # Implement your webhook event handling logic
        event_type = event.get("type")
        if event_type == "invoice.paid":
            # Handle a settled invoice
            pass
        elif event_type == "intake.completed":
            # Handle a completed intake
            pass
        else:
            print(f"Unhandled event type: {event_type}")

# Usage example
webhook_handler = WebhookRetryHandler()
await webhook_handler.process_webhook_event({
    "id": "dd8b2b068d57c2a1dfc6f33e9e4b3b3eabe64fe1f12b5ee9e44bb881e18ec1ad",
    "type": "invoice.paid",
    "data": {"provider_invoice_id": "in_000000000000"}
})
```

## Security Best Practices

> [card] Credentials & Tokens
>
> * Store `client_id` / `client_secret` securely (environment variables)
> * Rotate credentials regularly
> * Never commit credentials to version control
> * Treat access tokens as short-lived; refresh before expiry

> [card] Data Privacy
>
> * Encrypt sensitive data in transit
> * Follow HIPAA guidelines for patient data
> * Implement proper access controls

## Testing Your Integration

### Unit Testing

```javascript JavaScript theme={null}
// Example test using Jest
describe('Patient API', () => {
  test('should create patient successfully', async () => {
    const patientData = {
      email: 'test@example.com',
      first_name: 'John',
      last_name: 'Doe',
      // ... other required fields
    };
    
    const result = await createPatient(patientData);
    expect(result.success).toBe(true);
    expect(result.data.id).toBeDefined();
  });
});
```

```python Python theme={null}
# Example test using pytest
import pytest
from unittest.mock import patch, Mock

def test_create_patient_successfully():
    patient_data = {
        'email': 'test@example.com',
        'first_name': 'John',
        'last_name': 'Doe',
        # ... other required fields
    }
    
    with patch('your_module.create_patient') as mock_create:
        mock_create.return_value = {
            'success': True,
            'data': {'id': '12345'}
        }
        
        result = create_patient(patient_data)
        assert result['success'] is True
        assert result['data']['id'] is not None
```

## Support & Resources

> [card] [OpenLoop Health](https://openloophealth.com)
>
> Learn more about our platform and services

> [card] [Contact Support](https://openloophealth.com/contact)
>
> Get help from our technical team

> [card] [OpenAPI Spec](https://openloop.mintlify.site/openapi.json)
>
> Download the complete API specification


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.