Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

에코프로.AI

[Python] Requests 라이브러리 소개 및 활용(Feat. json) 본문

AI Tutorial

[Python] Requests 라이브러리 소개 및 활용(Feat. json)

AI_HitchHiker 2024. 8. 18. 12:01

https://levelup.gitconnected.com/an-introduction-to-python-requests-simplifying-web-communication-311851f7405e

  • Requests 라이브러리
    • 파이썬에서  HTTP요청을 보내기 위해 널리 사용되는 라이브러리
    • 간단하고 직관적인 인터페이스 제공하여, GET, POST, PUT, DELETE  등의 HTTP메소드 사용이 용이함.
    • 주요 특징
      • 간단한 HTTP요청/응답 처리
      • 다양한 HTTP 메소드 지원 (GET / POST / PUT / DELETE 등)
      • 요청 매개변수와 헤더 설정
      • JSON 데이터 자동 파싱
      • 타임아웃 및 예외처리 기능
    • 라이브러리 설치
pip install requests
  • Requests 기본 사용법
    • GET 요청 보내기
      • 서버에 데이터를 요청할 때, get() 함수 사용
  • json 데이터 변환시, json() 함수
result = response.json()
print(result)
  • DataFrame 생성
import pandas as pd

issue_labels = pd.DataFrame(result)
issue_labels

공공데이터 API를 통한 JSON 데이터 처리

  • requests 라이브러리 사용 선언
import requests

척노리스 조크 API 사이트 접속

url = 'https://api.chucknorris.io/jokes/random'
response = requests.get(url)

if response.status_code == 200:
    print(response.text)
else:
    print(response.status_code)

print(type(response))
print(type(response.text))

 

result = response.json()
print(result)
print(type(result))

 

print(result['categories'])
print(result['created_at'])
print(result['icon_url'])
print(result['id'])
print(result['updated_at'])
print(result['url'])
print(result['value'])

 

import pandas as pd

issue_labels = pd.DataFrame(result)
print(issue_labels)


공공데이터 실습

  • 공공데이터 포털
    • URL : https://www.data.go.kr
  • "식품의약품 안전처_식품 영양성분 정보"
    • 사이트 접속 후, "활용신청"을 눌러서 API KEY를 받는다.

 

  • "바나나칩"의 식품정보 가져오기
# Python3 샘플 코드 #
import requests

# 일반 인증키 (Decoding) 사용
apikey = '공공데이터 포털에서 "활용신청"을 통해서 받은 API KEY'

url = 'http://apis.data.go.kr/1471000/FoodNtrIrdntInfoService1/getFoodNtrItdntList1'

# 바나나칩
params ={'serviceKey' : apikey,
         'desc_kor' : '바나나칩',
         'pageNo' : '1',
         'numOfRows' : '3',
         'bgn_year' : '2017',
         'animal_plant' : '(유)돌코리아',
         'type' : 'json' }

response = requests.get(url, params=params)

if response.status_code == 200:
    result = response.json()
    print(result)
else:
    print('실패 : ', response.status_code)
[결과값]

{'header': {'resultCode': '00', 'resultMsg': 'NORMAL SERVICE.'}, 'body': {'pageNo': 1, 'totalCount': 1, 'numOfRows': 3, 'items': [{'DESC_KOR': '바나나칩', 'SERVING_WT': '30', 'NUTR_CONT1': '49.50', 'NUTR_CONT2': '5.40', 'NUTR_CONT3': '0.30', 'NUTR_CONT4': '3.00', 'NUTR_CONT5': '3.30', 'NUTR_CONT6': '0.60', 'NUTR_CONT7': '0.00', 'NUTR_CONT8': '2.70', 'NUTR_CONT9': '0.00', 'BGN_YEAR': '2017', 'ANIMAL_PLANT': '(유)돌코리아'}]}}

 

print(result)
print(type(result))

 

[결과값]

{'header': {'resultCode': '00', 'resultMsg': 'NORMAL SERVICE.'}, 'body': {'pageNo': 1, 'totalCount': 1, 'numOfRows': 3, 'items': [{'DESC_KOR': '바나나칩', 'SERVING_WT': '30', 'NUTR_CONT1': '49.50', 'NUTR_CONT2': '5.40', 'NUTR_CONT3': '0.30', 'NUTR_CONT4': '3.00', 'NUTR_CONT5': '3.30', 'NUTR_CONT6': '0.60', 'NUTR_CONT7': '0.00', 'NUTR_CONT8': '2.70', 'NUTR_CONT9': '0.00', 'BGN_YEAR': '2017', 'ANIMAL_PLANT': '(유)돌코리아'}]}} <class 'dict'>

 

for dic in result:
    print(dic)
[결과값]

header body

 

print(result['header'])
print(result['body'])

print(result['body']['items'][0]['DESC_KOR'])       # 바나나칩
print(result['body']['items'][0]['NUTR_CONT1'])
[결과값]

{'resultCode': '00', 'resultMsg': 'NORMAL SERVICE.'} {'pageNo': 1, 'totalCount': 1, 'numOfRows': 3, 'items': [{'DESC_KOR': '바나나칩', 'SERVING_WT': '30', 'NUTR_CONT1': '49.50', 'NUTR_CONT2': '5.40', 'NUTR_CONT3': '0.30', 'NUTR_CONT4': '3.00', 'NUTR_CONT5': '3.30', 'NUTR_CONT6': '0.60', 'NUTR_CONT7': '0.00', 'NUTR_CONT8': '2.70', 'NUTR_CONT9': '0.00', 'BGN_YEAR': '2017', 'ANIMAL_PLANT': '(유)돌코리아'}]} 바나나칩 49.50

 

  • "새우깡"의 식품정보 가져오기
# Python3 샘플 코드 #
import requests

# 일반 인증키 (Decoding) 사용
apikey = '공공데이터 포털에서 "활용신청"을 통해서 받은 API KEY'

url = 'http://apis.data.go.kr/1471000/FoodNtrIrdntInfoService1/getFoodNtrItdntList1'

# 새우깡
#  (식품이름, 열량, 1회제공량, 구축년도) DataFrame 형태로 반환
params ={'serviceKey' : apikey,
         'desc_kor' : '새우깡',
         'type' : 'json' }

response = requests.get(url, params=params)

if response.status_code == 200:
    result = response.json()
    print(result)
else:
    print('실패 : ', response.status_code)
[결과값]

{'header': {'resultCode': '00', 'resultMsg': 'NORMAL SERVICE.'}, 'body': {'pageNo': 1, 'totalCount': 8, 'numOfRows': 10, 'items': [{'DESC_KOR': '과자,DHA새우깡', 'SERVING_WT': '30', 'NUTR_CONT1': '151.20', 'NUTR_CONT2': '18.12', 'NUTR_CONT3': '1.80', 'NUTR_CONT4': '7.35', 'NUTR_CONT5': 'N/A', 'NUTR_CONT6': '210.00', 'NUTR_CONT7': 'N/A', 'NUTR_CONT8': 'N/A', 'NUTR_CONT9': 'N/A', 'BGN_YEAR': '2006', 'ANIMAL_PLANT': '농심'}, {'DESC_KOR': '과자,DHA새우깡', 'SERVING_WT': '30', 'NUTR_CONT1': '45.36', 'NUTR_CONT2': '5.44', 'NUTR_CONT3': '0.54', 'NUTR_CONT4': '2.20', 'NUTR_CONT5': '0.30', 'NUTR_CONT6': '63.00', 'NUTR_CONT7': '0.00', 'NUTR_CONT8': '0.00', 'NUTR_CONT9': '0.00', 'BGN_YEAR': '2017', 'ANIMAL_PLANT': '농심'}, {'DESC_KOR': '새우깡', 'SERVING_WT': '30', 'NUTR_CONT1': '146.67', 'NUTR_CONT2': '20.00', 'NUTR_CONT3': '2.00', 'NUTR_CONT4': '6.67', 'NUTR_CONT5': '1.33', 'NUTR_CONT6': '180.00', 'NUTR_CONT7': '0.00', 'NUTR_CONT8': '2.13', 'NUTR_CONT9': '0.00', 'BGN_YEAR': '2015', 'ANIMAL_PLANT': '농심'}, {'DESC_KOR': '새우깡', 'SERVING_WT': '30', 'NUTR_CONT1': '44.00', 'NUTR_CONT2': '6.00', 'NUTR_CONT3': '0.60', 'NUTR_CONT4': '2.00', 'NUTR_CONT5': '0.30', 'NUTR_CONT6': '54.00', 'NUTR_CONT7': '0.00', 'NUTR_CONT8': '0.64', 'NUTR_CONT9': '0.00', 'BGN_YEAR': '2017', 'ANIMAL_PLANT': '농심'}, {'DESC_KOR': '매운새우깡', 'SERVING_WT': '30', 'NUTR_CONT1': '146.67', 'NUTR_CONT2': '20.00', 'NUTR_CONT3': '2.00', 'NUTR_CONT4': '6.67', 'NUTR_CONT5': '1.33', 'NUTR_CONT6': '213.33', 'NUTR_CONT7': '0.00', 'NUTR_CONT8': '2.13', 'NUTR_CONT9': '0.00', 'BGN_YEAR': '2015', 'ANIMAL_PLANT': '농심'}, {'DESC_KOR': '매운새우깡', 'SERVING_WT': '30', 'NUTR_CONT1': '44.00', 'NUTR_CONT2': '6.00', 'NUTR_CONT3': '0.60', 'NUTR_CONT4': '2.00', 'NUTR_CONT5': '0.60', 'NUTR_CONT6': '64.00', 'NUTR_CONT7': '0.00', 'NUTR_CONT8': '0.64', 'NUTR_CONT9': '0.00', 'BGN_YEAR': '2017', 'ANIMAL_PLANT': '농심'}, {'DESC_KOR': '쌀새우깡', 'SERVING_WT': '30', 'NUTR_CONT1': '150.00', 'NUTR_CONT2': '19.50', 'NUTR_CONT3': '1.50', 'NUTR_CONT4': '7.50', 'NUTR_CONT5': '1.50', 'NUTR_CONT6': '157.50', 'NUTR_CONT7': '0.00', 'NUTR_CONT8': '2.17', 'NUTR_CONT9': '0.00', 'BGN_YEAR': '2015', 'ANIMAL_PLANT': '농심'}, {'DESC_KOR': '쌀새우깡', 'SERVING_WT': '30', 'NUTR_CONT1': '45.00', 'NUTR_CONT2': '5.85', 'NUTR_CONT3': '0.45', 'NUTR_CONT4': '2.25', 'NUTR_CONT5': '0.45', 'NUTR_CONT6': '47.25', 'NUTR_CONT7': '0.00', 'NUTR_CONT8': '0.65', 'NUTR_CONT9': '0.00', 'BGN_YEAR': '2017', 'ANIMAL_PLANT': '농심'}]}}

 

# 식품이름(DESC_KOR)
# 열량 (kcal) (NUTR_CONT1)
# 1회제공량 (g) (SERVING_WT)
# 구축년도 (BGN_YEAR)

df = pd.DataFrame(result['body']['items'])

# ===========================================================================
# Column Select
# Case1
df2 = df[['DESC_KOR', 'NUTR_CONT1', 'SERVING_WT', 'BGN_YEAR']]
# ===========================================================================


# ===========================================================================
# Column Rename
# Case1
df2.columns = ['식품이름', '열량 (kcal)', '1회제공량 (g)', '구축년도']
# Case2
newcols = {'DESC_KOR' : '식품이름', 'NUTR_CONT1' : '열량 (kcal)', 'SERVING_WT' : '1회제공량 (g)', 'BGN_YEAR' : '구축년도'}
df2.rename(columns=newcols, inplace=True)
# ===========================================================================

df2

 

  • 식품정보 불러오기 기능 함수로 구현
def Call_API():
    import requests
    import pandas as pd

    _desc_kor = str(input('식품이름을 입력해주세요=>'))
    print(f'{_desc_kor}를 입력하셨습니다')

    # 일반 인증키 (Decoding) 사용
    apikey = '공공데이터 포털에서 "활용신청"을 통해서 받은 API KEY'

    url = 'http://apis.data.go.kr/1471000/FoodNtrIrdntInfoService1/getFoodNtrItdntList1'

    # 새우깡
    #  (식품이름, 열량, 1회제공량, 구축년도) DataFrame 형태로 반환
    params ={'serviceKey' : apikey,
             'desc_kor' : _desc_kor,
             'type' : 'json' }

    # 데이터 가져오기
    response = requests.get(url, params=params)

    if response.status_code == 200:
        result = response.json()   # response => json 형식으로 변환
        # print(result)
        if 'items' in result['body'].keys():
        # if result['body']['totalCount'] > 0:
            items = result['body']['items']

            # DataFrame으로 변환
            df = pd.DataFrame(items)
            # 컬럼 조회 (['DESC_KOR', 'NUTR_CONT1', 'SERVING_WT', 'BGN_YEAR'])
            df = df[['DESC_KOR', 'NUTR_CONT1', 'SERVING_WT', 'BGN_YEAR']]
            # 컬럼이름 변경 (['식품이름', '1회 제공량', '열량', '조사년도'])
            df.columns=['식품이름', '1회 제공량', '열량', '조사년도']

            return df
        else:
            # return 'f{_desc_kor}을 조회하지 못했습니다.'
            return []
    else:
        return '실패 : ', response.status_code
Call_API()

 

 

 

[추가자료] https://realpython.com/python-requests/