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

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

// 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));

Error Handling Best Practices

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;
}
};

Pagination Examples

// 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));

Complete Application Example

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.