> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pr.snh-ai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Code Examples

> Working code examples in Python, JavaScript, and cURL for integrating with the Public Records API

Complete code examples for integrating with the SNH AI Public Records API in various programming languages.

<Tip>
  For detailed request/response documentation, see the individual endpoint pages under [API Reference](/api-reference/overview).
</Tip>

## Python

### Basic Authentication and Evaluation

```python theme={null}
import requests

API_KEY = "YOUR_API_KEY_HERE"
BASE_URL = "https://cra.pr.snh-ai.com"

def get_token():
    response = requests.post(
        f"{BASE_URL}/auth/token",
        headers={"X-API-Key": API_KEY}
    )
    response.raise_for_status()
    return response.json()["access_token"]

def evaluate_record(token, record_data):
    response = requests.post(
        f"{BASE_URL}/evaluate",
        headers={
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json"
        },
        json={"record": record_data}
    )
    response.raise_for_status()
    return response.json()

token = get_token()
result = evaluate_record(token, {
    "xml": "<ScreeningResults>...</ScreeningResults>",
    "search_id": "test-123",
    "search_date": "2025-04-30",
    "order_id": "12345",
    "order_number": "12345.1",
    "cases": [
        {"court_search_id": "CS40929433A", "offense_id": "34789896"}
    ],
    "applicant_state": "CA",
    "candidate_info": {
        "first_name": "John",
        "middle_name": "A",
        "last_name": "Doe",
        "date_of_birth": "1990-05-15",
        "ssn": "123-45-6789"
    }
})
decision = result["data"]["decision"]
print(f"Search queue: {decision['search_queue']}")
for court in decision["court_decisions"]:
    for case in court["case_decisions"]:
        for offense in case["offenses"]:
            print(offense["offense_id"], offense["charge_decision"], offense["routing"]["queue"])
```

### Token Caching with Auto-Refresh

```python theme={null}
import requests
import time
from typing import Optional

class PublicRecordsAPIClient:
    def __init__(self, api_key: str, base_url: str):
        self.api_key = api_key
        self.base_url = base_url
        self.token: Optional[str] = None
        self.token_expires_at: float = 0

    def get_token(self) -> str:
        if self.token and time.time() < self.token_expires_at:
            return self.token

        response = requests.post(
            f"{self.base_url}/auth/token",
            headers={"X-API-Key": self.api_key}
        )
        response.raise_for_status()
        data = response.json()

        self.token = data["access_token"]
        self.token_expires_at = time.time() + data["expires_in"] - 300
        return self.token

    def evaluate(self, record_data: dict) -> dict:
        token = self.get_token()
        response = requests.post(
            f"{self.base_url}/evaluate",
            headers={
                "Authorization": f"Bearer {token}",
                "Content-Type": "application/json"
            },
            json={"record": record_data}
        )
        response.raise_for_status()
        return response.json()

    def check_health(self) -> dict:
        response = requests.get(f"{self.base_url}/health")
        response.raise_for_status()
        return response.json()

client = PublicRecordsAPIClient(
    api_key="YOUR_API_KEY_HERE",
    base_url="https://cra.pr.snh-ai.com"
)

result = client.evaluate({
    "xml": "<ScreeningResults>...</ScreeningResults>",
    "search_id": "test-123",
    "search_date": "2025-04-30",
    "applicant_state": "CA",
    "candidate_info": {
        "first_name": "John",
        "last_name": "Doe",
        "date_of_birth": "1990-05-15"
    }
})
```

### Identity Match (Compliance Engine)

```python theme={null}
CE_BASE_URL = "https://cra.pr.snh-ai.com"

def identity_match(candidate_to_verify: dict, candidate_in_record: dict) -> dict:
    response = requests.post(
        f"{CE_BASE_URL}/complianceEngine/identity-match",
        headers={"Content-Type": "application/json"},
        json={
            "candidateToVerify": candidate_to_verify,
            "candidateInRecord": candidate_in_record
        }
    )
    response.raise_for_status()
    return response.json()

result = identity_match(
    candidate_to_verify={
        "firstName": "EDGAR",
        "lastName": "LINARES",
        "dateOfBirth": "1997-05-05",
        "ssn": "",
        "aliases": [],
        "addresses": [{
            "streetOne": "200 AVANT ST APT C1 DEL RIO, TX 78840",
            "addressType": "DOMESTIC",
            "country": "US"
        }]
    },
    candidate_in_record={
        "firstName": "EDGAR",
        "lastName": "LINARES",
        "dateOfBirth": "1997-05-05",
        "ssn": "",
        "aliases": [],
        "addresses": [{
            "streetOne": "200 AVANT ST APT C1 DEL RIO, TX 78840",
            "addressType": "DOMESTIC",
            "country": "US"
        }]
    }
)
print(f"Match: {result['isMatch']}, Score: {result['matchScore']}")
```

## JavaScript/Node.js

### Basic Authentication and Evaluation

```javascript theme={null}
const API_KEY = 'YOUR_API_KEY_HERE';
const BASE_URL = 'https://cra.pr.snh-ai.com';

async function getToken() {
  const response = await fetch(`${BASE_URL}/auth/token`, {
    method: 'POST',
    headers: { 'X-API-Key': API_KEY }
  });
  const data = await response.json();
  return data.access_token;
}

async function evaluateRecord(token, recordData) {
  const response = await fetch(`${BASE_URL}/evaluate`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ record: recordData })
  });
  return response.json();
}

const token = await getToken();
const result = await evaluateRecord(token, {
  xml: '<ScreeningResults>...</ScreeningResults>',
  search_id: 'test-123',
  search_date: '2025-04-30',
  order_id: '12345',
  order_number: '12345.1',
  cases: [
    { court_search_id: 'CS40929433A', offense_id: '34789896' }
  ],
  applicant_state: 'CA',
  candidate_info: {
    first_name: 'John',
    middle_name: 'A',
    last_name: 'Doe',
    date_of_birth: '1990-05-15',
    ssn: '123-45-6789'
  }
});
const decision = result.data.decision;
console.log(`Search queue: ${decision.search_queue}`);
for (const court of decision.court_decisions) {
  for (const c of court.case_decisions) {
    for (const offense of c.offenses) {
      console.log(offense.offense_id, offense.charge_decision, offense.routing.queue);
    }
  }
}
```

### Token Caching with Auto-Refresh

```javascript theme={null}
class PublicRecordsAPIClient {
  constructor(apiKey, baseUrl) {
    this.apiKey = apiKey;
    this.baseUrl = baseUrl;
    this.token = null;
    this.tokenExpiresAt = 0;
  }

  async getToken() {
    if (this.token && Date.now() < this.tokenExpiresAt - 300000) {
      return this.token;
    }

    const response = await fetch(`${this.baseUrl}/auth/token`, {
      method: 'POST',
      headers: { 'X-API-Key': this.apiKey }
    });
    const data = await response.json();

    this.token = data.access_token;
    this.tokenExpiresAt = Date.now() + (data.expires_in * 1000);
    return this.token;
  }

  async evaluate(recordData) {
    const token = await this.getToken();
    const response = await fetch(`${this.baseUrl}/evaluate`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ record: recordData })
    });
    return response.json();
  }

}

const client = new PublicRecordsAPIClient(
  'YOUR_API_KEY_HERE',
  'https://cra.pr.snh-ai.com'
);

const result = await client.evaluate({
  xml: '<ScreeningResults>...</ScreeningResults>',
  search_id: 'test-123',
  search_date: '2025-04-30',
  applicant_state: 'CA',
  candidate_info: {
    first_name: 'John',
    last_name: 'Doe',
    date_of_birth: '1990-05-15'
  }
});
console.log(result);
```

## cURL

### Get Token

```bash theme={null}
curl -X POST https://cra.pr.snh-ai.com/auth/token \
  -H "X-API-Key: YOUR_API_KEY_HERE" \
  -H "Content-Type: application/json"
```

### Evaluate Record (Full)

```bash theme={null}
curl -X POST https://cra.pr.snh-ai.com/evaluate \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{
    "record": {
      "xml": "<ScreeningResults><login><account>05022022</account><username>test</username></login><postResults order=\"12345\"><case><case_number>MJ-05003-TR-0006023-2020</case_number><offense_date>20200310</offense_date><jurisdiction_state>PA</jurisdiction_state><chargeinfo><charge>DRIVING WHILE OPERATOR PRIVILEGES SUSPENDED</charge><disposition>GUILTY</disposition></chargeinfo></case></postResults></ScreeningResults>",
      "search_id": "76190bc0-e58c-494f-92c5-0c9a47389528",
      "search_date": "2025-04-30",
      "order_id": "41115779",
      "order_number": "41115779.1",
      "applicant_state": "CA",
      "candidate_info": {
        "first_name": "John",
        "middle_name": "A",
        "last_name": "Doe",
        "date_of_birth": "1990-05-15",
        "ssn": "123-45-6789"
      },
      "cases": [
        { "court_search_id": "CS40929433A", "offense_id": "34789896" }
      ]
    }
  }'
```

### Identity Match

```bash theme={null}
curl -X POST https://cra.pr.snh-ai.com/complianceEngine/identity-match \
  -H "Content-Type: application/json" \
  -d '{
    "candidateToVerify": {
      "firstName": "EDGAR",
      "lastName": "LINARES",
      "dateOfBirth": "1997-05-05",
      "ssn": "",
      "aliases": [],
      "addresses": [{
        "streetOne": "200 AVANT ST APT C1 DEL RIO, TX 78840",
        "addressType": "DOMESTIC",
        "country": "US"
      }]
    },
    "candidateInRecord": {
      "firstName": "EDGAR",
      "lastName": "LINARES",
      "dateOfBirth": "1997-05-05",
      "ssn": "",
      "aliases": [],
      "addresses": [{
        "streetOne": "200 AVANT ST APT C1 DEL RIO, TX 78840",
        "addressType": "DOMESTIC",
        "country": "US"
      }]
    }
  }'
```

### Health Check

```bash theme={null}
curl https://cra.pr.snh-ai.com/health
```

## Error Handling

### Python — Retry with Token Refresh

```python theme={null}
import requests
import time

def evaluate_with_retry(client, record_data, max_retries=3):
    for attempt in range(max_retries):
        try:
            token = client.get_token()
            response = requests.post(
                f"{client.base_url}/evaluate",
                headers={
                    "Authorization": f"Bearer {token}",
                    "Content-Type": "application/json"
                },
                json={"record": record_data}
            )

            if response.status_code == 401:
                client.token = None
                continue

            if response.status_code == 206:
                result = response.json()
                print(f"Partial success: {result['data'].get('errors', [])}")
                return result

            response.raise_for_status()
            return response.json()

        except requests.exceptions.RequestException as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)

    raise Exception("Max retries exceeded")
```
