DevelopersAPI Reference

    API Reference

    Complete documentation for the TouchpointHQ REST API. All endpoints return JSON and require API key authentication.

    HTTPS Required
    JSON Responses
    Rate Limit: 1000/hour

    Getting Started

    Follow these steps to make your first API call

    1

    Get Your API Key

    Request API access through our sales team. You'll receive a unique API key that identifies your organization and determines your rate limits and access level.

    Keep your API key secure

    Never expose your API key in client-side code or public repositories. Store it in environment variables or a secure secrets manager.

    Request API Access
    2

    Set Up Your Environment

    Configure your development environment with the API base URL and your authentication credentials.

    .env
    # TouchpointHQ API Configuration
    TOUCHPOINT_API_URL=https://api.touchpointhq.com
    TOUCHPOINT_API_KEY=your_api_key_here
    TOUCHPOINT_API_VERSION=v1
    3

    Make Your First Request

    Test your setup by making a simple request to the HEDIS compliance endpoint. This will verify your API key is working correctly.

    Terminal
    curl -X GET "https://api.touchpointhq.com/v1/hedis/compliance" \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json"
    4

    Verify the Response

    A successful response will return your organization's HEDIS compliance data. Here's an example of what to expect:

    200 OK
    Response
    {
      "organization_id": "org_abc123",
      "period": {
        "start": "2024-01-01",
        "end": "2024-12-31"
      },
      "measures": [
        {
          "measure_id": "DSF-BH",
          "measure_name": "Depression Screening and Follow-Up",
          "rate": 82.8,
          "status": "above_50th"
        }
      ],
      "summary": {
        "total_measures": 8,
        "above_90th": 3,
        "above_50th": 4
      }
    }
    5

    Explore More Endpoints

    Now that you're set up, explore the full API capabilities. Here are some popular next steps:

    HEDIS Trends

    Track compliance over time with historical data

    Stratification

    Analyze equity gaps across demographics

    Webhooks

    Get real-time notifications for events

    Patient API

    Manage patient records programmatically

    Authentication

    All API requests require an API key passed in the Authorization header. Contact sales to obtain your organization's API key.

    curl -X GET "https://api.touchpointhq.com/v1/hedis/compliance" \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json"

    Rate Limiting & Usage Quotas

    API requests are rate-limited to ensure fair usage and system stability. Rate limits are applied per API key and vary by plan tier.

    Rate Limits by Plan

    Request limits per hour based on your subscription tier

    PlanRequests/HourRequests/DayBurst Limit
    Starter
    1,00010,00050/min
    Professional
    5,00050,000200/min
    Enterprise
    25,000250,0001,000/min
    Custom
    Contact sales for custom rate limits

    Rate Limit Headers

    Headers included in every API response to track your usage

    HeaderDescription
    X-RateLimit-LimitMaximum requests allowed per hour
    X-RateLimit-RemainingRequests remaining in current window
    X-RateLimit-ResetUnix timestamp when the rate limit resets
    Retry-AfterSeconds to wait before retrying (only on 429 responses)

    Example Response Headers:

    HTTP/1.1 200 OK
    X-RateLimit-Limit: 5000
    X-RateLimit-Remaining: 4847
    X-RateLimit-Reset: 1735401600
    Content-Type: application/json

    Monthly Usage Quotas

    Additional limits on specific API operations

    OperationStarterProfessionalEnterprise
    Patient Records5005,000Unlimited
    Assessment Submissions1,00010,000Unlimited
    HEDIS Reports50/month500/monthUnlimited
    Bulk Data Exports5/month50/monthUnlimited
    Webhook Endpoints31050
    API Keys210Unlimited

    Handling Rate Limits

    Best practices for dealing with rate limit responses

    When you exceed your rate limit, the API returns a 429 Too Many Requests response. Implement exponential backoff to handle rate limits gracefully.

    async function apiRequestWithRetry(url, options, maxRetries = 3) {
      for (let attempt = 0; attempt < maxRetries; attempt++) {
        const response = await fetch(url, options);
        
        if (response.status === 429) {
          const retryAfter = response.headers.get('Retry-After') || 60;
          const waitTime = Math.min(
            parseInt(retryAfter) * 1000,
            Math.pow(2, attempt) * 1000  // Exponential backoff
          );
          
          console.log(`Rate limited. Waiting ${waitTime}ms before retry...`);
          await new Promise(resolve => setTimeout(resolve, waitTime));
          continue;
        }
        
        return response;
      }
      
      throw new Error('Max retries exceeded');
    }

    Pro Tip

    Monitor the X-RateLimit-Remaining header and proactively slow down requests when approaching your limit to avoid 429 errors.

    SDKs & Client Libraries

    Official client libraries to integrate TouchpointHQ into your application quickly. All SDKs handle authentication, rate limiting, and error handling automatically.

    JS
    JavaScript / TypeScript

    v2.1.0

    Full-featured SDK for Node.js, browsers, and edge runtimes

    Installation

    npm install @touchpointhq/sdk
    yarn add @touchpointhq/sdk

    Quick Start

    import { TouchpointHQ } from '@touchpointhq/sdk';
    
    // Initialize the client
    const client = new TouchpointHQ({
      apiKey: process.env.TOUCHPOINTHQ_API_KEY,
      // Optional: specify environment
      environment: 'production', // or 'sandbox'
    });
    
    // Get HEDIS compliance rates
    const compliance = await client.hedis.getCompliance({
      periodStart: '2024-01-01',
      periodEnd: '2024-12-31',
    });
    
    console.log(`Overall compliance: ${compliance.summary.above_50th} measures above 50th percentile`);
    
    // List patients with pagination
    const patients = await client.patients.list({
      status: 'active',
      limit: 50,
    });
    
    // Submit an assessment
    const assessment = await client.assessments.create({
      patientId: 'pat_123abc',
      formCode: 'PHQ-9',
      responses: {
        q1: 2, q2: 1, q3: 2, q4: 3, q5: 2,
        q6: 1, q7: 2, q8: 1, q9: 0
      },
    });
    
    console.log(`Assessment score: ${assessment.totalScore} (${assessment.severityLevel})`);

    PY
    Python

    v1.4.2

    Async-first SDK with type hints and Pydantic models

    Installation

    pip install touchpointhq
    poetry add touchpointhq

    Quick Start

    import os
    from touchpointhq import TouchpointHQ, AsyncTouchpointHQ
    
    # Synchronous client
    client = TouchpointHQ(api_key=os.environ["TOUCHPOINTHQ_API_KEY"])
    
    # Get HEDIS compliance
    compliance = client.hedis.get_compliance(
        period_start="2024-01-01",
        period_end="2024-12-31"
    )
    
    for measure in compliance.measures:
        print(f"{measure.measure_name}: {measure.rate}%")
    
    # Async client for high-performance applications
    async def main():
        async with AsyncTouchpointHQ(api_key=os.environ["TOUCHPOINTHQ_API_KEY"]) as client:
            # Fetch multiple resources concurrently
            compliance, patients, gaps = await asyncio.gather(
                client.hedis.get_compliance(),
                client.patients.list(status="active", limit=100),
                client.equity.get_gaps(measure_id="DSF-BH")
            )
            
            print(f"Found {len(patients.patients)} active patients")
            print(f"Equity gaps identified: {len(gaps.gaps)}")
    
    # Run async code
    import asyncio
    asyncio.run(main())

    Other Languages

    Community-maintained SDKs and direct API access

    RB
    Ruby
    Community
    gem install touchpointhqView on RubyGems →
    GO
    Go
    Community
    go get github.com/touchpointhq/sdk-goView on GitHub →
    PHP
    PHP
    Community
    composer require touchpointhq/sdkView on Packagist →
    C#
    .NET
    Community
    dotnet add package TouchpointHQView on NuGet →

    Direct API Access

    For languages without an SDK, you can call the REST API directly. The API follows standard REST conventions and returns JSON responses.

    Base URL: https://api.touchpointhq.com/v1

    SDK Features

    All official SDKs include these built-in features

    Automatic Retries

    Exponential backoff for transient failures

    Rate Limit Handling

    Automatic throttling when limits are reached

    Type Safety

    Full TypeScript/Python type hints

    Pagination Helpers

    Iterate through large result sets easily

    Request Logging

    Built-in debug logging for troubleshooting

    Webhook Verification

    Helper methods to verify webhook signatures

    API Explorer

    Test API endpoints directly from the documentation. Responses are simulated for demonstration.

    Get current HEDIS compliance rates for all measures

    Your API key is only used for this demo and is not stored or transmitted.

    (string)
    (string)
    (string)
    GET
    /v1/hedis/compliance

    Get current HEDIS compliance rates for all measures

    Code Examples

    cURL
    curl -X GET "https://api.touchpointhq.com/v1/hedis/compliance" \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json"

    Parameters

    NameTypeRequiredDescription
    period_startstringOptionalStart date (YYYY-MM-DD). Defaults to current year.
    period_endstringOptionalEnd date (YYYY-MM-DD). Defaults to today.
    measure_idsstring[]OptionalFilter to specific measure IDs

    Example Response

    {
      "organization_id": "org_abc123",
      "period": {
        "start": "2024-01-01",
        "end": "2024-12-31"
      },
      "measures": [
        {
          "measure_id": "DSF-BH",
          "measure_name": "Depression Screening and Follow-Up",
          "description": "Percentage of patients screened for depression and receiving follow-up",
          "numerator": 847,
          "denominator": 1023,
          "rate": 82.8,
          "benchmark_50th": 75.0,
          "benchmark_90th": 88.0,
          "status": "above_50th",
          "trend": {
            "direction": "improving",
            "change_pct": 4.2
          }
        },
        {
          "measure_id": "FUH-7",
          "measure_name": "Follow-Up After Hospitalization (7 Days)",
          "description": "Follow-up within 7 days of mental health hospitalization",
          "numerator": 156,
          "denominator": 189,
          "rate": 82.5,
          "benchmark_50th": 52.0,
          "benchmark_90th": 68.0,
          "status": "above_90th",
          "trend": {
            "direction": "stable",
            "change_pct": 0.3
          }
        }
      ],
      "summary": {
        "total_measures": 8,
        "above_90th": 3,
        "above_50th": 4,
        "below_50th": 1
      }
    }
    GET
    /v1/hedis/measures

    List all supported HEDIS measures with scoring criteria

    Code Examples

    cURL
    curl -X GET "https://api.touchpointhq.com/v1/hedis/measures" \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json"

    Parameters

    NameTypeRequiredDescription
    categorystringOptionalFilter by category: depression, anxiety, substance_use, etc.

    Example Response

    {
      "measures": [
        {
          "measure_id": "DSF-BH",
          "measure_name": "Depression Screening and Follow-Up",
          "category": "depression",
          "assessment_tools": ["PHQ-9", "PHQ-2"],
          "eligibility": {
            "age_min": 12,
            "age_max": null,
            "diagnoses": ["F32.*", "F33.*"]
          },
          "numerator_criteria": "Positive screen AND follow-up within 30 days",
          "denominator_criteria": "All patients with depression diagnosis",
          "scoring": {
            "positive_threshold": 10,
            "response_required_within_days": 30
          }
        }
      ]
    }

    Webhooks

    Receive real-time notifications when events occur in your TouchpointHQ account. Configure webhook endpoints to be notified when assessments are completed, alerts are triggered, or patient data changes.

    Setting Up Webhooks

    Configure your endpoint to receive webhook notifications

    1. Navigate to Settings → API & Integrations → Webhooks in your dashboard
    2. Click Add Endpoint and enter your HTTPS URL
    3. Select which events you want to receive
    4. Copy the signing secret to verify webhook authenticity

    Security Requirement

    Your endpoint must use HTTPS and respond with a 2xx status code within 30 seconds.

    Webhook Events

    Available event types you can subscribe to

    Event TypeDescription
    assessment.completedFired when a patient completes an assessment
    assessment.scheduledFired when a new assessment is scheduled
    assessment.expiredFired when an assessment link expires without completion
    alert.triggeredFired when a clinical alert is triggered (score change, high severity)
    alert.acknowledgedFired when a provider acknowledges an alert
    patient.createdFired when a new patient is added to the system
    patient.updatedFired when patient information is updated
    hedis.threshold_crossedFired when a HEDIS measure crosses a benchmark threshold

    Payload Examples

    Sample webhook payloads for common events

    assessment.completed
    {
      "id": "evt_abc123xyz",
      "type": "assessment.completed",
      "created_at": "2024-12-28T14:30:00Z",
      "data": {
        "assessment_id": "asmt_789def",
        "patient_id": "pat_456ghi",
        "patient_external_id": "MRN-12345",
        "form_code": "PHQ-9",
        "form_name": "Patient Health Questionnaire-9",
        "total_score": 14,
        "severity_level": "moderate",
        "previous_score": 18,
        "score_change": -4,
        "completed_at": "2024-12-28T14:29:45Z",
        "provider_id": "prov_123abc",
        "hedis_measures_affected": ["DSF-BH"],
        "alerts_generated": []
      },
      "metadata": {
        "organization_id": "org_xyz789",
        "environment": "production"
      }
    }
    alert.triggered
    {
      "id": "evt_def456uvw",
      "type": "alert.triggered",
      "created_at": "2024-12-28T14:31:00Z",
      "data": {
        "alert_id": "alert_xyz123",
        "alert_type": "score_increase",
        "severity": "high",
        "patient_id": "pat_456ghi",
        "patient_external_id": "MRN-12345",
        "form_code": "PHQ-9",
        "message": "PHQ-9 score increased significantly",
        "current_score": 22,
        "previous_score": 14,
        "score_change": 8,
        "percent_change": 57.1,
        "threshold_exceeded": true,
        "requires_follow_up": true,
        "provider_id": "prov_123abc",
        "assessment_id": "asmt_newxyz"
      },
      "metadata": {
        "organization_id": "org_xyz789",
        "environment": "production"
      }
    }
    hedis.threshold_crossed
    {
      "id": "evt_ghi789rst",
      "type": "hedis.threshold_crossed",
      "created_at": "2024-12-28T15:00:00Z",
      "data": {
        "measure_id": "DSF-BH",
        "measure_name": "Depression Screening and Follow-Up",
        "previous_rate": 74.8,
        "current_rate": 75.2,
        "threshold_type": "50th_percentile",
        "threshold_value": 75.0,
        "direction": "crossed_above",
        "numerator": 752,
        "denominator": 1000
      },
      "metadata": {
        "organization_id": "org_xyz789",
        "environment": "production"
      }
    }

    Verifying Webhook Signatures

    Validate that webhooks are genuinely from TouchpointHQ

    Each webhook request includes a X-TouchpointHQ-Signature header containing an HMAC-SHA256 signature. Verify this signature using your webhook signing secret.

    Node.js Example

    const crypto = require('crypto');
    
    function verifyWebhookSignature(payload, signature, secret) {
      const expectedSignature = crypto
        .createHmac('sha256', secret)
        .update(payload, 'utf8')
        .digest('hex');
      
      const trusted = Buffer.from(expectedSignature, 'hex');
      const untrusted = Buffer.from(signature, 'hex');
      
      return crypto.timingSafeEqual(trusted, untrusted);
    }
    
    // In your webhook handler:
    app.post('/webhooks/touchpointhq', (req, res) => {
      const signature = req.headers['x-touchpointhq-signature'];
      const isValid = verifyWebhookSignature(
        JSON.stringify(req.body),
        signature,
        process.env.WEBHOOK_SECRET
      );
      
      if (!isValid) {
        return res.status(401).send('Invalid signature');
      }
      
      // Process the webhook...
      res.status(200).send('OK');
    });

    Python Example

    import hmac
    import hashlib
    
    def verify_webhook_signature(payload: str, signature: str, secret: str) -> bool:
        expected = hmac.new(
            secret.encode('utf-8'),
            payload.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()
        
        return hmac.compare_digest(expected, signature)
    
    # In your Flask handler:
    @app.route('/webhooks/touchpointhq', methods=['POST'])
    def handle_webhook():
        signature = request.headers.get('X-TouchpointHQ-Signature')
        is_valid = verify_webhook_signature(
            request.data.decode('utf-8'),
            signature,
            os.environ['WEBHOOK_SECRET']
        )
        
        if not is_valid:
            return 'Invalid signature', 401
        
        # Process the webhook...
        return 'OK', 200

    Retry Policy

    How we handle failed webhook deliveries

    If your endpoint returns a non-2xx status code or times out, we'll retry the webhook with exponential backoff:

    1

    minute

    1st retry

    5

    minutes

    2nd retry

    30

    minutes

    3rd retry

    2

    hours

    Final retry

    After 4 failed attempts, the webhook will be marked as failed. You can view failed webhooks and manually retry them from the dashboard.

    API Changelog

    Version history and breaking changes

    Current
    v1.3.0Released December 15, 2024
    New Features
    • Added /v1/stratification/breakdown endpoint for demographic stratification
    • New webhook event types: compliance.threshold_crossed and equity.gap_detected
    • Support for filtering trends by provider ID
    • Added projected_year_end field to HEDIS trends response
    Improvements
    • Improved response times for compliance endpoints by 40%
    • Enhanced rate limiting with better burst handling
    • More detailed error messages for validation failures
    v1.2.0October 28, 2024
    New Features:
    • Equity gaps analysis endpoints
    • Bulk patient import via API
    • Assessment scheduling endpoints
    Breaking Change:

    Renamed patient_mrn field to external_id across all patient endpoints. Update your integrations before upgrading.

    v1.1.0August 15, 2024
    New Features:
    • Webhook support for real-time notifications
    • HEDIS trends endpoint with historical data
    • Pagination support for all list endpoints
    Deprecations:
    • /v1/reports/hedis - Use /v1/hedis/compliance instead
    v1.0.0June 1, 2024
    Initial Release
    Initial API Release:
    • HEDIS compliance and measures endpoints
    • Patient management API
    • Assessment forms and responses
    • API key authentication

    Need help migrating?

    Our team can help you upgrade to the latest API version with minimal disruption to your integration.

    Contact Support

    Error Codes

    Status CodeError TypeDescription
    400Bad RequestInvalid request parameters
    401UnauthorizedMissing or invalid API key
    403ForbiddenAPI key doesn't have access to this resource
    404Not FoundResource not found
    429Rate LimitedToo many requests. Retry after the specified time.
    500Server ErrorInternal server error. Contact support.

    Troubleshooting

    Common issues and how to resolve them

    Authentication Errors

    401 Unauthorized
    Invalid or missing API key

    This error occurs when the API key is missing, malformed, or has been revoked.

    Solutions:

    • Verify your API key is correctly formatted: Bearer YOUR_API_KEY
    • Check that you're using the Authorization header, not a query parameter
    • Ensure your API key hasn't expired or been revoked
    • Confirm you're using the correct key for the environment (test vs. production)
    403 Forbidden
    Insufficient permissions

    Your API key is valid but doesn't have access to the requested resource.

    Solutions:

    • Verify your API key has the required scopes for this endpoint
    • Check if the resource belongs to your organization
    • Contact support to upgrade your API access level

    Rate Limiting Issues

    429 Too Many Requests
    Rate limit exceeded

    You've exceeded your allowed requests per time window.

    Solutions:

    • Check the Retry-After header for when to retry
    • Implement exponential backoff in your retry logic
    • Cache responses to reduce API calls
    • Batch multiple operations into single requests where possible
    • Contact sales to upgrade your rate limits

    Example: Checking rate limit headers

    // Response headers to monitor
    X-RateLimit-Limit: 1000
    X-RateLimit-Remaining: 0
    X-RateLimit-Reset: 1703779200
    Retry-After: 3600

    Request Format Issues

    400 Bad Request
    Invalid JSON or parameters

    The request body or parameters don't match the expected format.

    Common causes & solutions:

    • Malformed JSON: Validate your JSON using a linter before sending
    • Missing required fields: Check the API reference for required parameters
    • Invalid date format: Use ISO 8601 format: YYYY-MM-DD
    • Wrong data type: Ensure numbers aren't quoted as strings
    • Invalid enum value: Check allowed values in the documentation
    Content-Type header missing

    All requests with a body must include the Content-Type header.

    // Always include this header for POST/PUT requests
    Content-Type: application/json

    Data & Response Issues

    Empty or unexpected results

    API returns empty arrays or unexpected data.

    Solutions:

    • Verify the date range parameters are correct
    • Check if filters are too restrictive
    • Ensure patient/measure IDs exist in your organization
    • Confirm data has been synced for the requested period
    Stale or cached data

    Data doesn't reflect recent changes or submissions.

    Solutions:

    • HEDIS calculations update every 15 minutes
    • Use webhooks for real-time updates instead of polling
    • Add a cache-busting parameter if using client-side caching

    Webhook Issues

    Webhooks not being received

    Troubleshooting steps:

    • Verify your endpoint URL is publicly accessible (not localhost)
    • Ensure your endpoint returns 2xx status within 30 seconds
    • Check your firewall allows incoming HTTPS requests
    • Verify the webhook is active in your dashboard
    • Check the webhook delivery logs for failure reasons
    Signature verification failing

    Solutions:

    • Use the raw request body for verification (not parsed JSON)
    • Ensure you're using the correct webhook secret
    • Check for encoding issues when computing the HMAC
    • Verify you're using SHA-256 for the signature algorithm

    Still having issues?

    If you're still experiencing problems after trying these solutions, our developer support team is here to help. Include your request ID from the response headers when contacting us.

    Ready to Integrate?

    Contact our team to get your API key and discuss your integration requirements.

    Request API Access