TraceKit API Integration
Complete guide for integrating TraceKit Context.io monitoring into your application using our REST API. Build custom integrations, create partner libraries, and automate onboarding flows.
Overview
The TraceKit API provides:
- Account Registration - Email-based verification with automatic provisioning
- Health Check Monitoring - Push-based heartbeats and pull-based endpoint checks
- Distributed Tracing - OTLP-compatible trace ingestion
- Metrics & Alerts - Real-time service metrics and alert management
- Webhook Management - Real-time event notifications
200,000 traces/month, email notifications, health monitoring, and full dashboard access.
Quick Start
1. Register Your Service
curl -X POST https://app.tracekit.dev/v1/integrate/register \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"service_name": "my-api",
"source": "your-framework",
"source_metadata": {
"version": "1.0.0",
"environment": "production"
}
}'source field identifies which partner or framework referred this signup (e.g., 'gemvc', 'laravel', 'nestjs'). This helps us track referrals and provide proper attribution to partners.Response:
{
"verification_required": true,
"session_id": "550e8400-e29b-41d4-a716-446655440000",
"message": "Verification code sent to [email protected]",
"expires_at": "2025-12-02T12:15:00Z"
}2. Verify with Email Code
Check your email for a 6-digit verification code, then:
curl -X POST https://app.tracekit.dev/v1/integrate/verify \
-H "Content-Type: application/json" \
-d '{
"session_id": "550e8400-e29b-41d4-a716-446655440000",
"code": "123456"
}'Response:
{
"api_key": "ctxio_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6",
"organization_id": "a8f3c9e1-4d2b-4a9c-8f7e-1b2c3d4e5f6a",
"service_name": "my-api",
"dashboard_url": "https://app.tracekit.dev"
}3. Test Your Integration
curl -X GET https://app.tracekit.dev/v1/integrate/status \
-H "X-API-Key: ctxio_your_api_key_here"Response:
{
"status": "active",
"integration": {
"service_name": "my-api",
"integration_type": "your-framework",
"source": "your-framework",
"status": "active",
"first_data_at": "2025-12-02T12:00:00Z",
"last_data_at": "2025-12-02T12:30:00Z"
}
}Authentication Flow
TraceKit uses email-based verification for account creation:
New vs Existing Users
New User:
- Creates new user account
- Generates random organization name (e.g., "Quantum Labs")
- Creates Hacker plan subscription (200k traces/month)
- Generates API key
- Auto-creates email notification channel
Existing User:
- Uses existing organization
- Generates new API key for same organization
- Maintains existing subscription
API Reference
Base URL
https://app.tracekit.devEndpoints
Register Service
POST /v1/integrate/register Content-Type: application/jsonRequest Body:
{
"email": "string (required, email format)",
"service_name": "string (required)",
"organization_name": "string (optional, auto-generated if empty)",
"source": "string (partner/framework code for attribution, e.g., 'gemvc', 'laravel', defaults to 'cli')",
"source_metadata": {
"version": "string",
"environment": "string",
"custom_field": "any"
}
}Verify Code
POST /v1/integrate/verify Content-Type: application/jsonRequest Body:
{
"session_id": "uuid (required)",
"code": "string (required, 6 digits)"
}Check Status
GET /v1/integrate/status X-API-Key: ctxio_your_api_keyHealth Check Monitoring
Push-Based Heartbeat
Send heartbeats every 60 seconds to indicate service is healthy.
POST /v1/health/heartbeat
X-API-Key: ctxio_your_api_key
Content-Type: application/json
{
"service_name": "my-api",
"status": "healthy",
"metadata": {
"memory_usage": 67108864,
"cpu_usage": 45.5,
"active_connections": 23
}
}Response:
{
"success": true,
"message": "Heartbeat received",
"next_expected_at": "ISO8601 timestamp"
}List Health Checks
GET /api/health-checks X-API-Key: ctxio_your_api_keySending Traces
TraceKit supports OTLP (OpenTelemetry Protocol) for trace ingestion.
OTLP Endpoint
POST /v1/traces Content-Type: application/json X-API-Key: ctxio_your_api_keyUsing OpenTelemetry SDK
PHP Example:
<?php
use OpenTelemetry\SDK\Trace\TracerProviderFactory;
use OpenTelemetry\Contrib\Otlp\SpanExporter;
$exporter = new SpanExporter(
'https://app.tracekit.dev/v1/traces',
['X-API-Key' => $_ENV['TRACEKIT_API_KEY']]
);
$tracerProvider = (new TracerProviderFactory())->create($exporter);
$tracer = $tracerProvider->getTracer('my-api');
// Create a span
$span = $tracer->spanBuilder('user.login')->startSpan();
// ... your code ...
$span->end();Node.js Example:
const { NodeSDK } = require('@opentelemetry/sdk-node');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http');
const exporter = new OTLPTraceExporter({
url: process.env.TRACEKIT_BASE_URL + '/v1/traces',
headers: {
'X-API-Key': process.env.TRACEKIT_API_KEY
}
});
const sdk = new NodeSDK({
traceExporter: exporter,
serviceName: process.env.TRACEKIT_SERVICE_NAME
});
sdk.start();Metrics & Alerts
Get Service Metrics
GET /api/metrics/services/{service_name}?window=15m
X-API-Key: ctxio_your_api_keyQuery Parameters:
window: 5m, 15m, 1h, 6h, 24h (default: 15m)
Response:
{
"success": true,
"service": "my-api",
"window": "15m",
"metrics": {
"p50_latency_ms": 45,
"p95_latency_ms": 120,
"p99_latency_ms": 250,
"error_rate": 2.5,
"success_rate": 97.5,
"throughput": 15420
},
"timestamp": "ISO8601 timestamp"
}Get Alerts Summary
GET /v1/alerts/summary X-API-Key: ctxio_your_api_keyGet Active Alerts
GET /v1/alerts/active?limit=50 X-API-Key: ctxio_your_api_keyWebhook Management
TraceKit webhooks deliver real-time event notifications to your application.
Create Webhook
POST /v1/webhooks
X-API-Key: ctxio_your_api_key
Content-Type: application/json
{
"name": "Production Alerts",
"url": "https://your-app.com/webhook",
"events": [
"health_check.failed",
"health_check.recovered",
"alert.triggered"
],
"enabled": true
}Response:
{
"success": true,
"webhook": {
"id": "5530d278-beb2-4c13-9e20-f610832d2962",
"organization_id": "59bc99cd-f9e6-47a8-babc-04a55fdff340",
"name": "Production Alerts",
"url": "https://your-app.com/webhook",
"secret": "whsec_7k3n9m2p4q8r1s5t6v9w0x2y4z",
"events": [
"health_check.failed",
"health_check.recovered",
"alert.triggered"
],
"enabled": true,
"created_at": "2025-12-02T20:30:00Z",
"updated_at": "2025-12-02T20:30:00Z"
}
}Webhook Events
TraceKit sends webhooks for the following event types:
| Event Type | Description | Trigger Condition |
|---|---|---|
health_check.failed | Health check failed | Service health check fails (timeout, wrong status, connection error) |
health_check.recovered | Health check recovered | Previously failing health check passes |
alert.triggered | Alert rule triggered | Alert rule threshold exceeded |
alert.resolved | Alert resolved | Active alert condition resolves |
trace.error | Trace contains error | Trace with error status received |
anomaly.detected | Anomaly detected | Unusual behavior detected by anomaly detection |
Webhook Payload Structure
All webhooks follow this standard format:
{
"event": "health_check.failed",
"event_id": "854eb8d7-7cdf-4e6a-832f-6319bd46aa2d",
"webhook_id": "5530d278-beb2-4c13-9e20-f610832d2962",
"organization_id": "59bc99cd-f9e6-47a8-babc-04a55fdff340",
"timestamp": "2025-12-02T20:40:46Z",
"data": {
"...event-specific data..."
}
}Webhook Security (HMAC Verification)
Every webhook includes an X-Webhook-Signature header containing an HMAC-SHA256 signature:
Node.js/Express Example:
const crypto = require('crypto');
app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
const signature = req.headers['x-webhook-signature'];
const secret = process.env.TRACEKIT_WEBHOOK_SECRET;
// Calculate expected signature
const hmac = crypto.createHmac('sha256', secret);
hmac.update(req.body); // Use raw body
const expected = 'sha256=' + hmac.digest('hex');
// Constant-time comparison
if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
return res.status(401).json({ error: 'Invalid signature' });
}
// Signature is valid - process webhook
const payload = JSON.parse(req.body);
console.log('Received event:', payload.event);
res.json({ status: 'success' });
});PHP/Laravel Example:
<?php
class WebhookController extends Controller
{
public function handle(Request $request)
{
// Get signature from header
$signature = $request->header('X-Webhook-Signature');
$secret = env('TRACEKIT_WEBHOOK_SECRET');
// Calculate expected signature
$payload = $request->getContent();
$expectedSignature = 'sha256=' . hash_hmac('sha256', $payload, $secret);
// Constant-time comparison
if (!hash_equals($expectedSignature, $signature)) {
return response()->json(['error' => 'Invalid signature'], 401);
}
// Signature is valid - process webhook
$data = $request->json()->all();
Log::info('Webhook received', ['event' => $data['event']]);
return response()->json(['status' => 'success']);
}
}Subscription & Billing API
Get Current Subscription
GET /v1/billing/subscription X-API-Key: ctxio_xxxResponse:
{
"plan": "starter",
"status": "active",
"usage": {
"traces_used": 45230,
"trace_limit": 1000000,
"percentage": 4.5,
"bytes_used": 0,
"bytes_limit": 0
},
"current_period_end": "2025-12-20T00:00:00Z"
}List Available Plans
GET /v1/billing/plansCreate Checkout Session
This endpoint can be used from any authenticated context (web app, mobile app, custom integrations).
POST /v1/billing/create-checkout-session
X-API-Key: ctxio_xxx
Content-Type: application/json
{
"plan_id": "starter",
"billing_interval": "monthly",
"source": "dashboard",
"success_url": "https://yourapp.com/upgrade/success?session_id={CHECKOUT_SESSION_ID}",
"cancel_url": "https://yourapp.com/upgrade?source=dashboard"
}Response:
{
"checkout_url": "https://checkout.stripe.com/c/pay/cs_test_...",
"session_id": "cs_test_..."
}Best Practices
1. Security
- Use environment variables (
.envfiles) - Never commit API keys to version control
- Rotate keys periodically
2. Error Handling
Graceful degradation:
try {
$tracekit->sendHeartbeat();
} catch (\Exception $e) {
// Log error but don't fail the application
error_log("TraceKit heartbeat failed: " . $e->getMessage());
}3. Performance
Send heartbeats asynchronously:
// Non-blocking heartbeat
register_shutdown_function(function() use ($tracekit) {
$tracekit->sendHeartbeat();
});Rate limit heartbeats (max once per minute):
$tracekit->sendHeartbeat(); // Auto rate-limitedTroubleshooting
Common Issues
1. "Invalid API key"
Cause: API key is incorrect or revoked
Solution:
- Verify API key is correct
- Check if key was revoked in dashboard
- Generate a new API key if needed
2. "Verification code expired"
Cause: 15-minute verification window expired
Solution:
- Start registration process again
- Verify code within 15 minutes
3. "Service not sending heartbeats"
Cause: Heartbeat interval exceeded
Solution:
- Ensure heartbeat is sent every 60 seconds
- Check network connectivity
- Review error logs for failed requests