Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ตรวจสอบสภาพอากาศปัจจุบันด้วย OpenWeatherMap API ใน Python

ใช้ OpenWeatherMap API ดึงข้อมูลสภาพอากาศของเมืองใดก็ได้ ฟรี 60 คำขอ/นาที

ขั้นตอน

  1. สมัครสมาชิกและได้ API Key
  2. ติดตั้ง requests
  3. ส่ง request ไปที่ endpoint https://api.openweathermap.org/data/2.5/weather
  4. แปลง JSON response อ่านค่าอุณหภูมิ ความชื้น ความดัน และรายงานสภาพอากาศ

ตัวอย่างโค้ด

import requests

BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
CITY = "Bangkok"
API_KEY = "YOUR_API_KEY"

url = f"{BASE_URL}q={CITY}&appid={API_KEY}&units=metric"

response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    main = data['main']
    temp = main['temp']
    humidity = main['humidity']
    pressure = main['pressure']
    weather = data['weather'][0]['description']
    
    print(f"------{CITY}------")
    print(f"อุณหภูมิ: {temp}°C")
    print(f"ความชื้น: {humidity}%")
    print(f"ความดัน: {pressure} hPa")
    print(f"สภาพอากาศ: {weather}")
else:
    print("Error in HTTP request")

ผลลัพธ์ตัวอย่าง

------Bangkok------
อุณหภูมิ: 32.5°C
ความชื้น: 70%
ความดัน: 1010 hPa
สภาพอากาศ: few clouds

หมายเหตุ

  • เพิ่ม &units=metric เพื่อได้ค่าเป็นองศาเซลเซียส
  • API key ต้องถูกต้อง มิฉะนั้นจะได้ error 401

สรุป

ดึงข้อมูลสภาพอากาศแบบเรียลไทม์ได้ง่ายด้วย OpenWeatherMap API