LoginSignup
1
6

More than 5 years have passed since last update.

google shorter apiを利用した短縮URL生成スクリプト

Posted at

短縮URLを生成するスクリプトを作りました。

googleのAPIでしたら1日に100万リクエストまで行けるので他の短縮URLサービスより高可用性があります。
例えば、bitlyでは100URL/分で1ヶ月あたり5000URLの制限があり厳しいです。

参考:https://www.quora.com/What-is-the-Bitly-API-rate-limit

API_KEYは以下URLから取得します。API_KEYの取得方法はその次のURLをご参考に。

APIキーの取得 | Google Maps API入門

長くてスミマセン。API_KEYの部分は取得したキーを入れます。

google-shorter.rb
#!/usr/bin/ruby

require 'json'
require 'net/http'

long_url = ARGV.shift

API_KEY = 'your api key'

url = "https://www.googleapis.com/urlshortener/v1/url?key=#{API_KEY}"
uri = URI.parse(url)

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

req = Net::HTTP::Post.new(uri.request_uri)
req["Content-Type"] = "application/json"
req.body = { longUrl: long_url}.to_json
res = http.request(req)

short = JSON.parse(res.body)['id']
print short

使い方。

ruby google-shorter.rb http://qiita.com

結果:
https://goo.gl/6giPj

gemを使用したい人は以下のほうが楽だと思います。ただ、単に短縮URLがほしいだけなら独自実装でも十分。

zigotto/googl: Google URL Shortener API in Ruby

参考

1
6
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
1
6