GoogleSpreadsheet(スプレッドシート)をWeb APIにして公開、RubyでGETしようとするとリダイレクトさせないとエラーになってしまいます。
302 Moved Temporarily
が返ってきてしまいます。
これに対応します。
GoogleSpreadsheetのAPIのredirectに対応する方法
結論から書くと、rubyで以下のように書くことでredirect先のjsonなどのデータを返してくれます。
responseが302だった場合にその先に再度getする、という処理です。
google_uri = URI.parse(GOOGLE_SP_URL) response = Net::HTTP.get_response(google_uri) if response.code == "302" response = Net::HTTP.get_response(URI.parse(response.header['location'])) end result = JSON.parse(response.body)
なぜスプレッドシートはリダイレクト先にデータを置くのか?
この理由については公式ドキュメントにも書かれています。
セキュリティ面を考慮してのことのようですね。
For security reasons, content returned by the Content service isn't served from script.google.com, but instead redirected to a one-time URL at script.googleusercontent.com. This means that if you use the Content service to return data to another application, you must ensure that the HTTP client is configured to follow redirects. For example, in the cURL command line utility, add the flag -L. Check the documentation for your HTTP client for more information on how to enable this behavior.
ワンタイムURLで取得させるようにしているみたいです。
https://developers.google.com/apps-script/guides/content#redirects