LoginSignup
8

More than 5 years have passed since last update.

Google Indexing APIのRubyのサンプル

Posted at

概要

Googleのお仕事検索が始まってIndexing APIを試してみました。

公式にはRubyのサンプルがなかったので載せておきます。

準備

公式を読めば分かりますが、準備の流れをざっくり流れを書いておきます。

  • Google API consoleでプロジェクトを作成する。既にあればもちろんそれでもOK。
  • IndexingAPIを有効にする。
  • メニュの「IAMの管理」>「サービス アカウント」に行ってサービスアカウントを作成する。この時JSON形式で秘密鍵をダウンロードしておく。
  • 作成したサービスアカウントのメールアドレス(自動で生成されるもの)をサーチコンソールで対象サイトの所有者にする。

以上で完了です。

Rubyのサンプル

google-auth-library-rubyが必要です。

gem install googleauth

コードはこんな感じ。service_account.jsonは先ほどダウンロードした秘密鍵を含むデータです。

require 'googleauth'

authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open('./service_account.json'),
  scope: ["https://www.googleapis.com/auth/indexing"]
)

tokens = authorizer.fetch_access_token!

uri = URI('https://indexing.googleapis.com/v3/urlNotifications:publish')
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = req['Accept'] = 'application/json'
req['Authorization'] = 'Bearer ' + tokens['access_token']
req.body = {
  url: "http://example.com/jobs/42",
  type: 'URL_UPDATED'
}.to_json
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  http.request(req)
end

puts res.body

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
8