.. _api-integration: =============== API Integration =============== This guide explains how to integrate external systems with the tiger Rating Engine REST API for automated premium calculations, product queries, and rating history retrieval. .. contents:: Table of Contents :local: :depth: 2 API Overview ============ Architecture ------------ .. figure:: _static/screenshots/api_architecture.png :alt: API Architecture Diagram :align: center :width: 100% *Screenshot Placeholder: Architecture diagram showing Client Applications → API Gateway → Authentication → REST API → Rating Engine → Database* The tiger Rating Engine API provides: * **RESTful Design**: Standard HTTP methods (GET, POST, PUT, DELETE) * **JSON Format**: All requests and responses in JSON * **Token Authentication**: Secure Bearer token authentication * **Rate Limiting**: Prevent overload with built-in limits * **Versioning**: API version in URL for stability * **Comprehensive Documentation**: Interactive Swagger/OpenAPI docs Base URL -------- .. code-block:: text Production: https://api.tigerrating.com/v1/ Staging: https://staging-api.tigerrating.com/v1/ Development: https://dev-api.tigerrating.com/v1/ Endpoints Overview ------------------ .. table:: Main API Endpoints :widths: 30 20 50 +--------------------------------+--------+---------------------------------------------+ | Endpoint | Method | Description | +================================+========+=============================================+ | /auth/token | POST | Obtain authentication token | +--------------------------------+--------+---------------------------------------------+ | /rating/calculate | POST | Calculate insurance premium | +--------------------------------+--------+---------------------------------------------+ | /rating/products | GET | List available products | +--------------------------------+--------+---------------------------------------------+ | /rating/products/{code} | GET | Get product details | +--------------------------------+--------+---------------------------------------------+ | /rating/runs | GET | Query rating history | +--------------------------------+--------+---------------------------------------------+ | /rating/runs/{id} | GET | Get specific calculation details | +--------------------------------+--------+---------------------------------------------+ | /rating/factors/{product} | GET | Get product rating factors | +--------------------------------+--------+---------------------------------------------+ | /rating/tables/{product} | GET | Get product rating tables | +--------------------------------+--------+---------------------------------------------+ Authentication ============== Obtaining API Credentials ------------------------- .. figure:: _static/screenshots/api_credentials_portal.png :alt: API Credentials Portal :align: center :width: 100% *Screenshot Placeholder: Developer portal showing API Keys section with client ID, client secret (hidden), and "Generate New Key" button* To get API access: 1. Log into Developer Portal at ``https://developers.tigerrating.com`` 2. Navigate to **API Keys** 3. Click **Create New Application** 4. Enter application details: .. code-block:: text Application Name: My Rating System Description: Integration for automated quotes Environment: Production Allowed IPs: 192.168.1.100, 10.0.0.0/24 (optional) 5. Save and copy credentials: .. code-block:: json { "client_id": "app_3a5b7c9d2e4f6g8h", "client_secret": "secret_1a2b3c4d5e6f7g8h9i0j", "api_endpoint": "https://api.tigerrating.com/v1/" } Token Authentication -------------------- .. figure:: _static/screenshots/api_auth_flow.png :alt: Authentication Flow :align: center :width: 100% *Screenshot Placeholder: Sequence diagram showing Client → Auth Endpoint → Token Response → API Calls with Token* Get authentication token: **Request:** .. code-block:: bash curl -X POST https://api.tigerrating.com/v1/auth/token \ -H "Content-Type: application/json" \ -d '{ "client_id": "app_3a5b7c9d2e4f6g8h", "client_secret": "secret_1a2b3c4d5e6f7g8h9i0j" }' **Response:** .. code-block:: json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "refresh_9h8g7f6e5d4c3b2a1" } Using the Token --------------- Include token in all API requests: .. code-block:: bash curl -X GET https://api.tigerrating.com/v1/rating/products \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." Token Refresh ------------- Before expiration, refresh your token: .. code-block:: bash curl -X POST https://api.tigerrating.com/v1/auth/refresh \ -H "Content-Type: application/json" \ -d '{ "refresh_token": "refresh_9h8g7f6e5d4c3b2a1" }' Core API Operations =================== Listing Available Products -------------------------- .. figure:: _static/screenshots/api_products_list.png :alt: Products API Response :align: center :width: 100% *Screenshot Placeholder: JSON response showing array of products with codes, names, and effective dates* **Endpoint:** ``GET /rating/products`` **Request:** .. code-block:: bash curl -X GET https://api.tigerrating.com/v1/rating/products \ -H "Authorization: Bearer {token}" **Response:** .. code-block:: json { "success": true, "data": [ { "product_code": "BOP", "product_name": "Business Owners Policy", "description": "Comprehensive coverage for small businesses", "effective_date": "2025-01-01", "is_active": true }, { "product_code": "GL_POLICY", "product_name": "General Liability", "description": "General liability coverage", "effective_date": "2025-01-01", "is_active": true } ], "count": 2 } Getting Product Details ----------------------- **Endpoint:** ``GET /rating/products/{product_code}`` **Request:** .. code-block:: bash curl -X GET https://api.tigerrating.com/v1/rating/products/BOP \ -H "Authorization: Bearer {token}" **Response:** .. code-block:: json { "success": true, "data": { "product_code": "BOP", "product_name": "Business Owners Policy", "description": "Comprehensive coverage for small businesses", "effective_date": "2025-01-01", "rating_factors": [ { "factor_code": "territory", "factor_name": "Territory", "data_type": "text", "required": true, "validation": { "allowed_values": ["001", "002", "003"] } }, { "factor_code": "building_value", "factor_name": "Building Value", "data_type": "decimal", "required": true, "validation": { "min_value": 50000, "max_value": 10000000 } } ], "available_coverages": [ "property", "general_liability", "business_income" ] } } Calculating Premium ------------------- .. figure:: _static/screenshots/api_calculation_flow.png :alt: Calculation API Flow :align: center :width: 100% *Screenshot Placeholder: Flow diagram showing Request → Validation → Calculation → Response with example JSON* **Endpoint:** ``POST /rating/calculate`` **Request:** .. code-block:: bash curl -X POST https://api.tigerrating.com/v1/rating/calculate \ -H "Authorization: Bearer {token}" \ -H "Content-Type: application/json" \ -d '{ "product_code": "BOP", "effective_date": "2025-02-01", "external_reference": "QUOTE-2025-001", "rating_factors": { "territory": "001", "building_value": 500000, "contents_value": 100000, "building_class": "B", "occupancy_type": "OFFICE", "liability_limit": 1000000, "deductible": 1000 } }' **Response:** .. code-block:: json { "success": true, "data": { "run_id": "RUN-2025-02-01-123456", "product_code": "BOP", "total_premium": 3450.00, "status": "SUCCESS", "coverages": [ { "coverage_type": "property", "premium": 1850.00, "limit": 600000 }, { "coverage_type": "general_liability", "premium": 1200.00, "limit": 1000000 }, { "coverage_type": "business_income", "premium": 400.00, "limit": 100000 } ], "calculation_details": { "base_premium": 3000.00, "territory_factor": 1.15, "class_factor": 1.0, "credits_applied": [], "taxes_fees": 0.00 }, "warnings": [], "execution_time_ms": 245 } } Retrieving Rating History ------------------------- **Endpoint:** ``GET /rating/runs`` **Query Parameters:** .. table:: Query Parameters :widths: 20 20 60 +------------------+----------+----------------------------------------+ | Parameter | Type | Description | +==================+==========+========================================+ | start_date | date | Filter runs after this date | +------------------+----------+----------------------------------------+ | end_date | date | Filter runs before this date | +------------------+----------+----------------------------------------+ | product_code | string | Filter by product | +------------------+----------+----------------------------------------+ | external_ref | string | Filter by external reference | +------------------+----------+----------------------------------------+ | status | string | Filter by status (SUCCESS/FAILED) | +------------------+----------+----------------------------------------+ | limit | integer | Number of results (default: 50) | +------------------+----------+----------------------------------------+ | offset | integer | Pagination offset (default: 0) | +------------------+----------+----------------------------------------+ **Request:** .. code-block:: bash curl -X GET "https://api.tigerrating.com/v1/rating/runs?start_date=2025-02-01&limit=10" \ -H "Authorization: Bearer {token}" **Response:** .. code-block:: json { "success": true, "data": [ { "run_id": "RUN-2025-02-01-123456", "created_at": "2025-02-01T10:30:00Z", "product_code": "BOP", "external_reference": "QUOTE-2025-001", "total_premium": 3450.00, "status": "SUCCESS" } ], "pagination": { "total": 150, "limit": 10, "offset": 0, "has_next": true } } Advanced Integration Patterns ============================== Batch Rating ------------ .. figure:: _static/screenshots/api_batch_rating.png :alt: Batch Rating Process :align: center :width: 100% *Screenshot Placeholder: Diagram showing batch submission → processing queue → results retrieval* For multiple calculations: **Request:** .. code-block:: bash curl -X POST https://api.tigerrating.com/v1/rating/batch \ -H "Authorization: Bearer {token}" \ -H "Content-Type: application/json" \ -d '{ "batch_id": "BATCH-2025-02-01-001", "calculations": [ { "reference": "QUOTE-001", "product_code": "BOP", "effective_date": "2025-02-01", "rating_factors": {...} }, { "reference": "QUOTE-002", "product_code": "BOP", "effective_date": "2025-02-01", "rating_factors": {...} } ] }' **Response:** .. code-block:: json { "success": true, "data": { "batch_id": "BATCH-2025-02-01-001", "status": "PROCESSING", "total_items": 2, "processed": 0, "estimated_completion": "2025-02-01T10:35:00Z", "results_url": "/rating/batch/BATCH-2025-02-01-001/results" } } Webhook Integration ------------------- .. figure:: _static/screenshots/api_webhooks.png :alt: Webhook Configuration :align: center :width: 100% *Screenshot Placeholder: Webhook configuration interface with URL, events selection, and secret key* Configure webhooks for async notifications: **Setup Webhook:** .. code-block:: bash curl -X POST https://api.tigerrating.com/v1/webhooks \ -H "Authorization: Bearer {token}" \ -H "Content-Type: application/json" \ -d '{ "url": "https://yourapp.com/webhooks/rating", "events": ["calculation.completed", "batch.completed"], "secret": "webhook_secret_key" }' **Webhook Payload:** .. code-block:: json { "event": "calculation.completed", "timestamp": "2025-02-01T10:30:15Z", "data": { "run_id": "RUN-2025-02-01-123456", "external_reference": "QUOTE-2025-001", "status": "SUCCESS", "total_premium": 3450.00 }, "signature": "sha256=abcdef123456..." } Rate Limiting ------------- .. figure:: _static/screenshots/api_rate_limits.png :alt: Rate Limiting Headers :align: center :width: 100% *Screenshot Placeholder: Response headers showing X-RateLimit headers with remaining calls and reset time* API rate limits: .. table:: Rate Limits by Plan :widths: 20 20 20 20 20 +----------+---------+----------+----------+----------+ | Plan | Per Min | Per Hour | Per Day | Burst | +==========+=========+==========+==========+==========+ | Basic | 60 | 1,000 | 10,000 | 100 | +----------+---------+----------+----------+----------+ | Standard | 300 | 5,000 | 50,000 | 500 | +----------+---------+----------+----------+----------+ | Premium | 1,000 | 20,000 | 200,000 | 2,000 | +----------+---------+----------+----------+----------+ Check headers for limit status: .. code-block:: text X-RateLimit-Limit: 1000 X-RateLimit-Remaining: 950 X-RateLimit-Reset: 1612137600 Error Handling ============== Error Response Format --------------------- All errors follow consistent format: .. code-block:: json { "success": false, "error": { "code": "VALIDATION_ERROR", "message": "Invalid rating factors provided", "details": [ { "field": "building_value", "error": "Value must be between 50000 and 10000000" } ], "request_id": "req_abc123def456" } } Common Error Codes ------------------ .. table:: Error Codes and Resolution :widths: 25 35 40 +----------------------+--------------------------------+----------------------------------+ | Error Code | Description | Resolution | +======================+================================+==================================+ | AUTH_FAILED | Invalid credentials | Check client ID and secret | +----------------------+--------------------------------+----------------------------------+ | TOKEN_EXPIRED | Access token expired | Refresh token | +----------------------+--------------------------------+----------------------------------+ | VALIDATION_ERROR | Invalid input data | Check field requirements | +----------------------+--------------------------------+----------------------------------+ | PRODUCT_NOT_FOUND | Product code doesn't exist | Verify product code | +----------------------+--------------------------------+----------------------------------+ | RATE_NOT_FOUND | No rates for effective date | Check effective date | +----------------------+--------------------------------+----------------------------------+ | CALCULATION_ERROR | Formula execution failed | Review input values | +----------------------+--------------------------------+----------------------------------+ | RATE_LIMIT_EXCEEDED | Too many requests | Wait or upgrade plan | +----------------------+--------------------------------+----------------------------------+ Retry Strategy -------------- Implement exponential backoff: .. code-block:: python import time import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry def create_session(): session = requests.Session() retry = Retry( total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504] ) adapter = HTTPAdapter(max_retries=retry) session.mount("https://", adapter) return session def calculate_premium(data, token): session = create_session() headers = {"Authorization": f"Bearer {token}"} try: response = session.post( "https://api.tigerrating.com/v1/rating/calculate", json=data, headers=headers, timeout=30 ) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"Error: {e}") # Implement retry logic time.sleep(2 ** attempt) # Exponential backoff Client Libraries ================ Python SDK ---------- Install the Python client: .. code-block:: bash pip install tigerrating-python Usage example: .. code-block:: python from tigerrating import TigerRatingClient # Initialize client client = TigerRatingClient( client_id="app_3a5b7c9d2e4f6g8h", client_secret="secret_1a2b3c4d5e6f7g8h9i0j", environment="production" ) # Calculate premium result = client.calculate_premium( product_code="BOP", effective_date="2025-02-01", factors={ "territory": "001", "building_value": 500000, "building_class": "B", "occupancy_type": "OFFICE", "liability_limit": 1000000, "deductible": 1000 } ) print(f"Total Premium: ${result.total_premium}") for coverage in result.coverages: print(f" {coverage.type}: ${coverage.premium}") JavaScript/Node.js SDK ---------------------- Install the Node.js client: .. code-block:: bash npm install @tigerrating/api-client Usage example: .. code-block:: javascript const TigerRating = require('@tigerrating/api-client'); // Initialize client const client = new TigerRating({ clientId: 'app_3a5b7c9d2e4f6g8h', clientSecret: 'secret_1a2b3c4d5e6f7g8h9i0j', environment: 'production' }); // Calculate premium async function calculatePremium() { try { const result = await client.calculatePremium({ productCode: 'BOP', effectiveDate: '2025-02-01', factors: { territory: '001', building_value: 500000, building_class: 'B', occupancy_type: 'OFFICE', liability_limit: 1000000, deductible: 1000 } }); console.log(`Total Premium: $${result.totalPremium}`); result.coverages.forEach(coverage => { console.log(` ${coverage.type}: $${coverage.premium}`); }); } catch (error) { console.error('Error:', error.message); } } calculatePremium(); .NET SDK -------- Install via NuGet: .. code-block:: bash dotnet add package TigerRating.Client Usage example: .. code-block:: csharp using TigerRating.Client; var client = new TigerRatingClient( clientId: "app_3a5b7c9d2e4f6g8h", clientSecret: "secret_1a2b3c4d5e6f7g8h9i0j", environment: Environment.Production ); var factors = new Dictionary { {"territory", "001"}, {"building_value", 500000}, {"building_class", "B"}, {"occupancy_type", "OFFICE"}, {"liability_limit", 1000000}, {"deductible", 1000} }; var result = await client.CalculatePremiumAsync( productCode: "BOP", effectiveDate: DateTime.Parse("2025-02-01"), factors: factors ); Console.WriteLine($"Total Premium: ${result.TotalPremium}"); Testing and Development ======================= API Sandbox ----------- .. figure:: _static/screenshots/api_sandbox.png :alt: API Testing Sandbox :align: center :width: 100% *Screenshot Placeholder: Interactive API sandbox with request builder, parameter inputs, and response viewer* Test API calls in sandbox: 1. Navigate to ``https://sandbox.tigerrating.com`` 2. Use test credentials: .. code-block:: json { "client_id": "test_client_id", "client_secret": "test_secret_key" } 3. No charges for sandbox calls 4. Data resets daily Postman Collection ------------------ .. figure:: _static/screenshots/postman_collection.png :alt: Postman Collection :align: center :width: 100% *Screenshot Placeholder: Postman interface showing tiger Rating API collection with folders for Auth, Products, Calculations* Import our Postman collection: 1. Download from ``https://api.tigerrating.com/postman/collection.json`` 2. Import into Postman 3. Set environment variables: .. code-block:: json { "base_url": "https://api.tigerrating.com/v1", "client_id": "your_client_id", "client_secret": "your_client_secret" } 4. Run example requests Mock Server ----------- Use mock server for development: .. code-block:: bash docker run -p 8080:8080 tigerrating/mock-api:latest Mock endpoints return realistic responses without actual calculations. Monitoring and Analytics ======================== API Dashboard ------------- .. figure:: _static/screenshots/api_dashboard.png :alt: API Usage Dashboard :align: center :width: 100% *Screenshot Placeholder: Dashboard showing API call volume graph, success rate, average latency, and top endpoints* Monitor usage at ``https://developers.tigerrating.com/dashboard``: * **Call Volume**: Requests per time period * **Success Rate**: Percentage of successful calls * **Latency**: Average response times * **Error Analysis**: Common error patterns * **Usage by Endpoint**: Most used operations Logging Best Practices ---------------------- Log important events: .. code-block:: python import logging import json logger = logging.getLogger('tigerrating') def log_api_call(endpoint, request_data, response): logger.info(json.dumps({ "event": "api_call", "endpoint": endpoint, "request": { "product_code": request_data.get("product_code"), "external_ref": request_data.get("external_reference") }, "response": { "run_id": response.get("data", {}).get("run_id"), "status": response.get("success"), "premium": response.get("data", {}).get("total_premium") }, "timestamp": datetime.utcnow().isoformat() })) Security Best Practices ======================= Protecting Credentials ---------------------- Never expose credentials: .. code-block:: python # BAD - Don't hardcode credentials client_id = "app_3a5b7c9d2e4f6g8h" # Never do this! # GOOD - Use environment variables import os client_id = os.environ.get('TIGERRATING_CLIENT_ID') client_secret = os.environ.get('TIGERRATING_CLIENT_SECRET') # BETTER - Use secret management from aws_secretsmanager import get_secret credentials = get_secret('tigerrating/api/credentials') IP Whitelisting --------------- Restrict access by IP: .. figure:: _static/screenshots/ip_whitelist.png :alt: IP Whitelist Configuration :align: center :width: 100% *Screenshot Placeholder: Security settings showing IP whitelist with ranges and descriptions* 1. Go to Security Settings 2. Add allowed IP ranges 3. Enable IP restriction Webhook Security ---------------- Verify webhook signatures: .. code-block:: python import hmac import hashlib def verify_webhook(payload, signature, secret): expected = hmac.new( secret.encode(), payload.encode(), hashlib.sha256 ).hexdigest() return hmac.compare_digest( f"sha256={expected}", signature ) Migration Guide =============== From Manual Process ------------------- Transition steps: 1. **Phase 1**: Test API in sandbox 2. **Phase 2**: Pilot with select products 3. **Phase 3**: Parallel run (manual + API) 4. **Phase 4**: Full API adoption From Legacy System ------------------ Migration checklist: .. code-block:: text ☐ Map legacy fields to API fields ☐ Convert data formats ☐ Test calculation accuracy ☐ Implement error handling ☐ Set up monitoring ☐ Train staff ☐ Plan rollback strategy Support Resources ================= Documentation ------------- * **API Reference**: ``https://api.tigerrating.com/docs`` * **OpenAPI Spec**: ``https://api.tigerrating.com/openapi.json`` * **Change Log**: ``https://developers.tigerrating.com/changelog`` * **Status Page**: ``https://status.tigerrating.com`` Getting Help ------------ * **Developer Forum**: ``https://forum.tigerrating.com/developers`` * **Support Email**: api-support@tigerrating.com * **Slack Channel**: tigerrating.slack.com #api-support * **Office Hours**: Thursdays 2-3 PM EST Next Steps ========== * **Quick Start**: :doc:`getting_started` * **Product Setup**: :doc:`product_configuration` * **Manual Rating**: :doc:`performing_calculations` * **User Guide**: :doc:`user_guide` .. tip:: Start with the sandbox environment to test your integration before using production credentials. .. warning:: Rate limits apply to all API calls. Monitor your usage to avoid disruptions.