ModRelay Documentation
Everything you need to integrate ModRelay's API relay service into your applications. From quick setup to advanced configuration.
API Reference
Base URL
https://api.modrelay.net
Authentication
All requests require a bearer token in the Authorization header:
Authorization: Bearer YOUR_API_TOKEN
Request Headers
X-Relay-Target
Target upstream URL (required)
X-Relay-Cache
Cache duration in seconds (optional)
X-Relay-Region
Preferred region (us-east, eu-west, ap-south)
SDK & Library Examples
React/Next.js
Custom Hook Implementation
import { useState, useEffect } from 'react'; const useModRelay = (baseURL = 'https://api.modrelay.net') => { const [token, setToken] = useState(null); const relay = async (endpoint, options = {}) => { const headers = { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', ...options.headers }; const response = await fetch(`${baseURL}${endpoint}`, { ...options, headers }); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } return response.json(); }; return { relay, setToken }; };
Express.js Middleware
Auto-Relay Middleware
const express = require('express'); const axios = require('axios'); const modRelayMiddleware = (config) => { return async (req, res, next) => { try { const relayHeaders = { 'Authorization': `Bearer ${config.apiToken}`, 'X-Relay-Target': config.targetUrl, 'X-Relay-Cache': config.cacheTime || '300' }; const response = await axios({ method: req.method, url: `https://api.modrelay.net${req.path}`, headers: { ...relayHeaders, ...req.headers }, data: req.body }); res.status(response.status).json(response.data); } catch (error) { next(error); } }; };
Python FastAPI
Async Client Implementation
import httpx from fastapi import FastAPI, HTTPException from typing import Optional class ModRelayClient: def __init__(self, api_token: str): self.base_url = "https://api.modrelay.net" self.headers = { "Authorization": f"Bearer {api_token}", "Content-Type": "application/json" } async def relay_request(self, endpoint: str, method: str = "GET", target_url: Optional[str] = None, cache_time: int = 300, data: dict = None): headers = self.headers.copy() if target_url: headers["X-Relay-Target"] = target_url headers["X-Relay-Cache"] = str(cache_time) async with httpx.AsyncClient() as client: response = await client.request( method, f"{self.base_url}{endpoint}", headers=headers, json=data ) return response.json()
Go with Gin Framework
Relay Client Package
package main import ( "bytes" "encoding/json" "fmt" "net/http" "strconv" "github.com/gin-gonic/gin" ) type ModRelayClient struct { BaseURL string APIToken string Client *http.Client } func NewModRelayClient(token string) *ModRelayClient { return &ModRelayClient{ BaseURL: "https://api.modrelay.net", APIToken: token, Client: &http.Client{}, } } func (c *ModRelayClient) RelayRequest(method, endpoint, targetURL string, cacheTime int, data interface{}) (*http.Response, error) { var body *bytes.Buffer if data != nil { jsonData, err := json.Marshal(data) if err != nil { return nil, err } body = bytes.NewBuffer(jsonData) } else { body = bytes.NewBuffer(nil) } req, err := http.NewRequest(method, fmt.Sprintf("%s%s", c.BaseURL, endpoint), body) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+c.APIToken) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Relay-Target", targetURL) req.Header.Set("X-Relay-Cache", strconv.Itoa(cacheTime)) return c.Client.Do(req) }
API Endpoints Reference
POST /relay
PrimaryMain relay endpoint for proxying requests to upstream services.
Request
// Headers Authorization: Bearer YOUR_TOKEN X-Relay-Target: https://api.example.com X-Relay-Cache: 300 Content-Type: application/json // Body { "method": "GET", "path": "/users/123", "headers": { "User-Agent": "MyApp/1.0" } }
Response
{
"status": 200,
"headers": {
"content-type": "application/json"
},
"data": {
"id": 123,
"name": "John Doe",
"email": "john@example.com"
},
"meta": {
"cached": false,
"latency_ms": 245,
"region": "us-east"
}
}
GET /health
PublicCheck ModRelay service health and status.
Request
GET https://api.modrelay.net/health
Response
{
"status": "healthy",
"version": "2.1.0",
"regions": {
"us-east": "online",
"us-west": "online",
"eu-west": "online",
"ap-south": "online"
},
"timestamp": "2024-01-15T10:30:00Z"
}
GET /analytics
AuthenticatedRetrieve usage analytics and metrics for your account.
Request
// Headers Authorization: Bearer YOUR_TOKEN // Query Parameters ?start=2024-01-01&end=2024-01-31&granularity=day
Response
{
"period": {
"start": "2024-01-01T00:00:00Z",
"end": "2024-01-31T23:59:59Z"
},
"metrics": {
"total_requests": 45690,
"cache_hit_rate": 0.73,
"avg_latency_ms": 187,
"error_rate": 0.02
},
"daily_breakdown": [...]
}
Configuration
Advanced Caching Configuration
Fine-tune caching behavior with advanced headers and policies:
Basic Cache Control
// Cache for 5 minutes 'X-Relay-Cache': '300' // No caching 'X-Relay-Cache': '0' // Cache with conditional refresh 'X-Relay-Cache': '600' 'X-Relay-Cache-Refresh': 'conditional'
Cache Invalidation
// Invalidate specific cache patterns POST /cache/invalidate { "patterns": ["/api/users/*", "/api/products/123"], "tags": ["user-data", "inventory"] }
Webhook Configuration
Configure webhooks for real-time notifications and monitoring:
Webhook Setup
POST /webhooks { "url": "https://your-app.com/webhooks/modrelay", "events": [ "request.completed", "request.failed", "rate_limit.exceeded", "cache.miss" ], "filters": { "paths": ["/api/critical/*"], "status_codes": [4xx, 5xx] } }
Webhook Payload Example
{
"event": "request.failed",
"timestamp": "2024-01-15T10:30:00Z",
"data": {
"request_id": "req_abc123",
"method": "POST",
"path": "/api/critical/payment",
"status_code": 504,
"error": "Gateway timeout",
"target_url": "https://api.payment-provider.com",
"latency_ms": 30000,
"region": "us-east"
}
}
Circuit Breaker & Retry Policies
Configure automatic failure handling and service protection:
// Headers for advanced retry configuration 'X-Relay-Retry-Count': '3' 'X-Relay-Retry-Backoff': 'exponential' 'X-Relay-Circuit-Breaker': 'enabled' 'X-Relay-Timeout': '10000' // Circuit breaker thresholds 'X-Relay-Failure-Threshold': '5' 'X-Relay-Recovery-Timeout': '30'
Load Balancing & Routing
Configure intelligent request routing across multiple upstream services:
// Multiple target configuration 'X-Relay-Targets': 'https://api1.example.com,https://api2.example.com' 'X-Relay-Load-Balance': 'round-robin' // Weighted routing 'X-Relay-Targets': 'https://api1.example.com:70,https://api2.example.com:30' 'X-Relay-Load-Balance': 'weighted' // Health check configuration 'X-Relay-Health-Check': '/health' 'X-Relay-Health-Interval': '30'
Rate Limiting
Plan Limits
Custom Rate Limiting
// Per-path limits 'X-Relay-Rate-Limit': '100/min' 'X-Relay-Rate-Key': 'user_id' // Burst handling 'X-Relay-Burst-Limit': '150'
Monitoring & Analytics
Real-time Dashboard
Monitor your API relay performance with comprehensive metrics and visualizations.
Request Volume (24h)
Custom Metrics & Alerts
Set up custom metrics tracking and alerting policies for your specific use cases.
Metric Configuration
POST /metrics/custom { "name": "api_performance", "type": "histogram", "dimensions": ["endpoint", "region"], "aggregation": "p95", "filters": { "status_code": [200, 201] } }
Alert Setup
POST /alerts { "name": "High Latency Alert", "condition": "avg_latency > 500", "window": "5m", "channels": [ "slack://ops-channel", "email://ops@company.com" ], "severity": "warning" }
Logging & Distributed Tracing
Comprehensive request logging and distributed tracing for debugging and monitoring.
Log Streaming
# Stream logs in real-time curl -N -H "Authorization: Bearer YOUR_TOKEN" \ https://api.modrelay.net/logs/stream?level=info # Filter by endpoint or status ?path=/api/users/*&status=4xx,5xx
Trace Context
// Automatic trace propagation 'X-Trace-Id': 'abc123-def456' 'X-Parent-Span-Id': 'span789' // OpenTelemetry integration 'X-Relay-Tracing': 'opentelemetry' 'X-Relay-Sampling-Rate': '0.1'
Security & Authentication
API Key Management
Secure API key creation, rotation, and scope management.
Key Creation with Scopes
POST /api-keys { "name": "Production API Key", "scopes": ["relay:read", "relay:write", "analytics:read"], "rate_limit": 1000, "ip_whitelist": ["192.168.1.0/24", "10.0.0.0/16"], "expires_at": "2024-12-31T23:59:59Z" }
Key Rotation
POST /api-keys/{key_id}/rotate { "transition_period": "7d", "notify_webhook": true }
OAuth 2.0 Integration
Secure OAuth 2.0 authentication flow for client applications.
Authorization Flow
# 1. Authorization Request https://api.modrelay.net/oauth/authorize? client_id=your_client_id& redirect_uri=https://app.com/callback& response_type=code& scope=relay:read+analytics:read # 2. Token Exchange POST /oauth/token { "grant_type": "authorization_code", "code": "auth_code_here", "client_id": "your_client_id", "client_secret": "your_secret" }
Token Response
{
"access_token": "eyJhbGciOiJIUzI1...",
"refresh_token": "eyJhbGciOiJIUzI1...",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "relay:read analytics:read"
}
Request Signing & Verification
Enhanced security with HMAC request signing and webhook verification.
HMAC Signing
const crypto = require('crypto'); function signRequest(secret, method, path, body, timestamp) { const payload = `${method}|${path}|${body}|${timestamp}`; const signature = crypto .createHmac('sha256', secret) .update(payload) .digest('hex'); return `sha256=${signature}`; } // Usage in headers 'X-Relay-Signature': signRequest(secret, 'POST', '/relay', body, Date.now()) 'X-Relay-Timestamp': Date.now().toString()
Webhook Verification
function verifyWebhook(payload, signature, secret) { const expectedSignature = crypto .createHmac('sha256', secret) .update(payload, 'utf8') .digest('hex'); return crypto.timingSafeEqual( Buffer.from(signature, 'hex'), Buffer.from(expectedSignature, 'hex') ); }
Compliance & Data Protection
Standards
- SOC 2 Type II Certified
- GDPR Compliant
- CCPA Compliant
- HIPAA Ready (BAA available)
Data Handling
- • End-to-end encryption in transit (TLS 1.3)
- • Data encryption at rest (AES-256)
- • No persistent storage of request payloads
- • Automatic PII detection and masking
- • Configurable data retention policies
- • Regular security audits and penetration testing
Framework Integrations
Mobile Development
React Native
import AsyncStorage from '@react-native-async-storage/async-storage'; class ModRelayClient { constructor(apiToken) { this.baseURL = 'https://api.modrelay.net'; this.token = apiToken; } async request(endpoint, options = {}) { const response = await fetch(`${this.baseURL}${endpoint}`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.token}`, 'Content-Type': 'application/json', 'X-Relay-Target': options.targetUrl }, body: JSON.stringify(options.data) }); return response.json(); } }
iOS (Swift)
import Foundation class ModRelayClient { private let baseURL = "https://api.modrelay.net" private let apiToken: String init(apiToken: String) { self.apiToken = apiToken } func relay(endpoint: String, targetURL: String, completion: @escaping (Result<Data, Error>) -> Void) { var request = URLRequest(url: URL(string: "\(baseURL)\(endpoint)")!) request.httpMethod = "POST" request.setValue("Bearer \(apiToken)", forHTTPHeaderField: "Authorization") request.setValue(targetURL, forHTTPHeaderField: "X-Relay-Target") URLSession.shared.dataTask(with: request, completionHandler: completion).resume() } }
Serverless Platform Integrations
Vercel Edge Functions
import { NextRequest, NextResponse } from 'next/server'; export async function middleware(request: NextRequest) { if (request.nextUrl.pathname.startsWith('/api/external')) { const response = await fetch('https://api.modrelay.net/relay', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.MODRELAY_TOKEN}`, 'X-Relay-Target': 'https://external-api.com', 'X-Relay-Cache': '300' }, body: JSON.stringify({ method: request.method, path: request.nextUrl.pathname.replace('/api/external', '') }) }); return NextResponse.json(await response.json()); } }
AWS Lambda
const AWS = require('aws-sdk'); const axios = require('axios'); exports.handler = async (event, context) => { const ssm = new AWS.SSM(); const apiToken = await ssm.getParameter({ Name: '/modrelay/api-token', WithDecryption: true }).promise(); try { const response = await axios.post('https://api.modrelay.net/relay', { method: event.httpMethod, path: event.path, headers: event.headers, body: event.body }, { headers: { 'Authorization': `Bearer ${apiToken.Parameter.Value}`, 'X-Relay-Target': process.env.TARGET_API_URL } }); return { statusCode: 200, body: JSON.stringify(response.data) }; } catch (error) { return { statusCode: 500, body: JSON.stringify({ error: error.message }) }; } };
Infrastructure as Code
Terraform Provider
terraform { required_providers { modrelay = { source = "modrelay/modrelay" version = "~> 1.0" } } } provider "modrelay" { api_token = var.modrelay_token } resource "modrelay_relay_config" "api_proxy" { name = "production-api" target_url = "https://api.example.com" cache_ttl = 300 retry_count = 3 rate_limit { requests_per_minute = 1000 burst_limit = 1200 } }
Docker Integration
# Dockerfile FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm install COPY . . ENV MODRELAY_BASE_URL=https://api.modrelay.net ENV MODRELAY_TOKEN=${MODRELAY_TOKEN} EXPOSE 3000 CMD ["npm", "start"] # docker-compose.yml version: '3.8' services: app: build: . environment: - MODRELAY_TOKEN=${MODRELAY_TOKEN} - TARGET_API_URL=https://api.example.com ports: - "3000:3000"
Performance Optimization
Advanced Caching Strategies
Optimize performance with intelligent caching patterns and strategies.
Smart Cache Keys
// Dynamic cache keys based on user context 'X-Relay-Cache-Key': 'user_${user_id}_${endpoint}' // Geographic caching 'X-Relay-Cache-Key': '${region}_${path}_${query_hash}' // Version-aware caching 'X-Relay-Cache-Key': 'v${api_version}_${endpoint}' 'X-Relay-Cache-Tags': 'api_v2,user_data'
Cache Warming
POST /cache/warm { "endpoints": [ "/api/popular-products", "/api/user-preferences/*" ], "schedule": "0 */6 * * *", "regions": ["us-east", "eu-west"], "priority": "high" }
Connection Optimization
Maximize throughput with advanced connection management.
Connection Pooling
// Global pool configuration 'X-Relay-Pool-Size': '100' 'X-Relay-Pool-Timeout': '30000' 'X-Relay-Keep-Alive': 'true' // Per-target configuration 'X-Relay-Target-Pool': 'api.example.com:50' 'X-Relay-Max-Connections': '20'
Request Batching
POST /batch { "requests": [ { "id": "req1", "method": "GET", "path": "/users/123" }, { "id": "req2", "method": "GET", "path": "/orders/456" } ], "parallel": true, "timeout": 5000 }
Performance Benchmarks
Real-world performance metrics across different scenarios and regions.
Performance Best Practices
✅ Do
- • Use appropriate cache TTLs for your data
- • Implement client-side connection pooling
- • Leverage batch requests for multiple operations
- • Set up cache warming for critical endpoints
- • Use regional targeting for better latency
- • Implement proper retry logic with exponential backoff
- • Monitor cache hit rates and optimize cache keys
❌ Don't
- • Cache sensitive or frequently changing data
- • Make synchronous calls without timeouts
- • Ignore rate limiting headers
- • Use overly complex cache keys
- • Skip request/response compression
- • Rely on default connection settings
- • Forget to handle partial batch failures
Enterprise Features
On-Premises Deployment
Deploy ModRelay within your own infrastructure for maximum control and compliance.
Kubernetes Deployment
apiVersion: apps/v1 kind: Deployment metadata: name: modrelay-enterprise spec: replicas: 3 selector: matchLabels: app: modrelay template: spec: containers: - name: modrelay image: modrelay/enterprise:latest env: - name: LICENSE_KEY valueFrom: secretKeyRef: name: modrelay-license key: key
High Availability Setup
Enterprise Security
Advanced security features for enterprise environments.
SSO Integration
Advanced Audit Logging
{
"timestamp": "2024-01-15T10:30:00Z",
"event": "api_key_created",
"actor": {
"user_id": "user_123",
"ip_address": "10.0.0.1",
"user_agent": "ModRelay-CLI/1.0"
},
"resource": {
"type": "api_key",
"id": "key_456",
"scopes": ["relay:read"]
},
"metadata": {
"organization": "acme-corp",
"compliance_level": "high"
}
}
Custom SLAs & Support
Standard
Premium
Mission Critical
Troubleshooting
HTTP Status Code Reference
Complete reference of status codes returned by ModRelay and their meanings.
2xx Success
200 OK
Request successful, data returned
202 Accepted
Request accepted for async processing
204 No Content
Successful request with no response body
4xx Client Errors
400 Bad Request
Invalid request format or parameters
401 Unauthorized
Missing or invalid authentication
403 Forbidden
Valid auth but insufficient permissions
429 Too Many Requests
Rate limit exceeded
5xx Server Errors
500 Internal Server Error
ModRelay service error
502 Bad Gateway
Upstream service unreachable
503 Service Unavailable
ModRelay temporarily unavailable
504 Gateway Timeout
Upstream service timeout
Custom ModRelay Codes
599 Network Timeout
Custom timeout for network issues
Common Issues & Solutions
Authentication Failures
Issue: 401 Unauthorized responses
Cause: Invalid or missing API token
Solution:
// Check token format
Authorization: Bearer mod_1234567890abcdef
// Verify token hasn't expired
curl -H "Authorization: Bearer YOUR_TOKEN" https://api.modrelay.net/auth/verify
Rate Limiting
Issue: 429 Too Many Requests
Cause: Exceeded rate limits
Solution:
// Check rate limit headers
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1640995200
// Implement exponential backoff
const delay = Math.pow(2, retryCount) * 1000;
Connection Issues
Issue: Intermittent 502/504 errors
Cause: Upstream service issues
Solution:
// Enable circuit breaker
'X-Relay-Circuit-Breaker': 'enabled'
'X-Relay-Failure-Threshold': '3'
// Configure retries
'X-Relay-Retry-Count': '3'
'X-Relay-Retry-Backoff': 'exponential'
Cache Issues
Issue: Stale data being returned
Cause: Aggressive caching settings
Solution:
// Force cache refresh
'X-Relay-Cache': '0'
'X-Relay-Cache-Bust': 'true'
// Invalidate specific cache
POST /cache/invalidate
{ "patterns": ["/api/users/*"] }
Debug Tools & Techniques
Request Tracing
Enable detailed request tracing for debugging:
// Add debug headers to your requests 'X-Relay-Debug': 'true' 'X-Relay-Trace-Level': 'verbose' // Response will include debug information { "data": { ... }, "debug": { "request_id": "req_abc123", "trace_id": "trace_def456", "upstream_latency_ms": 245, "cache_status": "miss", "route_taken": "us-east -> target-api" } }
Health Check Diagnostics
# Check specific endpoint health curl -H "Authorization: Bearer YOUR_TOKEN" \ "https://api.modrelay.net/health/endpoint?target=https://api.example.com" # Response includes connectivity test { "status": "healthy", "target_reachable": true, "avg_response_time_ms": 120, "last_error": null }
Performance Profiling
// Enable performance profiling 'X-Relay-Profile': 'true' // Get detailed timing breakdown { "timings": { "dns_lookup_ms": 5, "connection_ms": 45, "ssl_handshake_ms": 120, "request_sent_ms": 2, "waiting_ms": 180, "content_download_ms": 25 } }
Support Resources
Contact Support
Response Times
Frequently Asked Questions
How do I get started with ModRelay?
Does ModRelay support all HTTP methods?
Can I use ModRelay with existing APIs?
What regions are available?
Ready to get started?
Join thousands of developers using ModRelay to scale their applications.
Start Free Trial