{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 데이터를 API로 가져와 본다 - 공공 데이터"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "REST API 방식으로 데이터를 불러 오도록 한다. 먼저 다음과 같은 절차로 신청한다.<br>\n",
    "\n",
    "1. 먼저 다음 사이트에 접속한다: www.data.go.kr \n",
    "2. 사이트에 가입하고 로그인 한다.\n",
    "3. 상단 탭에서: 데이터 셋 => 오픈 API로 들어간다\n",
    "4. \"상가(상권) 정보\"를 클릭하여 들아간다.\n",
    "5. \"활용신청\" 버튼을 클릭하고 신청 양식을 작성한다.\n",
    "   - \"활용목적\"은 \"참고자료\"로 선택해 둔다.\n",
    "   - \"상세기능정보\"는 모두 체크 선택해 둔다.\n",
    "   - \"동의합니다\"에 체크를 해 둔다.\n",
    "6. \"신청\" 버튼을 클릭해서 신청 완료. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "신청이 완료된 후 다음 순서로 인증키를 받아 두어야만 한다. <br>\n",
    " \n",
    "1. 마이페이지 => 오픈 API => 개발계정 => 방금 승인된 아이템을 통해서 \"개발계정 상세보기\"로 들어간다.\n",
    "2. \"일반 인증키\" 발급을 클릭해서 인증키를 발급 받는다.\n",
    "3. 인증키를 복사해 둔다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests as rq\n",
    "import bs4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "endpoint = \"http://apis.data.go.kr/B553077/api/open/sdsc\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "serviceKey = \"cgkaWV3IqPLhyq0klAJ88TMjU5JNZ3baxmWAcj%2FK18m630LgD%2Bqofc3qlw6NdxJaHjd5K%2BCrhxRlJ5RpNtac%2Fw%3D%3D\" # 본인의 인증키"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1. 지정 상권 조회"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\"바로 API\"에 대한 부가적인 설명은 다음 사이트에서 얻을 수 있다:  http://data.sbiz.or.kr/sdsc/p00006/go/o/main"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# \"바로 API\" 사용.\n",
    "# 지정 상권 조회.\n",
    "# key = 573.       #573아이디에 해당하는 상권\n",
    "parameterset = \"/baroApi?resId=storezone&key=573&ServiceKey=\" + serviceKey   #바로api로 시작  #주소는 한글파일에 정해져 있음"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Status = 200\n"
     ]
    }
   ],
   "source": [
    "url = endpoint + parameterset\n",
    "res = rq.get(url)              #이렇게 하면rest api접속\n",
    "\n",
    "print(\"Status = \" + str(res.status_code))   #status = 200으로 출력해보기 위해 문자결합"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 파싱하기"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b'<response>\\n\\t<header>\\n\\t\\t<description>\\xec\\x86\\x8c\\xec\\x83\\x81\\xea\\xb3\\xb5\\xec\\x9d\\xb8\\xec\\x8b\\x9c\\xec\\x9e\\xa5\\xec\\xa7\\x84\\xed\\x9d\\xa5\\xea\\xb3\\xb5\\xeb\\x8b\\xa8 \\xec\\xa3\\xbc\\xec\\x9a\\x94\\xec\\x83\\x81\\xea\\xb6\\x8c</description>\\n\\t\\t<columns>\\xec\\x83\\x81\\xea\\xb6\\x8c\\xeb\\xb2\\x88\\xed\\x98\\xb8,\\xec\\x83\\x81\\xea\\xb6\\x8c\\xeb\\xaa\\x85,\\xec\\x8b\\x9c\\xeb\\x8f\\x84\\xec\\xbd\\x94\\xeb\\x93\\x9c,\\xec\\x8b\\x9c\\xeb\\x8f\\x84\\xeb\\xaa\\x85,\\xec\\x8b\\x9c\\xea\\xb5\\xb0\\xea\\xb5\\xac\\xec\\xbd\\x94\\xeb\\x93\\x9c,\\xec\\x8b\\x9c\\xea\\xb5\\xb0\\xea\\xb5\\xac\\xeb\\xaa\\x85,\\xec\\x83\\x81\\xea\\xb6\\x8c\\xeb\\xa9\\xb4\\xec\\xa0\\x81,\\xec\\xa2\\x8c\\xed\\x91\\x9c\\xea\\xb0\\x9c\\xec\\x88\\x98,\\xec\\xa2\\x8c\\xed\\x91\\x9c\\xea\\xb0\\x92,\\xeb\\x8d\\xb0\\xec\\x9d\\xb4\\xed\\x84\\xb0\\xea\\xb8\\xb0\\xec\\xa4\\x80\\xec\\x9d\\xbc\\xec\\x9e\\x90</columns>\\n\\t\\t<resultCode>00</resultCode>\\n\\t\\t<resultMsg>NORMAL SERVICE</resultMsg>\\n\\t</header>\\n\\t<body>\\n\\t\\t<items name=\"getStoreZone\">\\n\\t\\t\\t<item>\\n\\t\\t\\t\\t<trarNo>573</trarNo>\\n\\t\\t\\t\\t<mainTrarNm>\\xeb\\xb6\\x80\\xec\\x82\\xb0 \\xea\\xb8\\x88\\xec\\xa0\\x95\\xea\\xb5\\xac \\xea\\xb5\\xac\\xec\\x84\\x9c\\xeb\\x8f\\x99\\xec\\x97\\xad</mainTrarNm>\\n\\t\\t\\t\\t<ctprvnCd>26</ctprvnCd>\\n\\t\\t\\t\\t<ctprvnNm>\\xeb\\xb6\\x80\\xec\\x82\\xb0\\xea\\xb4\\x91\\xec\\x97\\xad\\xec\\x8b\\x9c</ctprvnNm>\\n\\t\\t\\t\\t<signguCd>26410</signguCd>\\n\\t\\t\\t\\t<signguNm>\\xea\\xb8\\x88\\xec\\xa0\\x95\\xea\\xb5\\xac</signguNm>\\n\\t\\t\\t\\t<trarArea>66080.5</trarArea>\\n\\t\\t\\t\\t<coordNum>16</coordNum>\\n\\t\\t\\t\\t<coords>POLYGON ((129.09092 35.248544, 129.090527 35.248755, 129.089265 35.248054, 129.089212 35.247334, 129.088914 35.247291, 129.088755 35.24522, 129.089828 35.244913, 129.08994 35.246723, 129.091246 35.246667, 129.091377 35.246602, 129.091466 35.247503, 129.091906 35.247535, 129.092248 35.247604, 129.091985 35.248508, 129.091776 35.248483, 129.09092 35.248544))</coords>\\n\\t\\t\\t\\t<stdrDt>2015-12-17</stdrDt>\\n\\t\\t\\t</item>\\n\\t\\t</items>\\n\\t</body>\\n</response>\\n'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_res = res.content   #내용 가져오기\n",
    "my_res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "soup = bs4.BeautifulSoup(my_res, 'lxml')       # XML로 파싱.   #디폴트가 xml임   #상가정보옆에 써있음\n",
    "                                               # print(soup.prettify())도 하면 전체 출력."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'POLYGON ((129.09092 35.248544, 129.090527 35.248755, 129.089265 35.248054, 129.089212 35.247334, 129.088914 35.247291, 129.088755 35.24522, 129.089828 35.244913, 129.08994 35.246723, 129.091246 35.246667, 129.091377 35.246602, 129.091466 35.247503, 129.091906 35.247535, 129.092248 35.247604, 129.091985 35.248508, 129.091776 35.248483, 129.09092 35.248544))'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res = soup.find('coords')                      # coords: Polygon으로 나타내는 상권 좌표. \n",
    "                                               # 좌표값은 WGS84 좌표계로 WKT 포맷으로 POLYGON((위도 경도,~~)) 형식이다.\n",
    "res.text        #res에서 태그제외하고 내용만 뽑아봄"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. 행정구역 단위 상권조회."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# \"바로 API\" 사용.\n",
    "parameterset = \"/baroApi?resId=storezone&catId=dong&divId=adongCd&key=1168069000&ServiceKey=\" + serviceKey  #바로api 키에 행정구역해당단위 넣음 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Status = 200\n"
     ]
    }
   ],
   "source": [
    "url = endpoint + parameterset\n",
    "res = rq.get(url)\n",
    "print(\"Status = \" + str(res.status_code))   #status = 200으로 출력해보기 위해 문자결합"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 파싱하기"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "my_res = res.content           #내용 가져오기"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "soup = bs4.BeautifulSoup(my_res, 'lxml')       # XML 파싱.\n",
    "                                               #print(soup.prettify())하면 전체 출력."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'POLYGON ((127.045483 37.477389, 127.045158 37.478072, 127.04694 37.478392, 127.046881 37.478599, 127.044704 37.478194, 127.04518 37.477216, 127.047481 37.474991, 127.047784 37.475182, 127.046868 37.476058, 127.047227 37.476304, 127.046929 37.47659, 127.046582 37.476353, 127.045483 37.477389))'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res = soup.find('coords')                      # coords: Polygon으로 나타내는 상권 좌표. \n",
    "                                               # 좌표값은 WGS84 좌표계로 WKT 포맷으로 POLYGON((위도 경도,~~)) 형식이다.\n",
    "res.text        #res에서 태그제외하고 내용만 뽑아봄"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3. 건물단위 상가업소 조회."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# \"바로 API\" 사용.                         #이거 키값일것\n",
    "parameterset = \"/baroApi?resId=store&catId=building&key=1123010300107370002030949&ServiceKey=\" + serviceKey"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Status = 200\n"
     ]
    }
   ],
   "source": [
    "url = endpoint + parameterset\n",
    "res = rq.get(url)\n",
    "print(\"Status = \" + str(res.status_code))    #status = 200으로 출력해보기 위해 문자결합"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 파싱하기"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "my_res = res.content     #내용 가져오기"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "soup = bs4.BeautifulSoup(my_res, 'lxml')       # XML 파싱.\n",
    "                                               # print(soup.prettify())로 전체 출력."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<bizesnm>주봉산장뇌산삼</bizesnm>,\n",
       " <bizesnm>국제축산</bizesnm>,\n",
       " <bizesnm>송원당약국</bizesnm>,\n",
       " <bizesnm>삼덕약업사</bizesnm>,\n",
       " <bizesnm>한솔건재약업사</bizesnm>]"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res = soup.find_all('bizesnm')                 # 건물의 비즈니스 검색.   #건물단위니까 bizesnm\n",
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "주봉산장뇌산삼\n",
      "국제축산\n",
      "송원당약국\n",
      "삼덕약업사\n",
      "한솔건재약업사\n"
     ]
    }
   ],
   "source": [
    "for x in res:     \n",
    "    print(x.text)                              # 출력."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}