Skip to content

Instantly share code, notes, and snippets.

@nmaruy27
Created November 18, 2019 03:50
Show Gist options
  • Save nmaruy27/bfb5dddb0514df5dcebde10254d61c3f to your computer and use it in GitHub Desktop.
Save nmaruy27/bfb5dddb0514df5dcebde10254d61c3f to your computer and use it in GitHub Desktop.
resas-apiから都道府県・市区町村データを取得するrakeタスク
require 'net/http'
require 'json'
require 'uri'
namespace :resas_api do
desc "get pref data from resas-api"
task get_prefecture: :environment do
API_URL = 'https://opendata.resas-portal.go.jp/api/v1/prefectures'
json = get_data(API_URL)
json['result'].each do |pref_data|
Prefecture.create({pref_code: pref_data["prefCode"], pref_name: pref_data["prefName"]})
end
end
desc "get city data from resas-api"
task get_city: :environment do
API_URL = 'https://opendata.resas-portal.go.jp/api/v1/cities?prefCode='
Prefecture.all.each do |pref|
json = get_data("#{API_URL}#{pref.pref_code}")
json['result'].each do |city_data|
City.create({
pref_code: city_data['prefCode'],
city_code: city_data['cityCode'],
city_name: city_data['cityName'],
big_city_flag: city_data['bigCityFlag']
})
end
end
end
def get_data(url)
pp "URL : #{url}"
uri = URI(url)
req = Net::HTTP::Get.new(uri)
req['X-API-KEY'] = 'APIキー'
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') {|http|
http.request(req)
}
JSON.parse(res.body)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment