Code Examples
Ready-to-use code examples for integrating the Predikt API into your applications.
JavaScript / TypeScript
Basic Setup
predikt-client.ts
const API_BASE = 'https://api.predikt.fun/api/v1';const API_KEY = process.env.PREDIKT_API_KEY;interface PriceResponse {symbol: string;price: number;sources: string[];timestamp: string;costUsd: string;}async function getPrice(symbol: string): Promise<PriceResponse> {const response = await fetch(`${API_BASE}/price/${symbol}`, {headers: {'Authorization': `Bearer ${API_KEY}`,},});if (!response.ok) {const error = await response.json();throw new Error(error.message || 'API request failed');}return response.json();}// Usageconst solPrice = await getPrice('SOL');console.log(`SOL price: $${solPrice.price}`);
Batch Price Request
batch-prices.ts
interface BatchPriceResponse {prices: Array<{symbol: string;price: number;sources: string[];}>;timestamp: string;costUsd: string;}async function getBatchPrices(symbols: string[]): Promise<BatchPriceResponse> {const response = await fetch(`${API_BASE}/price/batch`, {method: 'POST',headers: {'Authorization': `Bearer ${API_KEY}`,'Content-Type': 'application/json',},body: JSON.stringify({ symbols }),});if (!response.ok) {throw new Error('Batch request failed');}return response.json();}// Usageconst prices = await getBatchPrices(['SOL', 'BTC', 'ETH']);prices.prices.forEach(p => {console.log(`${p.symbol}: $${p.price}`);});
AI Resolution with Polling
ai-resolution.ts
interface AIResolutionRequest {requestId: string;status: 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'FAILED';estimatedCompletionSeconds: number;costUsd: string;}interface AIResolutionResult {requestId: string;status: string;result?: {winningOutcomeIndex: number;confidence: number;reasoning: string;sources: string[];};completedAt?: string;}async function requestAIResolution(marketId: string): Promise<AIResolutionResult> {const submitResponse = await fetch(`${API_BASE}/ai/resolve`, {method: 'POST',headers: {'Authorization': `Bearer ${API_KEY}`,'Content-Type': 'application/json',},body: JSON.stringify({ marketId }),});const request: AIResolutionRequest = await submitResponse.json();console.log(`Resolution requested: ${request.requestId}`);let result: AIResolutionResult;do {await new Promise(resolve => setTimeout(resolve, 5000));const resultResponse = await fetch(`${API_BASE}/ai/result/${request.requestId}`,{ headers: { 'Authorization': `Bearer ${API_KEY}` } });result = await resultResponse.json();console.log(`Status: ${result.status}`);} while (result.status === 'PENDING' || result.status === 'PROCESSING');return result;}// Usageconst resolution = await requestAIResolution('clx1234567890');if (resolution.result) {console.log(`Winner: Outcome ${resolution.result.winningOutcomeIndex}`);console.log(`Confidence: ${resolution.result.confidence * 100}%`);}
Python
Basic Setup
predikt_client.py
import osimport requestsfrom typing import TypedDict, ListAPI_BASE = "https://api.predikt.fun/api/v1"API_KEY = os.environ.get("PREDIKT_API_KEY")class PriceResponse(TypedDict):symbol: strprice: floatsources: List[str]timestamp: strcostUsd: strdef get_price(symbol: str) -> PriceResponse:"""Get current price for a symbol."""response = requests.get(f"{API_BASE}/price/{symbol}",headers={"Authorization": f"Bearer {API_KEY}"})response.raise_for_status()return response.json()# Usagesol_price = get_price("SOL")print(f"SOL price: {sol_price['price']}")
Batch Prices
batch_prices.py
from typing import TypedDict, Listclass PriceItem(TypedDict):symbol: strprice: floatsources: List[str]class BatchPriceResponse(TypedDict):prices: List[PriceItem]timestamp: strcostUsd: strdef get_batch_prices(symbols: List[str]) -> BatchPriceResponse:"""Get prices for multiple symbols."""response = requests.post(f"{API_BASE}/price/batch",headers={"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json"},json={"symbols": symbols})response.raise_for_status()return response.json()# Usageprices = get_batch_prices(["SOL", "BTC", "ETH"])for p in prices["prices"]:print(f"{p['symbol']}: {p['price']}")
Schedule Price Check
schedule_price.py
from datetime import datetime, timedeltafrom typing import TypedDictclass ScheduledJobResponse(TypedDict):jobId: strtype: strsymbol: strscheduledFor: strstatus: strcostUsd: strdef schedule_price_check(symbol: str,scheduled_for: datetime,callback_url: str | None = None) -> ScheduledJobResponse:"""Schedule a price check for a future time."""payload = {"symbol": symbol,"scheduledFor": scheduled_for.isoformat() + "Z"}if callback_url:payload["callbackUrl"] = callback_urlresponse = requests.post(f"{API_BASE}/price/scheduled",headers={"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json"},json=payload)response.raise_for_status()return response.json()# Usage: Schedule for tomorrow at midnight UTCtomorrow = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)job = schedule_price_check("SOL", tomorrow)print(f"Scheduled job: {job['jobId']}")
cURL
Get Price
Shell
# Get SOL pricecurl -X GET "https://api.predikt.fun/api/v1/price/SOL" \-H "Authorization: Bearer $PREDIKT_API_KEY"
Batch Prices
Shell
# Get multiple pricescurl -X POST "https://api.predikt.fun/api/v1/price/batch" \-H "Authorization: Bearer $PREDIKT_API_KEY" \-H "Content-Type: application/json" \-d '{"symbols": ["SOL", "BTC", "ETH"]}'
Request AI Resolution
Shell
# Request AI resolutioncurl -X POST "https://api.predikt.fun/api/v1/ai/resolve" \-H "Authorization: Bearer $PREDIKT_API_KEY" \-H "Content-Type: application/json" \-d '{"marketId": "clx1234567890"}'# Check result (replace REQUEST_ID)curl -X GET "https://api.predikt.fun/api/v1/ai/result/REQUEST_ID" \-H "Authorization: Bearer $PREDIKT_API_KEY"
Check Account Balance
Shell
# Get account infocurl -X GET "https://api.predikt.fun/api/v1/account" \-H "Authorization: Bearer $PREDIKT_API_KEY"
API Key Management
Programmatically manage API keys with IP restrictions, expiration, and rotation.
key-management.ts
interface ApiKeyResponse {id: string;keyPrefix: string;name: string;permissions: string[];isActive: boolean;expiresAt?: string;allowedIps: string[];ipRestrictionEnabled: boolean;allowedOrigins: string[];originRestrictionEnabled: boolean;createdAt: string;}interface CreateKeyResponse extends ApiKeyResponse {key: string; // Only returned once on creation!}// Create a new API key with restrictionsasync function createApiKey(options: {name: string;permissions?: string[];expiresAt?: string;allowedIps?: string[];ipRestrictionEnabled?: boolean;}): Promise<CreateKeyResponse> {const response = await fetch(`${API_BASE}/keys`, {method: 'POST',headers: {'Authorization': `Bearer ${API_KEY}`,'Content-Type': 'application/json',},body: JSON.stringify(options),});if (!response.ok) throw new Error('Failed to create key');return response.json();}// Rotate an API key (old key valid for 60 min grace period)async function rotateApiKey(keyId: string): Promise<{newKey: CreateKeyResponse;oldKey: ApiKeyResponse;}> {const response = await fetch(`${API_BASE}/keys/${keyId}/rotate`, {method: 'POST',headers: { 'Authorization': `Bearer ${API_KEY}` },});if (!response.ok) throw new Error('Failed to rotate key');return response.json();}// Usage: Create key with IP restrictionconst newKey = await createApiKey({name: 'Production Server',permissions: ['price', 'batch', 'markets'],allowedIps: ['192.168.1.0/24', '10.0.0.1'],ipRestrictionEnabled: true,});console.log('Save this key:', newKey.key); // Only shown once!// Usage: Rotate key with grace periodconst { newKey: rotated, oldKey } = await rotateApiKey('key_id_here');console.log('New key:', rotated.key);console.log('Old key expires:', oldKey.expiresAt);
Error Handling
Always handle errors gracefully. Here's a TypeScript example with all error codes:
error-handling.ts
interface APIError {error: string;code: string;details?: Record<string, unknown>;}async function safeApiCall<T>(url: string,options?: RequestInit): Promise<T> {const response = await fetch(url, {...options,headers: {'Authorization': `Bearer ${API_KEY}`,...options?.headers,},});if (!response.ok) {const error: APIError = await response.json();switch (error.code) {case 'INVALID_API_KEY':throw new Error('Invalid or expired API key');case 'API_KEY_EXPIRED':throw new Error('API key has expired - create a new one');case 'API_KEY_REVOKED':throw new Error('API key has been revoked');case 'INSUFFICIENT_BALANCE':throw new Error('Insufficient balance - please deposit funds');case 'PERMISSION_DENIED':throw new Error('Insufficient permissions for this endpoint');case 'RATE_LIMIT_EXCEEDED':throw new Error('Rate limit exceeded - slow down requests');case 'ACCOUNT_SUSPENDED':throw new Error('Account is suspended');case 'ACCOUNT_NOT_FOUND':throw new Error('API account not found');case 'INVALID_SYMBOL':throw new Error('Invalid symbol or mint address');case 'INVALID_TIMESTAMP':throw new Error('Invalid timestamp format');case 'TIMESTAMP_IN_PAST':throw new Error('Resolution timestamp must be in the future');case 'JOB_NOT_FOUND':throw new Error('Scheduled job not found');case 'JOB_CANNOT_CANCEL':throw new Error('Cannot cancel this job');case 'CALLBACK_FAILED':throw new Error('Callback delivery failed');case 'IP_NOT_ALLOWED':throw new Error('Your IP is not whitelisted for this key');case 'ORIGIN_NOT_ALLOWED':throw new Error('This origin is not allowed for this key');case 'MAX_KEYS_EXCEEDED':throw new Error('Maximum API keys limit reached');case 'QUOTA_EXCEEDED':throw new Error('Daily or monthly quota exceeded');case 'KEY_ROTATION_IN_PROGRESS':throw new Error('Key rotation already in progress');case 'VALIDATION_ERROR':throw new Error(`Validation failed: ${error.details ? JSON.stringify(error.details) : error.error}`);case 'INTERNAL_ERROR':throw new Error('Internal server error - please try again');default:throw new Error(error.error || 'API request failed');}}return response.json();}// Usage with error handlingtry {const price = await safeApiCall<PriceResponse>(`${API_BASE}/price/SOL`);console.log(price);} catch (error) {console.error('API Error:', error.message);}