0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

法人番号APIをたたいて、RailsのDBに保存する(バルクインサートではないが。。。)

0
Posted at

APIを叩く

法人番号API:
https://www.houjin-bangou.nta.go.jp/webapi/kyuusiyousyo.html

上記サイトに記載されているが、利用にあたってアプリケーションIDの発行を申請する必要がある。
詳しくは、HPを。。。

https://api.houjin-bangou.nta.go.jp/<バージョン番号>/diff?id=<アプリケーションIDを入れる>&from=2019-04-03&to=2019-04-03&type=12

のように期間指定してあげて、URLを送ると


<updateDate>2019-04-03</updateDate>
<changeDate>2015-10-05</changeDate>
<name>法人番号株式会社</name>
<nameImageId/>
<kind>30124</kind>
<prefectureName>東京都</prefectureName>
<cityName>千代田区</cityName>
<streetNumber>一番町99番地111</streetNumber>
<prefectureCode>13</prefectureCode>
<cityCode>1010</cityCode>
<postCode>101010101</postCode>
<successorCorporateNumber/>
<changeCause/>
<assignmentDate>2015-10-05</assignmentDate>
<furigana>ほうじんばんごう</furigana>

---中略---

<updateDate>2019-04-03</updateDate>
<changeDate>2017-10-19</changeDate>
<name>HHH HOUJIN株式会社</name>
<nameImageId/>
<kind>301124</kind>
<prefectureName>東京都</prefectureName>
<cityName>千代田区</cityName>
<streetNumber>大手町123丁目11番2321号大手町セカンドサーキュレートタワー4階</streetNumber>
<addressImageId/>
<prefectureCode>13</prefectureCode>
<cityCode>1014</cityCode>
<postCode>124124124</postCode>
<assignmentDate>2017-02-28</assignmentDate>
<furigana>トリプルエイチ</furigana>

※数字は適当、&だいぶ省略してます。
のように返ってくるのでこれをJSON形式に変換して、DBにブッコム。

データ保存 & 更新

コントローラーにメソッドを作って、viewから呼び出す。
コードはリファクタリングしてないので、いらないところとか、汚いところありますがご愛嬌で

corporation_number_controller.rb
def index
    # viewで"update_corp_num"とういparamsを送ってあげて、
    # もしparamsの値がそれならupdate_corporate_numberメソッドを呼び出す
    if params[:update_corp_num]
      update_corporate_number(params[:q])
      return
    end
      
    @q = CorporateNumber.all.order(corporate_number: :desc)
    -- 中略 --
  end
corporation_numbers_controller.rb
def update_corporate_number(params_q)
    CorporateNumber.delete_all
    
# どの期間で法人番号情報を取ってくるかを指定
# 日付指定が2桁で指定仕上げる必要があったので'%02' % ~ を入れている
    today = Date.today.months_ago(1)
    date = today.year.to_s + "-" + ('%02d' % today.month.to_s) + "-" + ('%02d' % today.day.to_s)
    from_date_i = from_date.year.to_s + "-" + ('%02d' % today.month.to_s) + "-" + ('%02d' % today.day.to_s)
    
 
# APIをたたいて情報を取得
# APIを叩く = http://...形式でリクエストを送って「情報くれ」ってAPIサーバーに伝えること
# (リクエストURIをchromeのURLの場所に貼り付け&Enterでリスポンスみれます)
# 今回貼り付けたのは完璧なURIじゃないので見れませんが。。。

    uri = URI.parse("https://api.houjin-bangou.nta.go.jp/<バージョン番号>/diff?id=<アプリケーションID>&from=#{date}&to=#{date}&type=12")
    resp = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|

    # よくわからないが、下記二行はつけないとダメらしい(詳しくわかる方教えてください)
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      http.get(uri)
    end
    # jsonの値がresultに入っている
    result = ActiveSupport::XmlMini.parse(resp.body)
    ary = []
    result["corporations"]["corporation"].each do |item|
  
      cnum_company_name = item["name"].values.join
      cnum_company_prefecture = item["prefectureName"].values.join
      cnum_company_city = item["cityName"].values.join
      cnum_company_street = item["streetNumber"].values.join
      cnum_zipcode = item["postCode"].values.join.to_i
      cnum_corporate_num = item["corporateNumber"].values.join.to_i

#  値がnilで入れられませんってエラーが出たので入れている
# 今思えば、compactでやったほうがよかったのかも??。。。
      next if cnum_company_name.nil?
      next if cnum_company_prefecture.nil?
      next if cnum_zipcode.nil?
      next if cnum_corporate_num.nil?
     
# 上で作った配列にそれぞれ入れていく      
      ary << CorporateNumber.new(
        corporate_number: cnum_corporate_num,
        company_name_jp: cnum_company_name,
        company_address_jp: cnum_company_prefecture + " " + cnum_company_city + " " + cnum_company_street,
        company_name_jp_kana: "ふりがな",
        insert_user_id: 1,
        update_user_id: 1,
        update_date: Time.now,
        insert_date: Time.now
        )
      end
      CorporateNumber.import hoge
      redirect_to action: 'index'
  end

今回のでは、一応データ更新はできたが、更新時間が長すぎてtimeoutでアプリケーションが見れなくなってしまう。
なので、リファクタリングで処理時間を短くする必要がある。例えば、今回のはSQL文が一回ごとに発行されてしまうので、バルクインサートを使って一括で入れてあげるとか、each_slice(1000)&sleep(1)を使って1000件づつ入れてあげるとか。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?