브라우저 확장 프로그램용 OpenWeatherMap API: 실용 가이드
Source: Dev.to
위 링크에 포함된 텍스트를 제공해 주시면, 해당 내용을 한국어로 번역해 드리겠습니다.
소개
날씨 데이터를 표시하는 브라우저 확장 프로그램을 만들고 있다면, OpenWeatherMap이 최고의 선택입니다. 무료 티어는 실제로 유용하고, API는 잘 문서화되어 있으며, 서버가 아닌 필요에 따라 API를 호출하는 확장 프로그램에 잘 작동합니다.
무료 티어 제한
- 분당 60회 호출
- 월 1,000,000회 호출
- Current Weather Data API 접근
- 5 Day / 3 Hour Forecast API 접근
새 탭 확장 프로그램의 경우, 활성 사용자가 10 000명이고 하루에 20개의 탭을 열어도 하루에 약 200 000회 호출이 필요합니다(월 약 6 백만 회). 10분 캐싱을 적용하면 월 약 600 000회로 감소하여 무료 한도 아래에서 충분히 운영할 수 있습니다.
사용자당 API 키
모든 사용자는 자신만의 API 키가 필요합니다. 공개 배포된 확장 프로그램에 단일 키를 번들로 포함하면 소스 코드에서 키가 추출될 수 있어 누구든지 할당량을 소진시킬 수 있습니다.
사용자의 키 저장
// Extension popup/settings page
async function saveApiKey(key) {
await chrome.storage.local.set({ owmApiKey: key });
}
사용자의 키로 날씨 가져오기
// In newtab.js
async function getWeather(city) {
const { owmApiKey } = await chrome.storage.local.get('owmApiKey');
if (!owmApiKey) {
// Show API key setup prompt
showApiKeyPrompt();
return;
}
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${owmApiKey}&units=metric`;
const response = await fetch(url);
if (!response.ok) {
if (response.status === 401) {
showApiKeyError('Invalid API key');
}
return;
}
return response.json();
}
장점
- 사용자 데이터(키, 계정)를 비공개로 유지
- 배포를 위한 백엔드가 필요 없음
- 확장 프로그램에서 API 키 추출 방지
- 각 사용자가 할당량 책임을 명확히 함
호출을 줄이기 위한 캐싱
탭을 열 때마다 API를 호출하는 것은 비효율적이며 금방 호출 제한에 도달합니다.
const CACHE_DURATION = 10 * 60 * 1000; // 10 minutes
async function getWeatherWithCache(city) {
const cacheKey = `weather_${city}`;
const cached = JSON.parse(localStorage.getItem(cacheKey) || 'null');
if (cached && (Date.now() - cached.timestamp) {
const date = new Date(item.dt * 1000);
const dayKey = date.toDateString();
const hour = date.getHours();
// Prefer readings around noon (12‑15h)
if (!byDay[dayKey] || (hour >= 12 && hour day !== today)
.slice(0, 3)
.map(([day, item]) => ({
date: day,
temp_min: Math.round(item.main.temp_min),
temp_max: Math.round(item.main.temp_max),
icon: item.weather[0].icon,
description: item.weather[0].main
}));
}
날씨 아이콘
OpenWeatherMap 아이콘은 다음 주소에서 제공됩니다:
https://openweathermap.org/img/wn/{icon}@2x.png
맞춤 아이콘을 사용하고 싶다면, 상태 코드를 이모지나 직접 만든 SVG에 매핑할 수 있습니다:
function weatherCodeToEmoji(iconCode) {
const code = iconCode.substring(0, 2); // '01', '02', etc.
const isDay = iconCode.endsWith('d');
const map = {
'01': isDay ? '☀️' : '🌙',
'02': isDay ? '⛅' : '☁️',
'03': '☁️',
'04': '☁️',
'09': '🌧️',
'10': isDay ? '🌦️' : '🌧️',
'11': '⛈️',
'13': '❄️',
'50': '🌫️'
};
return map[code] || '🌡️';
}
Geolocation vs. Manual Input
자동으로 위치를 감지하는 것이 이상적이지만 사용자 권한이 필요하고 실패할 수 있습니다. 수동으로 도시를 입력할 수 있는 대체 방법을 제공하십시오.
async function initWeather() {
// Try geolocation first
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(
async (pos) => {
const { latitude, longitude } = pos.coords;
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${apiKey}`;
// ... fetch and display
},
() => {
// Geolocation denied or failed
showCityInputForm();
},
{ timeout: 5000, maximumAge: 60 * 60 * 1000 } // Cache for 1 hour
);
} else {
showCityInputForm();
}
}
프로덕션 체크리스트
- API: OpenWeatherMap 무료 티어, 사용자 제공 키
- Caching: 10분
localStorage캐시 - Units: 위치에 따라 미터법/야드법 자동 감지, 사용자가 직접 설정 가능
- Fallback: 위치 정보 거부 시 수동으로 도시 입력
- Error handling:
401– 잘못된 API 키404– 도시를 찾을 수 없음- Network errors – 일반 재시도 메시지 표시
이 확장 프로그램은 오픈 소스이며, 자세한 내용은 구현을 검토할 수 있습니다.