Weather API Program
हम क्या बना रहे हैं
Weather app user से city पूछता है, internet पर weather API call करता है, और मौजूदा temperature व conditions दिखाता है। यह सीखने का बढ़िया project है कि programs requests library इस्तेमाल करके web से live data कैसे लाते हैं और JSON पढ़ते हैं।
requests library
requests web APIs से बात करने की standard Python library है। इसे एक बार install कीजिए:
pip install requests
फिर अपने program में import कीजिए। यह आपको एक line, requests.get(url), से किसी URL से data लाने देता है।
API call करना
import requests
city = "Delhi"
key = "YOUR_API_KEY"
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={key}&units=metric"
response = requests.get(url)
data = response.json()
हम URL को city, अपनी API key, और Celsius के लिए units=metric के साथ बनाते हैं। requests.get इसे लाता है, और .json() जवाब को Python dictionary में बदलता है।
JSON पढ़ना
temp = data["main"]["temp"]
weather = data["weather"][0]["description"]
print(f"Temperature in {city}: {temp} C")
print(f"Condition: {weather}")
Condition: clear sky
JSON एक nested dictionary है। हम इसमें keys से पहुँचते हैं — temperature को data["main"]["temp"] और condition को data["weather"][0]["description"]।
Errors संभालना
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(data["main"]["temp"], "C")
elif response.status_code == 404:
print("City not found")
else:
print("Error:", response.status_code)
हमेशा status code जाँचिए। 200 यानी सफलता; 404 यानी city नहीं मिली; अन्य codes यानी कोई और समस्या। यह app को बुरे input पर crash होने से बचाता है।
आम गलतियाँ
- Missing या गलत API key। Service request मना कर देती है — sign up करके valid key इस्तेमाल कीजिए।
- Status code न जाँचना। 404 या error फिर JSON पढ़ते समय crash करता है।
- गलत JSON keys। पहले पूरा
dataprint करके exact structure देखिए। units=metricभूलना। इसके बिना temperature Kelvin में आता है, Celsius में नहीं।
सारांश
- Weather app weather API से live data लाता है।
requestslibrary और एक free API key इस्तेमाल कीजिए।requests.get(url)लाता है;.json()dictionary देता है।data["main"]["temp"]जैसी nested keys पढ़िए।- Errors सहजता से संभालने को status code (200, 404) जाँचिए।
आगे, data format समझिए JSON in Python में, या इसे व्यवस्थित कीजिए dictionaries से।
अक्सर पूछे जाने वाले प्रश्न (FAQ)
Python program weather data कैसे लेता है?
requests library से internet पर weather API call करता है, city नाम और एक API key भेजकर। API JSON data से जवाब देता है, जिसे program temperature और conditions दिखाने को पढ़ता है।API key क्या है और मुझे क्यों चाहिए?
Python में JSON response कैसे पढ़ूँ?
response.json() call कीजिए, फिर values को उनकी keys से पढ़िए — जैसे temperature को data["main"]["temp"]।API call करने को कौन-सी library इस्तेमाल करूँ?
requests library standard विकल्प है। इसे pip install requests से install कीजिए, फिर API से data लाने को requests.get(url) इस्तेमाल कीजिए।