SimpleOAuthでAPI呼び出し
移転しました →
TwitterAPIのRuby用ラッパーのソース(sferik/twitter )を読んでいてSimpleOAuthというライブラリを知ったので、はてなブックマークのAPIを例にしてちょっとした使い方の例を書いてみます。
はてなブックマークAtomAPI - Hatena Developer Center
はてなの公式ドキュメントではOAuthライブラリを使った実装のサンプルが紹介されています。OAuthライブラリとSimpleOAuthの書き方の違いを見るために、あるURLのサイトをブックマークする場合について2パターン書いてみました。
個人的にはSimpleOAuthが名前通りシンプルで好きです。
OAuthではてなブックマーク
def create_hatena_bookmark(url) @consumer = OAuth::Consumer.new( ENV['HATENA_CONSUMER_KEY'], ENV['HATENA_CONSUMER_SECRET'], site:'', request_token_path: 'https://www.hatena.com/oauth/initiate', access_token_path: 'https://www.hatena.com/oauth/token', authorize_path: 'https://www.hatena.ne.jp/oauth/authorize' ) access_token = OAuth::AccessToken.new( @consumer, user.token, user.secret ) xml = <<-XML <entry xmlns="http://purl.org/atom/ns#"> <title>dummy</title> <link rel="related" type="text/html" href="#{url}" /> </entry> XML response = access_token.post( "http://b.hatena.ne.jp/atom/post", xml, {'Content-Type' => 'application/xml'} ) end
SimpleOAuthでブックマーク
def create_hatena_bookmark(url) credentials = { consumer_key: ENV['HATENA_CONSUMER_KEY'], consumer_secret: ENV['HATENA_CONSUMER_SECRET'], token: user.token, token_secret: user.secret } post_url = "http://b.hatena.ne.jp/atom/post" auth_header = SimpleOAuth::Header.new(:post, post_url, {}, credentials) xml = <<-XML <entry xmlns="http://purl.org/atom/ns#"> <title>dummy</title> <link rel="related" type="text/html" href="#{url}" /> </entry> XML conn = Faraday.new response = conn.post(post_url) do |req| req.headers[:authorization] = auth_header.to_s req.headers[:content_type] = 'application/xml' req.body = xml end end