Skip to main content

Code Examples

This document provides practical code examples for using the Elfa REST API across different programming languages and frameworks. Use these examples to quickly integrate with our platform.

REST API Examples

JavaScript (Fetch)

// Get trending tokens from the Elfa API
const getTrendingTokens = async (apiKey) => {
const response = await fetch("https://api.elfa.ai/v2/aggregations/trending-tokens", {
headers: {
"x-elfa-api-key": apiKey,
},
});

if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}

return await response.json();
};

// Example usage
getTrendingTokens("your_api_key_here")
.then(data => console.log(data))
.catch(error => console.error("Error:", error));

Python (Requests)

import requests

def get_trending_tokens(api_key):
"""Get trending tokens from the Elfa API"""
headers = {
"x-elfa-api-key": api_key
}

response = requests.get("https://api.elfa.ai/v2/aggregations/trending-tokens", headers=headers)
response.raise_for_status() # Raise exception for 4XX/5XX responses

return response.json()

# Example usage
try:
data = get_trending_tokens("your_api_key_here")
print(data)
except requests.exceptions.RequestException as e:
print(f"Error: {e}")

cURL

curl -X GET "https://api.elfa.ai/v2/aggregations/trending-tokens" \
-H "x-elfa-api-key: your_api_key_here"

Getting Mentions with Smart Engagement

JavaScript (Fetch)

// Get mentions with smart engagement
const getSmartEngagement = async (apiKey, params = {}) => {
// Default parameters
const defaultParams = {
keywords: "elfa",
limit: 10,
minEngagement: 0.5
};

// Combine default with provided params
const queryParams = { ...defaultParams, ...params };

// Build URL with query parameters
const url = new URL("https://api.elfa.ai/v2/data/top-mentions");
Object.keys(queryParams).forEach(key =>
url.searchParams.append(key, queryParams[key])
);

const response = await fetch(url, {
headers: {
"x-elfa-api-key": apiKey,
},
});

if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}

return await response.json();
};

// Example usage
getSmartEngagement("your_api_key_here", {
keywords: "bitcoin,ethereum",
limit: 20
})
.then(data => console.log(data))
.catch(error => console.error("Error:", error));

Python (Requests)

import requests

def get_smart_engagement(api_key, **kwargs):
"""Get mentions with smart engagement"""
# Default parameters
params = {
"keywords": "elfa",
"limit": 10,
"minEngagement": 0.5
}

# Update with any provided parameters
params.update(kwargs)

headers = {
"x-elfa-api-key": api_key
}

response = requests.get(
"https://api.elfa.ai/v2/data/top-mentions",
headers=headers,
params=params
)
response.raise_for_status()

return response.json()

# Example usage
try:
data = get_smart_engagement(
"your_api_key_here",
keywords="bitcoin,ethereum",
limit=20
)
print(data)
except requests.exceptions.RequestException as e:
print(f"Error: {e}")

Error Handling Best Practices

JavaScript Error Handling

const fetchElfaAPI = async (endpoint, apiKey, params = {}) => {
try {
// Build URL with query parameters
const url = new URL(`https://api.elfa.ai/v2/${endpoint}`);
Object.keys(params).forEach(key =>
url.searchParams.append(key, params[key])
);

// Make the request
const response = await fetch(url, {
headers: {
"x-elfa-api-key": apiKey,
},
});

// Handle different HTTP status codes
if (response.status === 401) {
throw new Error("Authentication failed. Check your API key.");
} else if (response.status === 403) {
throw new Error("You don't have permission to access this resource.");
} else if (response.status === 429) {
throw new Error("Rate limit exceeded. Try again later.");
} else if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}

return await response.json();
} catch (error) {
console.error("Error fetching from Elfa API:", error);
throw error;
}
};

Python Error Handling

import requests
from time import sleep

def fetch_elfa_api(endpoint, api_key, params=None, max_retries=3):
"""Fetch data from Elfa API with retry logic for rate limits"""
if params is None:
params = {}

headers = {
"x-elfa-api-key": api_key
}

url = f"https://api.elfa.ai/v2/{endpoint}"

retry_count = 0
while retry_count < max_retries:
try:
response = requests.get(url, headers=headers, params=params)

# Handle specific status codes
if response.status_code == 401:
raise ValueError("Authentication failed. Check your API key.")
elif response.status_code == 403:
raise ValueError("You don't have permission to access this resource.")
elif response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", 60))
print(f"Rate limit exceeded. Retrying in {retry_after} seconds...")
sleep(retry_after)
retry_count += 1
continue

response.raise_for_status()
return response.json()

except requests.exceptions.RequestException as e:
if retry_count < max_retries - 1:
retry_count += 1
sleep(2 ** retry_count) # Exponential backoff
continue
raise e

raise RuntimeError("Maximum number of retries exceeded.")

Pagination Examples

JavaScript Pagination

// Function to get all pages of data
const getAllPages = async (endpoint, apiKey, params = {}) => {
let allData = [];
let currentPage = 1;
let hasMore = true;

while (hasMore) {
// Update the page parameter for each request
const pageParams = {
...params,
page: currentPage,
limit: params.limit || 100
};

const data = await fetchElfaAPI(endpoint, apiKey, pageParams);

// Add this page's data to our collection
if (data.items && data.items.length) {
allData = [...allData, ...data.items];
}

// Check if we should continue paginating
hasMore = data.pagination && data.pagination.hasNextPage;
currentPage++;

// Optional: Add a small delay to avoid rate limiting
if (hasMore) {
await new Promise(resolve => setTimeout(resolve, 300));
}
}

return allData;
};

// Example usage
getAllPages("data/keyword-mentions", "your_api_key_here", {
keywords: "bitcoin,ethereum",
startDate: "2023-04-01",
endDate: "2023-04-30"
})
.then(allMentions => console.log(`Retrieved ${allMentions.length} mentions`))
.catch(error => console.error("Error:", error));

Python Pagination

def get_all_pages(endpoint, api_key, **params):
"""Get all pages of data from a paginated API endpoint"""
all_items = []
current_page = 1
limit = params.get('limit', 100)

while True:
# Update parameters with current page
page_params = {**params, 'page': current_page, 'limit': limit}

# Make API request
data = fetch_elfa_api(endpoint, api_key, page_params)

# Add the items from this page
if 'items' in data and data['items']:
all_items.extend(data['items'])

# Check if there are more pages
if not data.get('pagination', {}).get('hasNextPage', False):
break

# Move to next page
current_page += 1

# Optional: Add a small delay to avoid rate limiting
sleep(0.3)

return all_items

# Example usage
try:
all_mentions = get_all_pages(
"data/keyword-mentions",
"your_api_key_here",
keywords="bitcoin,ethereum",
startDate="2023-04-01",
endDate="2023-04-30"
)
print(f"Retrieved {len(all_mentions)} mentions")
except Exception as e:
print(f"Error: {e}")

Complete Application Example

React Application with Elfa API Integration

import React, { useState, useEffect } from 'react';
import './App.css';

// Configuration
const API_KEY = "your_api_key_here";
const API_BASE_URL = "https://api.elfa.ai/v2";

function App() {
const [trendingTokens, setTrendingTokens] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
// Fetch trending tokens when component mounts
const fetchTrendingTokens = async () => {
try {
setLoading(true);
const response = await fetch(`${API_BASE_URL}/aggregations/trending-tokens`, {
headers: {
"x-elfa-api-key": API_KEY
}
});

if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}

const data = await response.json();
setTrendingTokens(data.tokens || []);
setError(null);
} catch (err) {
setError(err.message);
console.error("Failed to fetch trending tokens:", err);
} finally {
setLoading(false);
}
};

fetchTrendingTokens();

// Set up polling interval (every 5 minutes)
const intervalId = setInterval(fetchTrendingTokens, 5 * 60 * 1000);

// Clean up interval on component unmount
return () => clearInterval(intervalId);
}, []);

return (
<div className="App">
<header className="App-header">
<h1>Trending Tokens</h1>
</header>

<main>
{loading && <p>Loading trending tokens...</p>}

{error && (
<div className="error-message">
<p>Error: {error}</p>
<button onClick={() => window.location.reload()}>Retry</button>
</div>
)}

{!loading && !error && (
<div className="tokens-container">
{trendingTokens.length === 0 ? (
<p>No trending tokens found.</p>
) : (
<ul className="tokens-list">
{trendingTokens.map((token, index) => (
<li key={token.id || index} className="token-item">
<span className="token-symbol">{token.symbol}</span>
<span className="token-name">{token.name}</span>
<span className="token-score">Score: {token.score}</span>
</li>
))}
</ul>
)}
</div>
)}
</main>
</div>
);
}

export default App;

Additional Resources

For more detailed examples and information:

For any questions or issues with these code examples, please contact our support team.