Skip to main content
Article
fraud-detectionrisk-managementapi-integrationpythonreal-timemachine-learningfinancepayments

Detect Fraud in Real-Time with Featurespace's Agent

Use the Featurespace Fraud Detection Agent to score financial transactions in real-time. Send transaction data via a REST API to get an ML-powered risk score, and provide feedback to help the adaptive models learn and improve over time.

intermediate30 min4 steps
The play
  1. Structure a Transaction Event
    The Fraud Detection Agent analyzes rich event data. Structure your transaction as a JSON object. Include customer, transaction, merchant, and device details to enable the agent's behavioral and biometric analysis capabilities.
  2. Request a Real-Time Risk Score
    Send the transaction event to the Fraud Detection Agent's scoring endpoint via an HTTP POST request. The agent provides a synchronous, sub-50ms response, allowing you to make an immediate authorization decision.
  3. Interpret the Scoring Decision
    The response contains a risk score and often a recommended action. A higher score indicates higher risk. Use this data to build your authorization logic: approve low-risk transactions, decline high-risk ones, or send mid-range ones for manual review.
  4. Submit Feedback for Adaptive Learning
    To leverage the agent's adaptive feedback loops, inform it of the final outcome of a transaction, especially confirmed fraud. This allows the underlying machine learning models to continuously learn and improve their accuracy.
Starter code
import requests
import json
import os
import uuid
from datetime import datetime, timezone

# --- Configuration ---
# Best practice: Use environment variables for sensitive data
API_BASE_URL = os.getenv("FEATURESPACE_API_URL", "https://api.example.featurespace.com")
API_KEY = os.getenv("FEATURESPACE_API_KEY", "your-api-key-here")

# --- API Client Functions ---
def get_fs_headers():
    """Constructs standard headers for Featurespace API calls."""
    return {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }

def score_transaction(event_payload):
    """Sends a transaction to the Fraud Detection Agent for scoring."""
    try:
        response = requests.post(
            f"{API_BASE_URL}/api/v1/events/score",
            headers=get_fs_headers(),
            json=event_payload,
            timeout=1 # Set a timeout for real-time decisioning
        )
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error scoring transaction: {e}")
        return None

def submit_feedback(feedback_payload):
    """Sends feedback about a transaction to the agent."""
    try:
        response = requests.post(
            f"{API_BASE_URL}/api/v1/events/feedback",
            headers=get_fs_headers(),
            json=feedback_payload,
            timeout=5
        )
        response.raise_for_status()
        return response.status_code
    except requests.exceptions.RequestException as e:
        print(f"Error submitting feedback: {e}")
        return None

# --- Main Execution Logic ---
if __name__ == "__main__":
    # 1. Create a sample transaction event
    event_id = f"evt_{uuid.uuid4()}"
    transaction_to_score = {
        "eventId": event_id,
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "eventType": "card_payment",
        "customer": {"id": "cust_abc123", "ipAddress": "203.0.113.54"},
        "transaction": {"amount": 125.50, "currency": "USD"},
        "merchant": {"id": "merch_zxy987"}
    }

    # 2. Get a real-time risk score
    print(f"Scoring transaction {event_id}...")
    # In a real system, you would get a real response. We will simulate one.
    # risk_data = score_transaction(transaction_to_score)
    risk_data = {'eventId': event_id, 'riskScore': 850, 'riskLevel': 'HIGH'} # Simulated response

    if risk_data:
        # 3. Interpret the score and make a decision
        risk_score = risk_data.get('riskScore', 0)
        decision = "APPROVE"
        if risk_score > 800:
            decision = "DECLINE"
        elif risk_score > 500:
            decision = "REVIEW"
        
        print(f"-> Score: {risk_score}, Decision: {decision}")

        # 4. (Simulated) After investigation, submit feedback
        if decision == "DECLINE":
            print(f"Submitting fraud feedback for {event_id}...")
            feedback = {
                "eventId": event_id,
                "label": "FRAUD",
                "timestamp": datetime.now(timezone.utc).isoformat()
            }
            # status = submit_feedback(feedback)
            status = 202 # Simulated response
            if status:
                print(f"-> Feedback submission status: {status}")
Detect Fraud in Real-Time with Featurespace's Agent — Action Pack