Last active
November 2, 2016 04:21
-
-
Save dproject21/77d1adeb30b47c7f10dc20bebd0e046e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
class Resas: | |
__ENDPOINT = "https://opendata.resas-portal.go.jp/" | |
__API_VER = "api/v1-rc.1/" | |
__address = "" | |
def __init__(self, api_key): | |
self.api_key = api_key | |
self.headers = {"X-API-KEY": api_key} | |
self.pref = {} | |
self.__address = self.__ENDPOINT + self.__API_VER | |
def __get_result(self, address): | |
url = self.__ENDPOINT + self.__API_VER + address | |
response = requests.get(url, headers=self.headers) | |
result = json.loads(response.text)["result"] | |
return result | |
def get_data(self, api_name, param): | |
p = "?" | |
for k, v in param.items(): | |
p = p + k + "=" + str(v) + "&" | |
if len(p) == 2: | |
p = "" | |
else: | |
p = p[0:len(p) - 1] | |
address = api_name + p | |
result = self.__get_result(address) | |
return result | |
def load_pref(self): | |
address = "prefectures" | |
result = self.__get_result(address) | |
dic = {} | |
for r in result: | |
dic[r['prefName']] = r['prefCode'] | |
self.pref = dic | |
def get_city(self, pref_code): | |
address = "cities?prefCode=" + str(pref_code) | |
result = self.__get_result(address) | |
dic = {} | |
for r in result: | |
dic[r['cityName']] = r['cityCode'] | |
return dic | |
resas = Resas("") #APIキーを入れてinitializeします。 | |
resas.load_pref() | |
pref_code = resas.pref['東京都'] | |
print(pref_code) | |
city = resas.get_city(pref_code) | |
city_code = city['渋谷区'] | |
print(city_code) | |
param = {'prefCode': pref_code, 'cityCode': city_code} | |
results = resas.get_data("municipality/foundation/perYear", param) | |
print(results) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment