ソースコードで学ぶWebプログラミング

[Ruby]API接続の基本を確認する[外部サーバ通信]

Web APIとはWebサイトの機能を外部から利用できるようにしたものです。提供された機能で外部の開発者が自発的に新しいサービスを展開するなどの相乗効果が期待されます。このページではRubyでAPI接続をする際の基本となる概念、コーディングのポイントを説明しています。

RubyでGET送信する方法

Rubyでurlへアクセスするには、標準ライブラリのnet/httpが使用できます。GET送信するデータは、URI.encode_www_form()でエンコードしてから、.queryに設定します。GETリクエストはNet::HTTP::Get.newで作成でき、リクエストを行なうURIは.request_uriで指定、第二引数でヘッダー情報を設定できます。

注意点としてhttps通信を行なう場合は、.use_sslをtrueに設定する必要があります。SSL証明書の検証を行わない場合は、.verify_modeに OpenSSL::SSL::VERIFY_NONEを設定します。

#!/usr/bin/ruby # coding: utf-8 # urlアクセス require 'net/http' # uri用のモジュール require 'uri' # 取得先URL URL = 'http://example.com/' def file_get_contents(url, data, limit=5) u = URI.parse(url) u.query = URI.encode_www_form(data) http = Net::HTTP.new(u.host) if u.scheme=='https' http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end # GETリクエスト req = Net::HTTP::Get.new(u.request_uri,{ 'User-Agent'=>'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)' }) res = http.start do |h| h.request(req) end case res when Net::HTTPSuccess res.body when Net::HTTPRedirection file_get_contents(res['location'], data, limit-1) else res.value end end # 送信するデータ data = { name: '名前' } body = file_get_contents(URL, data)

RubyでPOST送信する方法

RubyでデータをPOST送信する場合は、Net::HTTP::Post.newでリクエストを作成し、.set_form_data()メソッドで送信データを設定するだけです。GETの場合と同じように、第二引数でリクエストのヘッダー情報を設定できます。

#!/usr/bin/ruby # coding: utf-8 # urlアクセス require 'net/http' # uri用のモジュール require 'uri' # 取得先URL URL = 'http://example.com/' def file_get_contents(url, data, limit=5) u = URI.parse(url) http = Net::HTTP.new(u.host) if u.scheme=='https' http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end # GETリクエスト req = Net::HTTP::Post.new(u.request_uri,{ 'User-Agent'=>'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)' }) req.set_form_data(data) res = http.start do |h| h.request(req) end case res when Net::HTTPSuccess res.body when Net::HTTPRedirection file_get_contents(res['location'], data, limit-1) else res.value end end # 送信するデータ data = { name: '名前' } body = file_get_contents(URL, data)

RubyでCOOKIE送信する方法

Webサイトでログインが必要な画面などでは、クッキーと呼ばれるブラウザの管理データを送受信する必要があります。一般的に必要となるクッキーデータは、ログイン時のレスポンスヘッダーにあります。

先ほど作成したfile_get_contents()を少し改良して、POST、GETに対応して送信できるようにしています。クッキーはレスポンスヘッダーのSet-Cookieで発行されるので、そのデータを取得して次リクエストで送信しています。

#!/usr/bin/ruby # coding: utf-8 # urlアクセス require 'net/http' # uri用のモジュール require 'uri' # 取得先URL URL = 'http://example.com/login' def file_get_contents(url, data, limit=5) return 'too many HTTP redirects' if limit==0 if data[:method]=='POST' u = URI.parse(url) else u = URI.parse(url) u.query = URI.encode_www_form(data[:data]) end http = Net::HTTP.new(u.host,u.port) if u.scheme=='https' http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end hds = { 'User-Agent'=>'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)' } if data.key?(:headers) hds.merge!(data[:headers]) end if data[:method]=='POST' req = Net::HTTP::Post.new(u.request_uri,hds) req.set_form_data(data[:data]) else req = Net::HTTP::Get.new(u.request_uri,hds) end begin res = http.start do |h| h.request(req) end # レスポンスヘッダーから発行されたクッキーを取得 cookie = '' res.each_header do |key,val| if key=='set-cookie' cookie = val end end case res when Net::HTTPSuccess return res.body,cookie when Net::HTTPRedirection file_get_contents(res['location'], data, limit-1) else return res.value end rescue => e return e.to_s end end # POST送信でログイン data = { data: { id: 'value', pass: 'value' }, method: 'POST' } # クッキー取得 body,cookie = file_get_contents(URL, data) # クッキーを送信 data = { data: { id: 'value', pass: 'value' }, method: 'GET', headers: { 'Cookie'=>cookie.gsub(/, /,'; ') } } body = file_get_contents(URL, data)

RubyでBASIC認証する方法

BASIC認証とは、Webサーバで行われるアクセス制限で、一般的に.htaccessと.htpasswdで設定を行います。Rubyでは、リクエストの.basic_authメソッドでBASIC認証のIDとパスワードを設定できます。

#!/usr/bin/ruby # coding: utf-8 require 'net/http' require 'uri' # 取得先URL URL = 'http://example.com/' # BASIC認証 ID BASIC_ID = '***' # BASIC認証 パスワード BASIC_PW = '***' def file_get_contents(url, data, limit=5) u = URI.parse(url) u.query = URI.encode_www_form(data) http = Net::HTTP.new(u.host) if u.scheme=='https' http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end req = Net::HTTP::Get.new(u.request_uri,{ 'User-Agent'=>'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)' }) # BASIC認証の設定 req.basic_auth(BASIC_ID, BASIC_PW) res = http.start do |h| h.request(req) end case res when Net::HTTPSuccess res.body when Net::HTTPRedirection file_get_contents(res['location'], data, limit-1) else res.value end end data = { name: '名前' } body = file_get_contents(URL, data)