본문 바로가기
Python

[OpenWeatherMap] 날씨 API 사용해보기

2023. 1. 5.

Python으로 날씨 API를 사용하여 기온, 습도, 기압, 풍향, 풍속 등 날씨 정보를 가져오는 방법에 대해 알아보자.

1. API Key 발급
https://home.openweathermap.org/

 

Members

Enter your email address and we will send you a link to reset your password.

home.openweathermap.org


사이트에 접속해서 회원가입을 진행한다

필수 정보 입력 후 Create Account

※ 입력한 메일로 메일 인증을 해야 하므로 정확하게 입력

이메일 인증과 회원가입을 완료한 후 API subscribe 클릭


Free - Get API key 클릭


My API Keys를 확인하여 방금 발급 받은 본인의 Key 확인
프로그램에서 바로 사용할 것이므로 복사!

 


2. 날씨 정보 받아오기
아래 코드의 (My API Key) 자리에 복사한 Key를 넣으면 된다.

import requests
import json

city = "Seoul"
apikey = "(My API Key)"
lang = "kr"

api = f"""http://api.openweathermap.org/data/2.5/\
weather?q={city}&appid={apikey}&lang={lang}&units=metric"""

result = requests.get(api)

data = json.loads(result.text)

print(data)

# 실행 결과 - 서버로부터 받은 데이터
{'coord': {'lon': 126.9778, 'lat': 37.5683},
 'weather': [{'id': 800, 'main': 'Clear', 'description': '맑음', 'icon': '01n'}],
 'base': 'stations',
 'main': {'temp': -3.38,
  'feels_like': -3.38,
  'temp_min': -4.34,
  'temp_max': -3.22,
  'pressure': 1030,
  'humidity': 65},
 'visibility': 10000,
 'wind': {'speed': 0.51, 'deg': 170},
 'clouds': {'all': 0},
 'dt': 1672918169,
 'sys': {'type': 1,
  'id': 8105,
  'country': 'KR',
  'sunrise': 1672872432,
  'sunset': 1672907203},
 'timezone': 32400,
 'id': 1835848,
 'name': 'Seoul',
 'cod': 200}

API call은 API docs에 맞게 작성하였다.
도시는 서울로 지정하였고
응답을 한국어로 받기 위해 &lang=kr을 추가했으며
온도 단위를 섭씨로 설정하기 위해 &units=metric을 추가한 것이다.

API docs 내용


응답 받은 데이터에는 매우 많은 현재 날씨 정보가 들어 있는 것을 확인할 수 있다.
이제 저 dictionary data에서 원하는 데이터에 접근하여 예쁘게 출력해 보자.
전체 코드

import requests
import json

city = "Seoul"
apikey = "(My API Key)"
lang = "kr"

api = f"""http://api.openweathermap.org/data/2.5/\
weather?q={city}&appid={apikey}&lang={lang}&units=metric"""

result = requests.get(api)

data = json.loads(result.text)

# 지역 : name
print(data["name"],"의 날씨입니다.")
# 자세한 날씨 : weather - description
print("날씨는 ",data["weather"][0]["description"],"입니다.")
# 현재 온도 : main - temp
print("현재 온도는 ",data["main"]["temp"],"입니다.")
# 체감 온도 : main - feels_like
print("하지만 체감 온도는 ",data["main"]["feels_like"],"입니다.")
# 최저 기온 : main - temp_min
print("최저 기온은 ",data["main"]["temp_min"],"입니다.")
# 최고 기온 : main - temp_max
print("최고 기온은 ",data["main"]["temp_max"],"입니다.")
# 습도 : main - humidity
print("습도는 ",data["main"]["humidity"],"입니다.")
# 기압 : main - pressure
print("기압은 ",data["main"]["pressure"],"입니다.")
# 풍향 : wind - deg
print("풍향은 ",data["wind"]["deg"],"입니다.")
# 풍속 : wind - speed
print("풍속은 ",data["wind"]["speed"],"입니다.")

 

# 실행 결과
Seoul 의 날씨입니다.
날씨는  맑음 입니다.
현재 온도는  -3.38 입니다.
하지만 체감 온도는  -3.38 입니다.
최저 기온은  -4.34 입니다.
최고 기온은  -3.22 입니다.
습도는  65 입니다.
기압은  1030 입니다.
풍향은  170 입니다.
풍속은  0.51 입니다.

현재 서울의 기온, 습도, 기압, 풍향, 풍속 등 날씨 정보를 받아 출력한 결과를 확인할 수 있다.

댓글