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

# Python Cookbook

> Try out our the API with Python

Below is a quickstart guide in **Python** demonstrating how to call three primary endpoints using the [`requests`](https://pypi.org/project/requests/) library:

1. **Aggregated Crash Data**
2. **Commercial Auto Garaging**
3. **Commercial Auto Telematics** (file upload + job polling)

You can install the `requests` library using `pip`:

```
pip install requests
```

> **Note**
>
> * Replace `YOUR_API_KEY` with your actual API key or token.
> * If any endpoint is restricted in your plan or environment, you may receive `403` errors.
> * Make sure you have installed `requests` (e.g. `pip install requests`).
> * The examples below show minimal usage. Adjust request payloads as needed.

***

# Get an API Key

Create an API key in the dashboard [here](https://risk.matrisk.ai), which you’ll use to securely access the API. Store the key in a safe location, like a .zshrc file or another text file on your computer. Once you’ve generated an API key, export it as an environment variable in your terminal. For the sake of this example, we'll use `MATRISK_API_KEY`.

***

# Make your first API request

## 1. Aggregated Crash Data

[View documentation](/api-reference/aggregated-crashes/get-aggregated-crash-data)

**Endpoint**

```

POST /crash-data/aggregate

```

This endpoint allows you to get aggregated crash statistics for a particular location and date range.

```python theme={null}
import requests

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.risk.matrisk.ai/v1"

def get_aggregated_crash_data():
    url = f"{BASE_URL}/crash-data/aggregate"
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "location": {
            "latitude": 37.7749,
            "longitude": -122.4194
        },
        "start_date": "2020-01-01T00:00:00",
        "end_date": "2021-12-31T00:00:00",
        "radius_km": 50
    }

    r = requests.post(url, json=payload, headers=headers)
    r.raise_for_status()
    data = r.json()
    print(data)


get_aggregated_crash_data()
```

**Example Response**

```json theme={null}
{
  "latitude": 37.7749,
  "longitude": -122.4194,
  "start_date": "2020-01-01T00:00:00",
  "end_date": "2021-12-31T00:00:00",
  "radius_km": 50.0,
  "total_crashes": 123,
  "total_injuries": 7,
  "total_fatalities": 1,
  "incomplete_coverage": false
}
```

***

## 2. Commercial Auto Garaging

[View documentation](/api-reference/ca-garaging-risk-score/calculate-risk-score)

**Endpoint**

```
POST /risk-score/ca-garaging
```

This endpoint calculates a **risk score** for vehicles based on their primary garaging locations in a commercial auto context.

> **Note:** Although this example is for commercial auto, the PPA garaging is the same structure (without the `naics_code` field).

```python theme={null}
import requests

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.risk.matrisk.ai/v1"

def get_commercial_auto_risk_score():
    url = f"{BASE_URL}/risk-score/ca-garaging"
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "version": "v2",
        "policy_holder_id": "policy-holder-123",
        "vehicles": [
            {
                "vehicle_id": "vehicle-123",
                "garaging_location": {
                    "latitude": 37.7749,
                    "longitude": -122.4194
                }
            },
            {
                "vehicle_id": "vehicle-456",
                "garaging_location": {
                    "latitude": 34.0522,
                    "longitude": -118.2437
                }
            }
        ]
    }

    r = requests.post(url, json=payload, headers=headers)
    r.raise_for_status()
    data = r.json()
    print(data)

get_commercial_auto_risk_score()
```

**Example Response**

```json theme={null}
{
  "job_type": "ca-garaging-risk-score",
  "version": "v2",
  "policy_holder_id": "policy-holder-123",
  "vehicle_risk_scores": [
    {
      "vehicle_id": "vehicle-123",
      "vehicle_risk_score": 62.2
    },
    {
      "vehicle_id": "vehicle-456",
      "vehicle_risk_score": 37.9
    }
  ]
}
```

***

## 3. Personal Auto Telematics

[View documentation](/api-reference/ppa-telematics-risk-score/queue-risk-score-calculation)

**Endpoints**

```
POST /risk-score/ppa-telematics
GET  /risk-score/ppa-telematics/job/{job_id}/status
GET  /risk-score/ppa-telematics/job/{job_id}/result
```

This flow calculates a **risk score** for a personal auto policy based on telematics data uploaded via CSV.

> **Note:** Although this example is for personal auto, the CA telematics is the same structure.

**Sample CSV**\
You can download a [sample-ppa-telematics.csv](https://crash-data-prod.nyc3.cdn.digitaloceanspaces.com/website-assets/data-samples/sample-ppa-telematics.csv) file to try out.

### a) Queue a Telematics Job

```python theme={null}
import requests

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://www.api.risk.matrisk.ai/v1"

def queue_ppa_telematics_job():
    url = f"{BASE_URL}/risk-score/ppa-telematics"
    headers = {
        "Authorization": f"Bearer {API_KEY}"
    }

    data = {
        "version": "v2",
        "policy_holder_id": "policy-holder-123"
    }

    with open("sample-ppa-telematics.csv", "rb") as f:
        files = {"file": ("sample-ppa-telematics.csv", f, "text/csv")}
        r = requests.post(url, files=files, data=data, headers=headers)

    r.raise_for_status()
    job_info = r.json()
    job_id = job_info["job_id"]
    print("Queued job ID:", job_id)
    return job_id


queue_ppa_telematics_job()
```

**Example Response (job queued)**

```json theme={null}
{
  "job_id": "job_a1b2c3d4",
  "status": "processing",
  "error_message": null
}
```

### b) Check the Job Status

```python theme={null}
import requests

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://www.api.risk.matrisk.ai/v1"

def get_ppa_telematics_job_status(job_id: str):
    url = f"{BASE_URL}/risk-score/ppa-telematics/job/{job_id}/status"
    headers = {
        "Authorization": f"Bearer {API_KEY}"
    }
    r = requests.get(url, headers=headers)
    r.raise_for_status()
    status_info = r.json()
    print("Status:", status_info)
    return status_info


status_data = get_ppa_telematics_job_status("job_a1b2c3d4")
```

**Example Response (job status)**

```json theme={null}
{
  "job_id": "job_a1b2c3d4",
  "status": "processing",
  "error_message": null
}
```

### c) Retrieve Final Result

```python theme={null}
import requests

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://www.api.risk.matrisk.ai/v1"

def get_ppa_telematics_job_result(job_id: str):
    url = f"{BASE_URL}/risk-score/ppa-telematics/job/{job_id}/result"
    headers = {
        "Authorization": f"Bearer {API_KEY}"
    }
    r = requests.get(url, headers=headers)
    r.raise_for_status()
    result_data = r.json()
    print("Final Result:", result_data)
    return result_data


result = get_ppa_telematics_job_result("job_a1b2c3d4")
```

**Example Response (final result)**

```json theme={null}
{
  "job_type": "ppa-telematics-risk-score",
  "policy_holder_id": "policy-holder-123",
  "version": "v2",
  "vehicle_risk_scores": [
    {
      "vehicle_id": "vehicle-123",
      "vehicle_risk_score": 20.1,
      "metadata": {
        "start": "2023-01-01T12:00:00",
        "end": "2023-06-01T12:00:00",
        "num_trips": 56,
        "exposure_seconds": 8100,
        "state_exposure": [
          {
            "usstate": "OH",
            "exposure_seconds": 4050,
            "share": 0.5
          },
          {
            "usstate": "MI",
            "exposure_seconds": 4050,
            "share": 0.5
          }
        ]
      }
    }
  ]
}
```

***

## Additional Notes

* **File Upload**: When using the telematics endpoint, you must send your CSV as `multipart/form-data`. The snippet above shows how to open a local file in Python and upload it.
* **Status Polling**: Real-time processing can take several seconds to a few minutes. Continuously call the status endpoint until the `status` changes from `processing` to `completed` or `failed`. Once completed, fetch the final result.

Have a question? [Contact us!](mailto:sergey@matrisk.ai)
