こんにちは!kossyです!
さて、今回はOpenWeatherMapAPIをRailsから叩いて、JSONとして返却する方法について、
ブログに残してみたいと思います。
環境
Rails 6.0.2.1
Ruby 2.5.1
MacOS Mojave
API keyの取得
上記の記事を参考に、API keyを取得してください。
取得できたら、
$ cd your-rails-app $ EDITOR="vi" bin/rails credentials:edit
でcredentialsの設定を行います。
# aws: # access_key_id: 123 # secret_access_key: 345 # Used as the base secret for all MessageVerifiers in Rails, including the o ne protecting cookies. secret_key_base: 1234567812345678 weather_map_id: your api key
これで準備完了です。
コード全晒し
searchメソッドの返り値は、引数keywordの地名の天気5日間分の情報が返ります。
lib/open_weather_map_client.rb require 'net/https' class OpenWeatherMapClient include Singleton URL = 'http://api.openweathermap.org/data/2.5' API_KEY = Rails.application.credentials.dig(:weather_map_id) def initialize @uri = URI.parse URL @http = Net::HTTP.new @uri.host, @uri.port end def search(keyword) create_request(keyword) @res['list'].map do |list| main_info = list['main'] weather_info = list['weather'] { time: list['dt'], temp: main_info['temp'], feels_like: main_info['feels_like'], temp_min: main_info['temp_min'], temp_max: main_info['temp_max'], pressure: main_info['pressure'], humidity: main_info['humidity'], main_weather: weather_info[0]['main'], description: weather_info[0]['description'], clouds: list['clouds']['all'], wind: list['wind']['speed'], } end end private def create_request(keyword) req = Net::HTTP::Get.new @uri.path + "/forecast?q=#{keyword},jp&units=metric&APPID=#{API_KEY}" _res = @http.request req @res = JSON.parse(_res.body) end end
返り値はこんな感じ。
もっと値は受け取れますが、必要そうなものだけピックアップしてます。
=> [ {:time=>1583226000, # UNIXタイムで返る。 Timeクラスのatメソッドで、datetimeに変換できる。 Time.at(1583226000) => 2020-03-03 18:00:00 +0900 :temp=>12.22, # 気温 :feels_like=>8.54, # 体感気温 :temp_min=>12.22, # 最低気温 :temp_max=>12.22, # 最高気温 :pressure=>1020, # 気圧 :humidity=>65, # 湿度 :main_weather=>"Clouds", # メインの天気 :description=>"overcast clouds", # 説明 :clouds=>100, # 雲の濃度 :wind=>3.9}, # 風速 ]
あとはcontrollerのアクション内で @weathersOpenWeatherMapClient.instance.search('Tokyo') 的な変数を定義してviewに渡してやればOKかと思います。
libファイルの読み込み方法は
qiita.com
上記の記事が参考になるかと思います。