본문 바로가기

언어 꿀Tip/09. API

09_02. 공공데이터포탈 API - 공휴일 데이터

## Load the Modules
import requests
import re
import pandas as pd
import json
import os
import time, datetime
from dfply import *
from urllib.request import urlopen
import math
import xmltodict

API Key 설정

api_key= "API 인증키 입력"

 

호출할 공휴일 데이터 년, 월 정보 Setting

l_year = ["2018","2019","2020","2021"]
l_month = [str(val).zfill(2) for val in list(range(1, 13))]

 

for 문을 활용하여 데이터 호출

df_holiday=pd.DataFrame()

for year in l_year:
    for month in l_month:
        api_info_url = f'http://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getHoliDeInfo?solYear={year}&solMonth={month}&ServiceKey={api_key}'

        api_response = requests.get(api_info_url)

        dict_type = xmltodict.parse(api_response.content)  # orderedDict type 으로 결과 return
        json_type = json.dumps(dict_type)                  # orderedDict type -> Json 으로 변환
        dict2_type = json.loads(json_type)

        if (dict2_type['response']['body']["totalCount"]!='0') & (dict2_type['response']['body']["totalCount"]!='1'):
            df_tmp =  pd.DataFrame(dict2_type['response']['body']['items']['item'])
            df_holiday = pd.concat([df_holiday, df_tmp])
        elif dict2_type['response']['body']["totalCount"]=='1':
            df_tmp =  pd.DataFrame(dict2_type['response']['body']['items']['item'] , index=[0])
            df_holiday = pd.concat([df_holiday, df_tmp])

[설명]

xml 형태로 데이터가 호출 될 때, xml -> json 형태로 변환하고자 함. 이 때, xmltodict 모듈을 이용!

 

  • xmltodict.parse(api_response.content)   # orderedDict type 으로 결과 return

OrderedDict 는 기본 딕셔너리(dictionary)와 거의 비슷하지만, 입력된 아이템들(items)의 순서를 기억하는 Dictionary 클래스

orderedDict 데이터 형태

 

  • json.dumps(dict_type)                  # orderedDict type -> Json 으로 변환. Json 인코딩

 JSON 문자열이 한 줄로 길게 표현됨

json.dumps  결과

 

  • json.loads(json_type)                  # JSON 형태의 문자열을 읽기 위해 loads()를 사용

json.loads 결과

 

 

 

 

URL : https://www.data.go.kr/data/15012690/openapi.do

 

 

 

 

 

 

 

 

 

 

 

OpenAPI활용가이드_한국천문연구원_천문우주정보__특일_정보제공_서비스_v1.4 (1).docx
0.24MB