28. Third-Party APIs Integration
Why Third-Party API Integration Matters
Many modern apps rely on external services for functionality — like authentication, payments, maps, or social feeds. Learning how to integrate third-party APIs lets your app leverage powerful tools without reinventing the wheel.
Authentication & API Keys
Most APIs require authentication. This can be a simple API key, OAuth token, or more advanced mechanisms. Keep your credentials secure and avoid exposing them in frontend code.
// Using an API key (never hardcode in frontend!)
const API_KEY = process.env.API_KEY;
const res = await fetch(`https://api.example.com/data?key=${API_KEY}`);
const data = await res.json();
console.log(data);OAuth 2.0 & Access Tokens
OAuth allows users to grant limited access to their resources on a third-party service without exposing credentials. After authorization, your app receives an access token to make requests.
Handling API Rate Limits
Third-party APIs often enforce limits on requests per minute or day. Respect rate limits to avoid being blocked. Techniques include batching, caching, and throttling.
async function fetchWithRateLimit(urls, limit = 5) {
const results = [];
for (let i = 0; i < urls.length; i += limit) {
const batch = urls.slice(i, i + limit).map(url => fetch(url).then(r => r.json()));
results.push(...await Promise.all(batch));
await new Promise(r => setTimeout(r, 1000)); // small delay between batches
}
return results;
}Error Handling & Data Validation
Third-party APIs can fail or return unexpected data. Always validate responses and handle errors gracefully.
try {
const res = await fetch('https://api.example.com/data');
if (!res.ok) throw new Error('API request failed');
const data = await res.json();
if (!data || !Array.isArray(data.items)) throw new Error('Invalid data');
console.log(data.items);
} catch (err) {
console.error('Error fetching third-party API:', err);
}Pagination & Cursor-Based APIs
Some APIs return data in pages or use cursors. Learn to fetch all pages sequentially or in parallel while respecting rate limits.
async function fetchAllPages(baseUrl) {
let page = 1;
let allData = [];
let hasMore = true;
while (hasMore) {
const res = await fetch(`${baseUrl}?page=${page}`);
const data = await res.json();
allData.push(...data.items);
hasMore = data.items.length > 0;
page++;
}
return allData;
}Practical Example: GitHub API
The GitHub API lets you fetch user info, repositories, and more. Here’s a practical example of fetching a user’s repositories and filtering by stars.
async function getPopularRepos(username) {
const res = await fetch(`https://api.github.com/users/${username}/repos`);
const repos = await res.json();
const popular = repos.filter(r => r.stargazers_count >= 50);
console.log(popular.map(r => r.name));
}
getPopularRepos('octocat');Mini Challenge
1. Pick any public third-party API (e.g., OpenWeather, PokeAPI, NewsAPI). 2. Fetch data with proper error handling. 3. Implement pagination if applicable. 4. Display results dynamically on the page, filtering or sorting as needed. 5. Bonus: Use a personal API key and hide it securely.