파이썬/파이썬(python) 중급

[35-1 파이썬] API key, json 온라인 뷰어, openweather 날씨 정보 얻기, 401 인증키 오류 이유, API 인증키

Olivia-BlackCherry 2022. 9. 27. 18:10

API Key?

해당 어플리케이션에서 제공하는 여러 정보와 서비스를

다른 사람들이 함부로 남용하지 않도록,

API Key를 설정하고, 이를 입력해야만 정보를 얻을 수 있게 만들었다.

 

마치 네이버, 구글 등의 웹서비스를 이용할 때

개인 계정의 아이디& 비밀번호를 입력해야 하듯,

 

API 서비스를 이용하려면, 

자신만의 고유한 'API Key'를 입력해야 한다.

 

 

API 설명 확인하기

우리가 새로운 기계를 사면, 사용 설명서를 읽어야

제대로 그 기계를 사용할 수 있듯이

API 문서를 잘 읽어야, 

해당 API 서비스를 제대로 이용할 수 있다.

 

만약 '현재 날씨'에 관한 정보를 얻기 위해

아래의 사이트가 제공하는 API를 이용한다고 하자.

https://openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w

openweathermap.org

 

가장 먼저 할 일은 해당 API에 대한 설명서를 읽는 것이다.

API doc 버튼을 눌러 상세 내용을 확인하자.

이 API는 현재 날씨, 한 시간 동안의 분(minute)당 날씨, 48 시간 동안 시간(hour)당 날씨, 8일 간의 매일(daily)날씨 등의 정보를 제공한다고 적혀있다.

 

이번에는 5일 간 3시간 마다의 일기 예보 정보가 담겨있는 API

5 day weather forecast를 보며

API를 호출하는 방법과 관련한

API의 구체적인 정보를 확인하자. 

 

1. URL, 즉 endpoint를 확인한다.

URL = "http://api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&appid={API key}"

 

 

2. 파라미터를 확인한다.

필수(required) 파라미터는 lat(위도), lon(경도), appid(API key)가 있다.

parameters = {
    "lat":37.663998,
    "lon":127.978462,
    "appid":API_KEY
}

선택(optional) 파라미터는 cnt(갯수 count), units(측정방법: metric 미터법, imperial 파운드법, standard 표준-기본값), lang(언어)이 있다.

최종코드

3-hour forecast 5 days에서 API키 넣어서 데이터 json형식으로 불러오기

import requests
URL = "http://api.openweathermap.org/data/2.5/forecast"
API_KEY = "MY_API"

parameters = {
    "lat":37.663998,
    "lon":127.978462,
    "cnt": 12,
    "lang": "kr",
    "appid":API_KEY
}
response = requests.get(URL, params= parameters)
response.raise_for_status()
data = response.json()
print(data)

>>출력값{'cod': '200', 'message': 0, 'cnt': 12, 'list': [{'dt': 1664280000, 'main': {'temp': 288.55, 'feels_like': 287.92, 'temp_min': 287.8, 'temp_max': 288.55, 'pressure': 1015, 'sea_level': 1015, 'grnd_level': 980, 'humidity': 68, 'temp_kf': 0.75}, 'weather': [{'id': 800, 'main': 'Clear', 'description': '맑음', 'icon': '01n'}], 'clouds': {'all': 0}, 'wind': {'speed': 2.07, 'deg': 71, 'gust': 1.79}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2022-09-27 12:00:00'}, {'dt': 1664290800, 'main': {'temp': 286.97, 'feels_like': 286.24, 'temp_min': 285.99, 'temp_max': 286.97, 'pressure': 1016, 'sea_level': 1016, 'grnd_level': 980, 'humidity': 70, 'temp_kf': 0.98}, 'weather': [{'id': 800, 'main': 'Clear', 'description': '맑음', 'icon': '01n'}], 'clouds': {'all': 5}, 'wind': {'speed': 1.43, 'deg': 75, 'gust': 1.26}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2022-09-27 15:00:00'}, {'dt': 1664301600, 'main': {'temp': 285.23, 'feels_like': 284.14, 'temp_min': 285.23, 'temp_max': 285.23, 'pressure': 1016, 'sea_level': 1016, 'grnd_level': 979, 'humidity': 63, 'temp_kf': 0}, 'weather': [{'id': 802, 'main': 'Clouds', 'description': '구름조금', 'icon': '03n'}], 'clouds': {'all': 37}, 'wind': {'speed': 1.42, 'deg': 76, 'gust': 1.25}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2022-09-27 18:00:00'}, {'dt': 1664312400, 'main': {'temp': 285, 'feels_like': 283.78, 'temp_min': 285, 'temp_max': 285, 'pressure': 1016, 'sea_level': 1016, 'grnd_level': 979, 'humidity': 59, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': '온흐림', 'icon': '04n'}], 'clouds': {'all': 100}, 'wind': {'speed': 0.97, 'deg': 95, 'gust': 0.88}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2022-09-27 21:00:00'}, {'dt': 1664323200, 'main': {'temp': 290.45, 'feels_like': 289.65, 'temp_min': 290.45, 'temp_max': 290.45, 'pressure': 1016, 'sea_level': 1016, 'grnd_level': 980, 'humidity': 54, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': '온흐림', 'icon': '04d'}], 'clouds': {'all': 100}, 'wind': {'speed': 0.3, 'deg': 74, 'gust': 0.54}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'd'}, 'dt_txt': '2022-09-28 00:00:00'}, {'dt': 1664334000, 'main': {'temp': 295.32, 'feels_like': 294.85, 'temp_min': 295.32, 'temp_max': 295.32, 'pressure': 1015, 'sea_level': 1015, 'grnd_level': 979, 'humidity': 48, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': '온흐림', 'icon': '04d'}], 'clouds': {'all': 100}, 'wind': {'speed': 1.11, 'deg': 263, 'gust': 1.48}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'd'}, 'dt_txt': '2022-09-28 03:00:00'}, {'dt': 1664344800, 'main': {'temp': 295.42, 'feels_like': 295.06, 'temp_min': 295.42, 'temp_max': 295.42, 'pressure': 1013, 'sea_level': 1013, 'grnd_level': 978, 'humidity': 52, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': '온흐림', 'icon': '04d'}], 'clouds': {'all': 100}, 'wind': {'speed': 1.11, 'deg': 265, 'gust': 1.61}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'd'}, 'dt_txt': '2022-09-28 06:00:00'}, {'dt': 1664355600, 'main': {'temp': 291, 'feels_like': 290.8, 'temp_min': 291, 'temp_max': 291, 'pressure': 1014, 'sea_level': 1014, 'grnd_level': 978, 'humidity': 75, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': '온흐림', 'icon': '04d'}], 'clouds': {'all': 100}, 'wind': {'speed': 0.52, 'deg': 203, 'gust': 0.57}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'd'}, 'dt_txt': '2022-09-28 09:00:00'}, {'dt': 1664366400, 'main': {'temp': 287.87, 'feels_like': 287.62, 'temp_min': 287.87, 'temp_max': 287.87, 'pressure': 1015, 'sea_level': 1015, 'grnd_level': 978, 'humidity': 85, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': '온흐림', 'icon': '04n'}], 'clouds': {'all': 96}, 'wind': {'speed': 1.04, 'deg': 98, 'gust': 0.97}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2022-09-28 12:00:00'}, {'dt': 1664377200, 'main': {'temp': 286.3, 'feels_like': 286.05, 'temp_min': 286.3, 'temp_max': 286.3, 'pressure': 1015, 'sea_level': 1015, 'grnd_level': 979, 'humidity': 91, 'temp_kf': 0}, 'weather': [{'id': 802, 'main': 'Clouds', 'description': '구름조금', 'icon': '03n'}], 'clouds': {'all': 50}, 'wind': {'speed': 0.84, 'deg': 93, 'gust': 0.75}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2022-09-28 15:00:00'}, {'dt': 1664388000, 'main': {'temp': 285.52, 'feels_like': 285.27, 'temp_min': 285.52, 'temp_max': 285.52, 'pressure': 1015, 'sea_level': 1015, 'grnd_level': 979, 'humidity': 94, 'temp_kf': 0}, 'weather': [{'id': 802, 'main': 'Clouds', 'description': '구름조금', 'icon': '03n'}], 'clouds': {'all': 38}, 'wind': {'speed': 0.99, 'deg': 89, 'gust': 0.89}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2022-09-28 18:00:00'}, {'dt': 1664398800, 'main': {'temp': 285.01, 'feels_like': 284.71, 'temp_min': 285.01, 'temp_max': 285.01, 'pressure': 1016, 'sea_level': 1016, 'grnd_level': 979, 'humidity': 94, 'temp_kf': 0}, 'weather': [{'id': 802, 'main': 'Clouds', 'description': '구름조금', 'icon': '03n'}], 'clouds': {'all': 46}, 'wind': {'speed': 0.75, 'deg': 93, 'gust': 0.73}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2022-09-28 21:00:00'}], 'city': {'id': 1844191, 'name': 'Hongch’ŏn', 'coord': {'lat': 37.664, 'lon': 127.9785}, 'country': 'KR', 'population': 75251, 'timezone': 32400, 'sunrise': 1664227174, 'sunset': 1664270333}}

 

 

 

온라인 json viewer

json 파일이 파이참 안에서 출력되니, 

글이 너무 빡빡하고, 줄 띄움도 되지 않아 심난하다(?)

데이터를 해석할 엄두가 나지 않는다.

 

이럴 때는 온라인 뷰어를 이용한다.

json 파일을 시각적으로 정돈하여 보고 싶을 때, 

아래의 사이트에서 text 칸에 내용을 입력하고, viewer를 클릭하면 

시각적으로 아주 잘 정리된 내용을 볼 수 있다.

정돈 되기 전 json파일
viewer로 본 모습

http://jsonviewer.stack.hu/

 

Online JSON Viewer

 

jsonviewer.stack.hu

 

 

< openweather에서 401 에러코드가 발생하는 이유>

여담이지만.. 처음에 이 에러가 발생하여 몇 시간을 허비했다...ㅠ 

 

먼저, 처음으로 가입했다면 

가입한 이메일로 들어가 인증(verify)을 한다. 

 

그래도 

이 사이트에서 제공하는 API를 requests하면 401 코드 에러, 

즉 API key가 존재하지 않는다는 에러가 뜬다면.. 

 

요청한 API 서비스가 유료 API 서비스일 확률이 높다.

 API 서비스 자체가 무료~ 유료로 구분되어 있는데,

무료가 아닌 부분은 

서비스에 접근이 불가하기 때문이다.

 

우리가 무료로 사용할 수 있는 것은,

Free열에 있는

current weather

3-hour forecast 5 days

basic weather map

air pollution API

등이 있다. 

https://openweathermap.org/price#weather

 

Pricing - OpenWeatherMap

Get weather data for any location on the globe immediately with our superb API! Just subscribe with your email and start using minute forecasts, hourly forecasts, history and other weather data in your applications. For more functionality, please consider

openweathermap.org