Skip to content

Compliance Checking API ​

Overview ​

The Compliance Checking API ensures that AI requests and responses meet regulatory requirements including GDPR, CCPA, HIPAA, SOX, and PCI-DSS. This API automatically classifies data sensitivity, detects PII, and provides compliance recommendations for enterprise customers.

Endpoint ​

POST /api/v1/compliance/check

Authentication ​

Requires valid API key or session authentication. Enterprise customers have access to full compliance features.

Rate Limits ​

  • Free Tier: Not available
  • Standard Tier: 100 requests/hour
  • Professional Tier: 1,000 requests/hour
  • Enterprise Tier: Unlimited

Request Format ​

Headers ​

http
Content-Type: application/json
Authorization: Bearer <api-key>

Request Body ​

json
{
  "requestId": "string (required)",
  "data": {
    "prompt": "string (required)",
    "response": "string (optional)",
    "metadata": {
      "userId": "string",
      "sessionId": "string",
      "timestamp": "string (ISO 8601)",
      "ipAddress": "string",
      "userAgent": "string"
    }
  },
  "regulations": [
    "gdpr" | "ccpa" | "hipaa" | "sox" | "pci_dss"
  ],
  "context": {
    "userId": "string (required)",
    "companyId": "string (required)",
    "country": "string (required)",
    "industry": "string (required)",
    "dataTypes": [
      "personal" | "financial" | "health" | "legal"
    ]
  }
}

Field Descriptions ​

FieldTypeRequiredDescription
requestIdstring✅Unique identifier for compliance check
data.promptstring✅Prompt text to analyze
data.responsestring❌AI response to analyze (optional)
data.metadataobject❌Additional context metadata
regulationsarray✅Regulations to check compliance against
context.userIdstring✅User making the request
context.companyIdstring✅Organization identifier
context.countrystring✅Country code (ISO 3166-1)
context.industrystring✅Industry sector
context.dataTypesarray❌Expected data types in content

Response Format ​

Success Response (200 OK) ​

json
{
  "requestId": "string",
  "compliant": boolean,
  "violations": [
    {
      "regulation": "string",
      "severity": "critical" | "high" | "medium" | "low",
      "description": "string",
      "remediationRequired": boolean,
      "suggestedAction": "string"
    }
  ],
  "dataClassification": {
    "sensitivity": "public" | "internal" | "confidential" | "restricted",
    "piiDetected": boolean,
    "piiTypes": [
      "email" | "phone" | "ssn" | "credit_card" | "address" | "name"
    ],
    "retentionPeriod": number,
    "encryptionRequired": boolean
  },
  "auditLog": {
    "logged": boolean,
    "logId": "string",
    "retentionDays": number
  },
  "consentRequired": {
    "needed": boolean,
    "type": "explicit" | "implied" | "opt_out",
    "obtained": boolean
  },
  "recommendations": [
    "string"
  ],
  "processingTime": number
}

Response Field Descriptions ​

FieldTypeDescription
requestIdstringEcho of request identifier
compliantbooleanOverall compliance status
violationsarrayDetected compliance violations
violations[].regulationstringRegulation violated
violations[].severityenumSeverity of violation
violations[].descriptionstringDescription of violation
violations[].remediationRequiredbooleanWhether immediate action needed
violations[].suggestedActionstringRecommended remediation
dataClassificationobjectData sensitivity classification
dataClassification.sensitivityenumOverall sensitivity level
dataClassification.piiDetectedbooleanWhether PII was detected
dataClassification.piiTypesarrayTypes of PII found
dataClassification.retentionPeriodnumberRequired retention period (days)
dataClassification.encryptionRequiredbooleanWhether encryption is required
auditLogobjectAudit logging information
consentRequiredobjectUser consent requirements
recommendationsarrayCompliance recommendations
processingTimenumberProcessing time in milliseconds

Supported Regulations ​

GDPR (General Data Protection Regulation) ​

Scope: European Union residents Key Requirements:

  • Explicit consent for data processing
  • Right to erasure ("right to be forgotten")
  • Data portability
  • Breach notification within 72 hours
  • Privacy by design
json
{
  "regulation": "gdpr",
  "requirements": {
    "consent": "explicit",
    "dataRetention": 2555, // 7 years max
    "encryptionRequired": true,
    "breachNotification": 72, // hours
    "rightToErasure": true,
    "dataPortability": true
  }
}

CCPA (California Consumer Privacy Act) ​

Scope: California residents Key Requirements:

  • Right to know what personal information is collected
  • Right to delete personal information
  • Right to opt-out of sale of personal information
  • Non-discrimination for exercising rights
json
{
  "regulation": "ccpa",
  "requirements": {
    "consent": "opt_out",
    "dataRetention": 730, // 2 years default
    "rightToDelete": true,
    "rightToKnow": true,
    "optOutOfSale": true
  }
}

HIPAA (Health Insurance Portability and Accountability Act) ​

Scope: US healthcare data Key Requirements:

  • Protected Health Information (PHI) safeguards
  • Business Associate Agreements (BAA)
  • Encryption at rest and in transit
  • Access logging and monitoring
json
{
  "regulation": "hipaa",
  "requirements": {
    "phiProtection": true,
    "encryptionRequired": true,
    "accessLogging": true,
    "businessAssociateAgreement": true,
    "dataRetention": 2190 // 6 years
  }
}

SOX (Sarbanes-Oxley Act) ​

Scope: US public companies Key Requirements:

  • Financial data integrity
  • Internal controls documentation
  • Executive certification
  • Audit trail maintenance
json
{
  "regulation": "sox",
  "requirements": {
    "auditTrail": true,
    "dataIntegrity": true,
    "internalControls": true,
    "dataRetention": 2555 // 7 years
  }
}

PCI-DSS (Payment Card Industry Data Security Standard) ​

Scope: Payment card data processing Key Requirements:

  • Cardholder data protection
  • Secure networks and systems
  • Strong access control measures
  • Regular monitoring and testing
json
{
  "regulation": "pci_dss",
  "requirements": {
    "cardholderDataProtection": true,
    "encryptionRequired": true,
    "accessControl": true,
    "regularTesting": true,
    "dataRetention": 365 // 1 year default
  }
}

Data Classification ​

Sensitivity Levels ​

LevelDescriptionExample DataRequirements
PublicInformation intended for public consumptionMarketing materials, public docsNo special protection
InternalInformation for internal business useInternal policies, proceduresAccess controls
ConfidentialSensitive business informationCustomer lists, financial dataEncryption, audit logs
RestrictedHighly sensitive, regulated dataPII, PHI, payment dataStrong encryption, logging

PII Detection ​

The system automatically detects various types of personally identifiable information:

PII TypeExamplesRegex PatternCompliance Impact
Emailuser@example.com[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}GDPR, CCPA
Phone+1-555-123-4567(\+?[1-9]\d{0,2})?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}GDPR, CCPA
SSN123-45-6789\b\d{3}-\d{2}-\d{4}\bHIPAA, SOX
Credit Card4111-1111-1111-1111\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\bPCI-DSS
Address123 Main St, City, ST 12345Complex pattern matchingGDPR, CCPA
NameJohn DoeNLP-based detectionGDPR, CCPA

Error Responses ​

400 Bad Request ​

json
{
  "error": "Missing required fields",
  "details": {
    "missingFields": ["regulations", "context.country"]
  }
}

403 Forbidden ​

json
{
  "error": "Compliance checking not available for your tier",
  "requiredTier": "standard",
  "currentTier": "free"
}

422 Unprocessable Entity ​

json
{
  "error": "Unsupported regulation",
  "supportedRegulations": ["gdpr", "ccpa", "hipaa", "sox", "pci_dss"],
  "provided": "invalid_regulation"
}

500 Internal Server Error ​

json
{
  "error": "Compliance check failed",
  "requestId": "string"
}

Example Usage ​

Basic Compliance Check (cURL) ​

bash
curl -X POST https://app.veriprompt.tech/api/v1/compliance/check \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <your-api-key>" \
  -d '{
    "requestId": "compliance_123",
    "data": {
      "prompt": "Please process this customer record: John Doe, email: john@example.com, phone: +1-555-123-4567"
    },
    "regulations": ["gdpr", "ccpa"],
    "context": {
      "userId": "user_456",
      "companyId": "company_789",
      "country": "US",
      "industry": "healthcare",
      "dataTypes": ["personal"]
    }
  }'

JavaScript Integration ​

javascript
class ComplianceChecker {
  constructor(apiKey, baseUrl = 'https://app.veriprompt.tech') {
    this.apiKey = apiKey;
    this.baseUrl = baseUrl;
  }
  
  async checkCompliance(data, regulations, context) {
    const response = await fetch(`${this.baseUrl}/api/v1/compliance/check`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.apiKey}`
      },
      body: JSON.stringify({
        requestId: `compliance_${Date.now()}`,
        data,
        regulations,
        context
      })
    });
    
    if (!response.ok) {
      throw new Error(`Compliance check failed: ${response.status}`);
    }
    
    return await response.json();
  }
  
  async validatePromptCompliance(prompt, userContext) {
    const result = await this.checkCompliance(
      { prompt },
      this.getRequiredRegulations(userContext.country, userContext.industry),
      userContext
    );
    
    if (!result.compliant) {
      const criticalViolations = result.violations.filter(
        v => v.severity === 'critical' || v.severity === 'high'
      );
      
      if (criticalViolations.length > 0) {
        throw new ComplianceViolationError(
          'Critical compliance violations detected',
          criticalViolations
        );
      }
    }
    
    return result;
  }
  
  getRequiredRegulations(country, industry) {
    const regulations = [];
    
    // Geographic regulations
    if (country === 'US') {
      regulations.push('ccpa');
    } else if (['DE', 'FR', 'GB', 'IT', 'ES'].includes(country)) {
      regulations.push('gdpr');
    }
    
    // Industry-specific regulations
    if (industry === 'healthcare') {
      regulations.push('hipaa');
    } else if (industry === 'finance') {
      regulations.push('sox');
      regulations.push('pci_dss');
    }
    
    return regulations;
  }
}

// Usage
const checker = new ComplianceChecker(apiKey);

try {
  const result = await checker.validatePromptCompliance(
    "Process payment for John Doe, card: 4111-1111-1111-1111",
    {
      userId: 'user_123',
      companyId: 'company_456',
      country: 'US',
      industry: 'finance'
    }
  );
  
  console.log('Compliance status:', result.compliant);
  if (result.dataClassification.piiDetected) {
    console.log('PII types found:', result.dataClassification.piiTypes);
  }
  
} catch (error) {
  console.error('Compliance error:', error.message);
}

Python Enterprise Integration ​

python
import requests
import json
from dataclasses import dataclass
from typing import List, Optional
from enum import Enum

class Regulation(Enum):
    GDPR = "gdpr"
    CCPA = "ccpa" 
    HIPAA = "hipaa"
    SOX = "sox"
    PCI_DSS = "pci_dss"

class Severity(Enum):
    CRITICAL = "critical"
    HIGH = "high"
    MEDIUM = "medium"
    LOW = "low"

@dataclass
class ComplianceViolation:
    regulation: str
    severity: Severity
    description: str
    remediation_required: bool
    suggested_action: str

class ComplianceAPI:
    def __init__(self, api_key: str, base_url: str = "https://app.veriprompt.tech"):
        self.api_key = api_key
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        })
    
    def check_compliance(
        self, 
        prompt: str, 
        regulations: List[Regulation],
        context: dict,
        response: Optional[str] = None
    ) -> dict:
        """Check compliance for prompt and optional response"""
        
        data = {
            'requestId': f'compliance_{int(time.time() * 1000)}',
            'data': {
                'prompt': prompt,
                'response': response
            },
            'regulations': [r.value for r in regulations],
            'context': context
        }
        
        response = self.session.post(
            f'{self.base_url}/api/v1/compliance/check',
            json=data
        )
        
        response.raise_for_status()
        return response.json()
    
    def validate_for_industry(self, prompt: str, industry: str, country: str = "US") -> dict:
        """Industry-specific compliance validation"""
        
        # Map industry to required regulations
        industry_regulations = {
            'healthcare': [Regulation.HIPAA, Regulation.GDPR if country in ['DE', 'FR'] else Regulation.CCPA],
            'finance': [Regulation.SOX, Regulation.PCI_DSS, Regulation.GDPR if country in ['DE', 'FR'] else Regulation.CCPA],
            'technology': [Regulation.GDPR if country in ['DE', 'FR'] else Regulation.CCPA],
            'retail': [Regulation.PCI_DSS, Regulation.GDPR if country in ['DE', 'FR'] else Regulation.CCPA]
        }
        
        regulations = industry_regulations.get(industry, [Regulation.CCPA])
        
        context = {
            'userId': 'system_check',
            'companyId': 'validation',
            'country': country,
            'industry': industry
        }
        
        return self.check_compliance(prompt, regulations, context)
    
    def get_violations_by_severity(self, compliance_result: dict, min_severity: Severity = Severity.MEDIUM) -> List[ComplianceViolation]:
        """Filter violations by minimum severity"""
        
        severity_order = {
            Severity.LOW: 0,
            Severity.MEDIUM: 1,
            Severity.HIGH: 2,
            Severity.CRITICAL: 3
        }
        
        min_level = severity_order[min_severity]
        
        violations = []
        for v in compliance_result.get('violations', []):
            severity = Severity(v['severity'])
            if severity_order[severity] >= min_level:
                violations.append(ComplianceViolation(
                    regulation=v['regulation'],
                    severity=severity,
                    description=v['description'],
                    remediation_required=v['remediationRequired'],
                    suggested_action=v['suggestedAction']
                ))
        
        return violations

# Usage example
compliance_api = ComplianceAPI(api_key)

# Healthcare compliance check
result = compliance_api.validate_for_industry(
    "Patient John Doe, DOB: 01/01/1990, condition: diabetes",
    industry="healthcare",
    country="US"
)

if not result['compliant']:
    critical_violations = compliance_api.get_violations_by_severity(
        result, 
        Severity.CRITICAL
    )
    
    for violation in critical_violations:
        print(f"❌ {violation.regulation}: {violation.description}")
        print(f"   Action: {violation.suggested_action}")

# Check if PII was detected
if result['dataClassification']['piiDetected']:
    pii_types = result['dataClassification']['piiTypes']
    print(f"🔒 PII detected: {', '.join(pii_types)}")
    print(f"🔐 Encryption required: {result['dataClassification']['encryptionRequired']}")

Remediation Actions ​

Common Violations and Fixes ​

ViolationRegulationRemediation
PII without consentGDPRObtain explicit consent before processing
Excessive data retentionCCPAImplement data retention policies
Unencrypted PHIHIPAAEnable encryption at rest and in transit
Missing audit logsSOXImplement comprehensive audit logging
Stored card numbersPCI-DSSTokenize or encrypt card data

Data Minimization ​

python
def minimize_data_for_compliance(prompt: str, detected_pii: List[str]) -> str:
    """Remove or mask PII from prompts when possible"""
    
    minimized = prompt
    
    # Replace specific PII with generic placeholders
    pii_replacements = {
        'email': '[EMAIL_ADDRESS]',
        'phone': '[PHONE_NUMBER]',
        'ssn': '[SSN]',
        'credit_card': '[PAYMENT_METHOD]',
        'address': '[ADDRESS]',
        'name': '[PERSON_NAME]'
    }
    
    for pii_type in detected_pii:
        if pii_type in pii_replacements:
            # Apply appropriate masking regex
            minimized = apply_pii_masking(minimized, pii_type, pii_replacements[pii_type])
    
    return minimized

Best Practices ​

Implementation Guidelines ​

  1. Check Early: Validate compliance before sending to AI providers
  2. Log Everything: Maintain comprehensive audit logs
  3. Minimize Data: Only process necessary personal information
  4. Encrypt Always: Use encryption for all sensitive data
  5. Obtain Consent: Ensure proper consent mechanisms

Data Handling ​

javascript
// Best practice: Check compliance before processing
async function processAIRequest(prompt, userContext) {
  // 1. Check compliance first
  const complianceResult = await complianceChecker.checkCompliance(
    { prompt },
    getRequiredRegulations(userContext),
    userContext
  );
  
  if (!complianceResult.compliant) {
    const criticalViolations = complianceResult.violations.filter(
      v => v.severity === 'critical'
    );
    
    if (criticalViolations.length > 0) {
      throw new Error('Cannot process: Critical compliance violations');
    }
  }
  
  // 2. Apply data minimization if needed
  let processedPrompt = prompt;
  if (complianceResult.dataClassification.piiDetected) {
    processedPrompt = minimizePersonalData(
      prompt, 
      complianceResult.dataClassification.piiTypes
    );
  }
  
  // 3. Process with compliant prompt
  const aiResponse = await sendToAI(processedPrompt);
  
  // 4. Log for audit trail
  await logComplianceAction({
    complianceCheck: complianceResult,
    originalPrompt: prompt,
    processedPrompt,
    response: aiResponse,
    timestamp: new Date().toISOString()
  });
  
  return aiResponse;
}

Monitoring and Alerting ​

python
def setup_compliance_monitoring():
    """Set up monitoring for compliance violations"""
    
    # Monitor for high-risk patterns
    high_risk_patterns = [
        r'\b\d{3}-\d{2}-\d{4}\b',  # SSN
        r'\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b',  # Credit card
        r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'  # Email
    ]
    
    # Set up alerts for violations
    compliance_alerts = {
        'critical_violations': {
            'threshold': 1,
            'action': 'immediate_notification'
        },
        'pii_detection_rate': {
            'threshold': 0.1,  # 10% of requests contain PII
            'action': 'daily_report'
        }
    }
    
    return {
        'patterns': high_risk_patterns,
        'alerts': compliance_alerts
    }

Changelog ​

Version 1.0.0 (Current) ​

  • Initial release
  • Support for 5 major regulations (GDPR, CCPA, HIPAA, SOX, PCI-DSS)
  • Automatic PII detection
  • Data classification and retention policies
  • Audit logging integration
  • Remediation recommendations