By the end of this lesson, you will:
ℹ️ Info Why Authentication? Just like you need a library card to borrow books, you need API keys to use many APIs. They identify who you are and track your usage!
Library | API World |
---|---|
Library Card | API Key |
Shows you're a member | Shows you're registered |
Tracks books you borrow | Tracks API calls you make |
Has borrowing limits | Has rate limits |
Can be revoked if misused | Can be disabled if abused |
// Example API keys (these are fake!)
const weatherKey = "k7j3h5g9d2m8n4b6v1c9x0z2";
const googleKey = "AIzaSyB-1234567890abcdefghijk";
const stripeKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc";
⚠️ Warning Never share your real API keys! They're like passwords - keep them secret!
Free APIs | Paid APIs |
---|---|
Limited requests (e.g., 1000/day) | Higher or unlimited requests |
Basic features | Advanced features |
May require attribution | White-label options |
Perfect for learning | For production apps |
Sign Up
Get Your Key
Test It
https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_KEY_HERE
💡 Tip Most APIs send keys via email after signup. Check your inbox!
// BAD: Key visible in code
const apiKey = "abc123xyz789"; // Anyone can see this!
fetch(`https://api.example.com/data?key=${apiKey}`);
// Store in separate file (don't commit to GitHub!)
// config.js
const API_KEY = "your-key-here";
// main.js
fetch(`https://api.example.com/data?key=${API_KEY}`);
// Use environment variables
const apiKey = process.env.API_KEY;
// Or prompt user to enter their key
const apiKey = prompt("Enter your API key:");
// Key in the URL
async function getWeather(city) {
const apiKey = "your-key-here";
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`;
const response = await fetch(url);
const data = await response.json();
return data;
}
// Key in request headers
async function getData() {
const response = await fetch('https://api.example.com/data', {
headers: {
'X-API-Key': 'your-key-here',
'Content-Type': 'application/json'
}
});
const data = await response.json();
return data;
}
// Bearer token format
async function getProtectedData() {
const response = await fetch('https://api.example.com/protected', {
headers: {
'Authorization': 'Bearer your-token-here'
}
});
const data = await response.json();
return data;
}
APIs limit how many requests you can make:
// Headers tell you about limits
const response = await fetch(apiUrl);
// Check rate limit headers
console.log(response.headers.get('X-RateLimit-Limit')); // Max requests
console.log(response.headers.get('X-RateLimit-Remaining')); // Requests left
console.log(response.headers.get('X-RateLimit-Reset')); // Reset time
// 429 = Too Many Requests
if (response.status === 429) {
console.log("Slow down! Too many requests!");
// Wait before trying again
setTimeout(() => retry(), 60000); // Wait 1 minute
}
// Complete weather app with authentication
class WeatherApp {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseURL = 'https://api.openweathermap.org/data/2.5';
}
async getWeather(city) {
try {
const url = `${this.baseURL}/weather?q=${city}&appid=${this.apiKey}&units=metric`;
const response = await fetch(url);
// Check for errors
if (response.status === 401) {
throw new Error('Invalid API key');
}
if (response.status === 404) {
throw new Error('City not found');
}
if (response.status === 429) {
throw new Error('Rate limit exceeded');
}
const data = await response.json();
return {
city: data.name,
temp: Math.round(data.main.temp),
description: data.weather[0].description
};
} catch (error) {
console.error('Weather API Error:', error);
return null;
}
}
}
// Use it
const weather = new WeatherApp('your-api-key');
const data = await weather.getWeather('Paris');
async function testAPIKey(key) {
const testURL = `https://api.example.com/test?key=${key}`;
try {
const response = await fetch(testURL);
if (response.ok) {
console.log('✅ API key is valid!');
return true;
} else if (response.status === 401) {
console.log('❌ Invalid API key');
return false;
}
} catch (error) {
console.log('❌ Network error');
return false;
}
}
// Organize your keys
const apiKeys = {
weather: 'weather-key-here',
news: 'news-key-here',
maps: 'maps-key-here'
};
// Helper function
function getAPIKey(service) {
return apiKeys[service] || null;
}
// Usage
const weatherKey = getAPIKey('weather');
You've learned:
API keys are your passport to the world of external data!
In Concept 04, you'll learn to: