Skip to main content

Calls Endpoint

Retrieve and manage emergency call data stored in DynamoDB and S3 for access911.

Endpoint

GET https://your-api-gateway-url/calls

Request

Headers

HeaderTypeRequiredDescription
AcceptstringNoapplication/json

Query Parameters

ParameterTypeRequiredDefaultDescription
limitintegerNo50Maximum number of calls to return (1-1000)
offsetintegerNo0Number of calls to skip
emergency_typestringNo-Filter by emergency type
severitystringNo-Filter by severity level
statusstringNo-Filter by call status
start_datestringNo-Start date filter (ISO 8601)
end_datestringNo-End date filter (ISO 8601)
locationstringNo-Filter by location area
simulationbooleanNo-Filter by simulation status

Request Examples

Get Recent Calls

curl -X GET "https://your-api-gateway-url/calls?limit=20" \
  -H "Accept: application/json"

Filter by Emergency Type

curl -X GET "https://your-api-gateway-url/calls?emergency_type=structure_fire&limit=10" \
  -H "Accept: application/json"

Filter by Severity

curl -X GET "https://your-api-gateway-url/calls?severity=critical&limit=25" \
  -H "Accept: application/json"

Date Range Filter

curl -X GET "https://your-api-gateway-url/calls?start_date=2023-12-01T00:00:00Z&end_date=2023-12-31T23:59:59Z" \
  -H "Accept: application/json"

Complex Filter

curl -X GET "https://your-api-gateway-url/calls?emergency_type=structure_fire&severity=critical&status=active&limit=50" \
  -H "Accept: application/json"

Response

Success Response

{
  "calls": [
    {
      "conversation_id": "conv_123456789",
      "timestamp": 1703123456,
      "agent_id": "agent_emergency_911",
      "summary": "Caller reported house fire and provided location details.",
      "call_successful": true,
      "duration_secs": 180,
      "transcript_length": 15,
      "created_at": "2023-12-21T10:30:56.789Z",
      "emergency_type": "structure_fire",
      "location": "1234 Main Street, Anytown",
      "latitude": 34.0522,
      "longitude": -118.2437,
      "severity": "critical",
      "status": "active",
      "simulation": false,
      "scenario": null,
      "scenario_name": null
    }
  ],
  "pagination": {
    "limit": 20,
    "offset": 0,
    "total": 150,
    "has_more": true
  },
  "filters": {
    "emergency_type": null,
    "severity": null,
    "status": null,
    "start_date": null,
    "end_date": null,
    "location": null,
    "simulation": null
  }
}

Error Response

{
  "error": "Invalid query parameters",
  "message": "start_date must be in ISO 8601 format",
  "timestamp": "2023-12-21T10:30:56.789Z"
}

Response Fields

FieldTypeDescription
callsarrayArray of emergency call objects
paginationobjectPagination information
pagination.limitintegerMaximum number of calls returned
pagination.offsetintegerNumber of calls skipped
pagination.totalintegerTotal number of calls matching filters
pagination.has_morebooleanWhether more calls are available
filtersobjectApplied filters for reference

Call Object Structure

FieldTypeDescription
conversation_idstringUnique conversation identifier
timestampintegerUnix timestamp of the call
agent_idstringElevenLabs agent identifier
summarystringSummary of the emergency call
call_successfulbooleanWhether the call was successful
duration_secsintegerCall duration in seconds
transcript_lengthintegerNumber of transcript turns
created_atstringISO 8601 timestamp of record creation
emergency_typestringType of emergency
locationstringLocation description
latitudenumberLatitude coordinate
longitudenumberLongitude coordinate
severitystringEmergency severity level
statusstringCurrent call status
simulationbooleanWhether this is a simulated call
scenariostringSimulation scenario (if applicable)
scenario_namestringHuman-readable scenario name

HTTP Status Codes

CodeDescription
200Success - Calls retrieved successfully
400Bad Request - Invalid query parameters
500Internal Server Error - Server error during processing

Filter Options

Emergency Types

ValueDescription
structure_fireStructure fire emergency
evacuation_assistanceEvacuation assistance needed
trapped_personPerson trapped in emergency
medical_emergencyMedical emergency
shelter_informationShelter information request
floodingFlooding emergency
wind_damageWind damage emergency
power_outagePower outage emergency
evacuation_neededEvacuation needed
building_collapseBuilding collapse
gas_leakGas leak emergency
debris_injuryDebris-related injury
building_damageBuilding damage
vehicle_accidentVehicle accident

Severity Levels

ValueDescription
criticalCritical emergency requiring immediate response
highHigh-priority emergency
moderateModerate-priority emergency

Status Values

ValueDescription
activeCall is active and being processed
dispatchedEmergency services have been dispatched
enrouteEmergency services are en route
resolvedEmergency has been resolved
failedCall processing failed

Pagination

The API supports pagination for large result sets:

Pagination Parameters

  • limit: Maximum number of calls to return (1-1000)
  • offset: Number of calls to skip from the beginning

Pagination Example

# Get first 20 calls
curl -X GET "https://your-api-gateway-url/calls?limit=20&offset=0"

# Get next 20 calls
curl -X GET "https://your-api-gateway-url/calls?limit=20&offset=20"

# Get next 20 calls
curl -X GET "https://your-api-gateway-url/calls?limit=20&offset=40"

Sorting

Calls are returned in descending order by timestamp (most recent first).

Error Handling

Common Errors

ErrorDescriptionSolution
Invalid limitLimit parameter out of rangeUse a value between 1 and 1000
Invalid offsetOffset parameter is negativeUse a non-negative integer
Invalid date formatDate parameters not in ISO 8601 formatUse ISO 8601 format (e.g., 2023-12-21T10:30:56Z)
Database errorDynamoDB operation failedCheck AWS credentials and permissions

Error Response Format

{
  "error": "Error type",
  "message": "Detailed error message",
  "timestamp": "2023-12-21T10:30:56.789Z",
  "error_code": "INVALID_PARAMETER"
}

Rate Limits

  • Request rate: 1000 requests per minute
  • Burst limit: 500 requests per minute
  • Timeout: 30 seconds per request

Performance Considerations

Query Optimization

  • Use Filters: Apply filters to reduce result set size
  • Limit Results: Use appropriate limit values
  • Avoid Large Offsets: Large offset values can be slow

Caching

The API implements caching for frequently accessed data:
  • Recent Calls: Cached for 5 minutes
  • Filtered Results: Cached for 2 minutes
  • Count Queries: Cached for 10 minutes

Best Practices

Efficient Queries

  • Use Specific Filters: Apply specific filters to reduce result sets
  • Limit Results: Use appropriate limit values for your use case
  • Monitor Performance: Track query performance and optimize as needed

Error Handling

  • Implement Retry Logic: Retry failed requests with exponential backoff
  • Handle Rate Limits: Implement proper rate limiting in your client
  • Validate Parameters: Validate query parameters before sending requests

Security

  • Use HTTPS: Always use HTTPS for API requests
  • Validate Input: Validate all query parameters
  • Handle Sensitive Data: Be careful with sensitive information in logs

SDK Examples

Python

import requests
from datetime import datetime, timedelta

class DispatchAICallsAPI:
    def __init__(self, base_url):
        self.base_url = base_url
    
    def get_calls(self, **filters):
        params = {}
        
        # Add filters to params
        for key, value in filters.items():
            if value is not None:
                params[key] = value
        
        response = requests.get(f"{self.base_url}/calls", params=params)
        
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"API Error: {response.status_code} - {response.text}")
    
    def get_recent_calls(self, limit=50):
        return self.get_calls(limit=limit)
    
    def get_calls_by_type(self, emergency_type, limit=50):
        return self.get_calls(emergency_type=emergency_type, limit=limit)
    
    def get_calls_by_severity(self, severity, limit=50):
        return self.get_calls(severity=severity, limit=limit)
    
    def get_calls_by_date_range(self, start_date, end_date, limit=50):
        return self.get_calls(
            start_date=start_date.isoformat(),
            end_date=end_date.isoformat(),
            limit=limit
        )

# Usage
api = DispatchAICallsAPI("https://your-api-gateway-url")

# Get recent calls
recent_calls = api.get_recent_calls(limit=20)
print(f"Found {recent_calls['pagination']['total']} calls")

# Get critical emergencies
critical_calls = api.get_calls_by_severity("critical", limit=10)
print(f"Found {len(critical_calls['calls'])} critical calls")

# Get calls from last week
week_ago = datetime.now() - timedelta(days=7)
week_calls = api.get_calls_by_date_range(week_ago, datetime.now())
print(f"Found {len(week_calls['calls'])} calls from last week")

JavaScript

class DispatchAICallsAPI {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
  }
  
  async getCalls(filters = {}) {
    const params = new URLSearchParams();
    
    // Add filters to params
    Object.entries(filters).forEach(([key, value]) => {
      if (value !== null && value !== undefined) {
        params.append(key, value);
      }
    });
    
    try {
      const response = await fetch(`${this.baseUrl}/calls?${params}`);
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      return await response.json();
    } catch (error) {
      console.error('Error fetching calls:', error);
      throw error;
    }
  }
  
  async getRecentCalls(limit = 50) {
    return this.getCalls({ limit });
  }
  
  async getCallsByType(emergencyType, limit = 50) {
    return this.getCalls({ emergency_type: emergencyType, limit });
  }
  
  async getCallsBySeverity(severity, limit = 50) {
    return this.getCalls({ severity, limit });
  }
  
  async getCallsByDateRange(startDate, endDate, limit = 50) {
    return this.getCalls({
      start_date: startDate.toISOString(),
      end_date: endDate.toISOString(),
      limit
    });
  }
}

// Usage
const api = new DispatchAICallsAPI('https://your-api-gateway-url');

// Get recent calls
api.getRecentCalls(20)
  .then(result => console.log(`Found ${result.pagination.total} calls`))
  .catch(error => console.error('Error:', error));

// Get critical emergencies
api.getCallsBySeverity('critical', 10)
  .then(result => console.log(`Found ${result.calls.length} critical calls`))
  .catch(error => console.error('Error:', error));

// Get calls from last week
const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
const now = new Date();
api.getCallsByDateRange(weekAgo, now)
  .then(result => console.log(`Found ${result.calls.length} calls from last week`))
  .catch(error => console.error('Error:', error));

Testing

Unit Testing

import unittest
from unittest.mock import patch, Mock

class TestCallsAPI(unittest.TestCase):
    def setUp(self):
        self.api = DispatchAICallsAPI("https://test-api.com")
    
    def test_get_recent_calls(self):
        with patch('requests.get') as mock_get:
            mock_response = Mock()
            mock_response.status_code = 200
            mock_response.json.return_value = {
                "calls": [],
                "pagination": {"total": 0}
            }
            mock_get.return_value = mock_response
            
            result = self.api.get_recent_calls(limit=20)
            self.assertEqual(result["pagination"]["total"], 0)
    
    def test_get_calls_by_type(self):
        with patch('requests.get') as mock_get:
            mock_response = Mock()
            mock_response.status_code = 200
            mock_response.json.return_value = {
                "calls": [{"emergency_type": "structure_fire"}],
                "pagination": {"total": 1}
            }
            mock_get.return_value = mock_response
            
            result = self.api.get_calls_by_type("structure_fire")
            self.assertEqual(len(result["calls"]), 1)
            self.assertEqual(result["calls"][0]["emergency_type"], "structure_fire")

Integration Testing

# Test basic functionality
curl -X GET "https://your-api-gateway-url/calls?limit=10"

# Test filtering
curl -X GET "https://your-api-gateway-url/calls?emergency_type=structure_fire&limit=5"

# Test error handling
curl -X GET "https://your-api-gateway-url/calls?limit=2000"
Data Privacy: Ensure compliance with data privacy regulations when handling emergency call data. Consider data retention policies and access controls.