공공데이터 포털API사용하기

qq·2023년 8월 7일

의약품 데이터들을 쓰기 위해 공공데이터 포털의 Open Api를 적용해보는 프로젝트를 해보았다.

  • 사용한 api 식품의약품안전처_의약품 낱알식별 정보: https://www.data.go.kr/data/15057639/openapi.do 식품의약품안전처_의약품개요정보(e약은요) https://www.data.go.kr/data/15075057/openapi.do 건강보험심사평가원_의약품성분약효정보조회서비스 https://www.data.go.kr/tcs/dss/selectApiDataDetailView.do?publicDataPk=15021027
  • code
    # Create your views here.
    import json
    from django.test import TestCase
    import requests
    from django.http import JsonResponse
    
    #발급받은 API 키
    def get_data_from_api(request):
        # 발급받은 API 키를 여기에 입력하세요.
        api_key = 'rhyX4grma%2BTw7Er3sp5iXzXBEb5Ayy95cfIG7CkI89HNbql9iUNNXPOSrrPt98wdu7doArvn0ZwCUyj1jS9GMg%3D%3D'
        base_url = 'http://apis.data.go.kr/1471000/MdcinGrnIdntfcInfoService01/getMdcinGrnIdntfcInfoList01'
    
    # 요청 파라미터 설정
        params = {
            'serviceKey': api_key,
            'pageNo': '1',
            'numOfRows': '100',
            'type': 'json',
            'item_name': '아스피린',
        }
    
        # API 호출
        response = requests.get(base_url, params=params, timeout=10)
    
    # 데이터 값 출력해보기
    #contents = response.text
    
    #json_ob = json.loads(contents)
    #print(json_ob)
    #print(type(json_ob))
    
        # 응답 데이터 확인
        # 응답 데이터 확인
        if response.status_code == 200:
            try:
                data = response.json()
                # 원하는 작업을 수행하세요.
                items = data.get('body', {}).get('items', [])
                item_names = [item.get('ITEM_NAME') for item in items]
                return JsonResponse({'item_names': item_names})
            except json.JSONDecodeError as e:
                return JsonResponse({'error': '응답 데이터가 올바른 JSON 형식이 아닙니다.'})
        else:
            return JsonResponse({'error': 'API 호출에 실패하였습니다.'})
    # Create your views here.
    import json
    from django.test import TestCase
    import requests
    from django.http import JsonResponse
    
    #발급받은 API 키
    def get_data_from_api(request):
        # 발급받은 API 키를 여기에 입력하세요.
        api_key = 'rhyX4grma%2BTw7Er3sp5iXzXBEb5Ayy95cfIG7CkI89HNbql9iUNNXPOSrrPt98wdu7doArvn0ZwCUyj1jS9GMg%3D%3D'
        base_url = 'http://apis.data.go.kr/1471000/DrbEasyDrugInfoService/getDrbEasyDrugList'
    
    # 요청 파라미터 설정
        params = {
            'serviceKey': api_key,
            'pageNo': '1',
            'numOfRows': '100',
            'type': 'json',
        }
    
        # API 호출
        response = requests.get(base_url, params=params, timeout=10)
        print(response)
    
    # 데이터 값 출력해보기
    #contents = response.text
    
    #json_ob = json.loads(contents)
    #print(json_ob)
    #print(type(json_ob))
    
        # 응답 데이터 확인
        # 응답 데이터 확인
        if response.status_code == 200:
            try:
                data = response.json()
                print(data)
                # 원하는 작업을 수행하세요.
                items = data.get('body', {}).get('items', [])
                item_names = [item.get('useMethodQesitm') for item in items]
                return JsonResponse({'useMethodQesitm': item_names})
            except json.JSONDecodeError as e:
                return JsonResponse({'error': '응답 데이터가 올바른 JSON 형식이 아닙니다.'})
        else:
            return JsonResponse({'error': 'API 호출에 실패하였습니다.'})

결과창


트러블슈팅

그런데 계속 JSON decode에러가 떠서 파싱이 되었다가 안됬다가 그래서 문제가 생기는데 해결을 못했다 ㅜㅜ

profile
백엔드 개발자

0개의 댓글