LoginSignup
14
11

More than 5 years have passed since last update.

Googleの翻訳APIをRubyから叩いてみる

Posted at

前準備

Google Cloud Platform コンソールの API マネージャ にいって 認証情報 から適当にキーを作ってください。

作成したら以下図な感じになっているはずなので キー に表示されている文字列をコピーします。プログラム中で使います。

image

実装

test_translation.rb
require 'net/http'
require 'uri'
require 'json'

def translate q
  url = URI.parse('https://www.googleapis.com/language/translate/v2')
  params = {
    q: q,
    target: "ja",
    source: "en",
    key: "<ここにキーをペースト>"
  }
  url.query = URI.encode_www_form(params)
  res = Net::HTTP.get_response(url)
  JSON.parse(res.body)["data"]["translations"].first["translatedText"]
end

puts translate "I'm trying to use the google translation api."
実行結果
$ ruby test_translation.rb
私はGoogle翻訳のAPIを使用しようとしています。

参考情報

ドキュメント

お値段

https://cloud.google.com/translate/pricing
image

文字数で課金なんですね。

14
11
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
14
11