<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: building-security-api-integrations
description: >-
  Build resilient API integrations between security tools using rate-limited
  clients, retry logic, credential rotation, webhook receivers, and
  normalized data exchange with authentication and error handling patterns.
domain: cybersecurity
subdomain: security-operations-automation
tags:
  - api
  - integration
  - webhook
  - rate-limiting
  - oauth
  - rest
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: []
---

# Building Security API Integrations

## Overview

Security operations depend on tool interoperability — SIEM to SOAR, EDR to
ticketing, TI feeds to firewalls. This technique covers building production-
grade API integrations with proper authentication, rate limiting, retry
logic, circuit breakers, and normalized data exchange between security
platforms.

Mode: `[MODE: ARCHITECT]` — Integration architecture and resilience.

## Prerequisites

| Requirement | Details |
|---|---|
| Python 3.10+ with `requests`, `urllib3` | Required |
| API credentials for target platforms | Required |
| Webhook endpoint (Flask/FastAPI) for event reception | Required |
| Secret management (Vault, AWS Secrets Manager) | Required |

## Key Concepts

### Resilient API Client

```python
import time
import logging
from typing import Any

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

logger = logging.getLogger("security.api")


def build_session(
    max_retries: int = 3,
    backoff_factor: float = 0.5,
    timeout: int = 30,
) -> requests.Session:
    """Build a requests session with retry and backoff."""
    session = requests.Session()
    retry_strategy = Retry(
        total=max_retries,
        backoff_factor=backoff_factor,
        status_forcelist=[429, 500, 502, 503, 504],
        allowed_methods=["GET", "POST", "PUT"],
    )
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount("https://", adapter)
    session.mount("http://", adapter)
    return session
```

### Rate-Limited Request Handler

```python
class RateLimitedClient:
    """API client with rate limit awareness."""

    def __init__(self, base_url: str, api_key: str, requests_per_minute: int = 60):
        self.base_url = base_url.rstrip("/")
        self.session = build_session()
        self.session.headers["Authorization"] = f"Bearer {api_key}"
        self.min_interval = 60.0 / requests_per_minute
        self._last_request: float = 0.0

    def request(self, method: str, path: str, **kwargs: Any) -> dict[str, Any]:
        """Make a rate-limited API request."""
        elapsed = time.time() - self._last_request
        if elapsed < self.min_interval:
            time.sleep(self.min_interval - elapsed)

        url = f"{self.base_url}{path}"
        resp = self.session.request(method, url, timeout=30, **kwargs)
        self._last_request = time.time()

        if resp.status_code == 429:
            retry_after = int(resp.headers.get("Retry-After", 60))
            logger.warning("Rate limited, waiting %ds", retry_after)
            time.sleep(retry_after)
            return self.request(method, path, **kwargs)

        resp.raise_for_status()
        return resp.json()
```

### Webhook Receiver Pattern

```python
import hashlib
import hmac


def verify_webhook_signature(
    payload: bytes,
    signature: str,
    secret: str,
    algorithm: str = "sha256",
) -> bool:
    """Verify HMAC signature on incoming webhook."""
    expected = hmac.new(
        secret.encode(), payload, getattr(hashlib, algorithm)
    ).hexdigest()
    return hmac.compare_digest(expected, signature)
```

## Workflow

### Step 1: Test API Connectivity

```bash
node scripts/agent.js --action test-connection --platform crowdstrike
```

### Step 2: Sync Indicators

```bash
node scripts/agent.js --action sync-indicators --source misp --dest siem
```

### Step 3: Validate Webhook

```bash
node scripts/agent.js --action validate-webhook --secret mykey
```

## Verification

- [ ] API client retries on transient failures with exponential backoff
- [ ] Rate limits respected — no 429 errors in steady state
- [ ] Webhook signatures validated before processing
- [ ] Credentials never logged or exposed in error messages

## References

- [OWASP API Security Top 10](https://owasp.org/API-Security/)
- [RFC 6750 — Bearer Token Usage](https://www.rfc-editor.org/rfc/rfc6750)
- [CrowdStrike Falcon API](https://falcon.crowdstrike.com/documentation/)
