RubyからEvernoteAPIを使う-Web Application編-
更新日:2022.07.02
作成日:2012.03.05
前回のエントリ( RubyからEvernoteAPIを使ってノートブックの取得と、ノートの作成をする - ギークを夢見るじょーぶん男子 )で、クライアントからAPIを使ってノートブックの取得と、ノートの作成はできました。今回、Web Applicationとして、OAuthを使って認証して、EvernoteAPIを叩こうと思います。
APIキーの取得
APIキーのリクエスト同じようにAPIキーを取得。 今回は、「Application Type」を「Web Application」を選択します。
サンプルを修正
以下のリンクからRubyのサンプルを取得。oauthフォルダに入ってるものが、Web Applicationのサンプルみたいです。Web ApplicationのRuby版のサンプルは、sinatraを使ったものでした。
http://evernote.s3.amazonaws.com/api/evernote-api-1.20.zip
自分の取得したAPIキーを反映するために、evernote_config.rbを 修正
require 'oauth'
require 'oauth/consumer'
require 'thrift'
# 以下、取得したAPIキー
OAUTH_CONSUMER_KEY = "YOUR_CONSUMER_KEY"
OAUTH_CONSUMER_SECRET = "YOUR_CONSUMER_SECRET"
# 定数
EVERNOTE_SERVER = "https://sandbox.evernote.com"
REQUEST_TOKEN_URL = "#{EVERNOTE_SERVER}/oauth"
ACCESS_TOKEN_URL = "#{EVERNOTE_SERVER}/oauth"
AUTHORIZATION_URL = "#{EVERNOTE_SERVER}/OAuth.action"
NOTESTORE_URL_BASE = "#{EVERNOTE_SERVER}/edam/note/"
Evetenoのgemを使うように、ちょこちょこ修正。
require "./evernote_config.rb"
としないと、読み込まれなかったのはなーぜー?
require 'rubygems'
require 'sinatra'
require 'evernote'
enable :sessions
# Load our dependencies and configuration settings
require "./evernote_config.rb"
##
# Verify that you have obtained an Evernote API key
##
before do
if (OAUTH_CONSUMER_KEY == "en-edamtest")
halt '<span style="color:red">Before using this sample code you must edit evernote_config.rb and replace OAUTH_CONSUMER_KEY and OAUTH_CONSUMER_SECRET with the values that you received from Evernote. If you do not have an API key, you can request one from <a href="http://www.evernote.com/about/developer/api/">http://www.evernote.com/about/developer/api/</a>.</span>'
end
end
##
# Index page
##
get '/' do
erb :authorize
end
##
# Reset the session
##
get '/reset' do
session[:request_token] = nil
erb :authorize
end
##
# Get temporary credentials and redirect the user to Evernote for authoriation
##
get '/authorize' do
callback_url = request.url.chomp("authorize").concat("callback")
begin
consumer = OAuth::Consumer.new(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET,{
:site => EVERNOTE_SERVER,
:request_token_path => "/oauth",
:access_token_path => "/oauth",
:authorize_path => "/OAuth.action"})
session[:request_token] = consumer.get_request_token(:oauth_callback => callback_url)
redirect session[:request_token].authorize_url
rescue Exception => e
@last_error = "Error obtaining temporary credentials: #{e.message}"
erb :error
end
end
##
# Receive callback from the Evernote authorization page and exchange the
# temporary credentials for an token credentials.
##
get '/callback' do
if (params['oauth_verifier'].nil?)
@last_error = "Content owner did not authorize the temporary credentials"
erb :error
else
oauth_verifier = params['oauth_verifier']
begin
access_token = session[:request_token].get_access_token(:oauth_verifier => oauth_verifier)
shard_id = access_token.params['edam_shard']
# Construct the URL used to access the user's account
noteStoreUrl = NOTESTORE_URL_BASE + shard_id
noteStoreTransport = Thrift::HTTPClientTransport.new(noteStoreUrl)
noteStoreProtocol = Thrift::BinaryProtocol.new(noteStoreTransport)
noteStore = Evernote::EDAM::NoteStore::NoteStore::Client.new(noteStoreProtocol)
# Build an array of notebook names from the array of Notebook objects
notebooks = noteStore.listNotebooks(access_token.token)
result = Array.new
notebooks.each do |notebook|
result << notebook
end
@notebooks = result
erb :complete
rescue Exception => e
@last_error = e
erb :error
end
end
end
__END__
@@ layout
<html>
<head>
<title>Evernote Ruby OAuth Demo</title>
</head>
<body>
<h1>Evernote Ruby OAuth Demo</h1>
<p>
This application uses the <a href="http://www.sinatrarb.com/">Sinatra framework</a> to demonstrate the use of OAuth to authenticate to the Evernote web service. OAuth support is implemented using the <a href="https://github.com/oauth/oauth-ruby">Ruby OAuth RubyGem</a>.
</p>
<p>
On this page, we demonstrate how OAuth authentication might work in the real world.
To see a step-by-step demonstration of how OAuth works, see <code>evernote_oauth.rb</code>.
</p>
<hr/>
<h2>Evernote Authentication</h2>
<%= yield %>
<hr/>
<p>
<a href="/reset">Click here</a> to start over
</p>
</body>
</html>
@@ error
<p>
<span style="color:red">An error occurred: <%= @last_error.message %></span>
</p>
@@ authorize
<p>
<a href="/authorize">Click here</a> to authorize this application to access your Evernote account. You will be directed to evernote.com to authorize access, then returned to this application after authorization is complete.
</p>
@@ complete
<p style="color:green">
Congratulations, you have successfully authorized this application to access your Evernote account!
</p>
<p>
You account contains the following notebooks:
</p>
<ul>
<% @notebooks.each do |notebook| %>
<li><%= notebook.name %></li>
<% end %>
</ul>
ターミナルから起動
ruby -rubygems evernote_oauth_simple.rb
http://localhost:4567
で確認。動いた動いた。
次やりたいこと
- herokuで動かしてみる。
Related contents
TECH
2012.03.04
RubyからEvernoteAPIを使ってノートブックの取得と、ノートの作成をする
TECH
2012.02.01
Sinatra触ってると出てくるRackって何?
TECH
2012.04.19
RubyからGMailを使ってメール送信
TECH
2012.04.03
Padrinoを触ってみた
TECH
2012.03.21
TEDから取得したmp3に英語原稿を埋め込む
TECH
2012.03.20
TEDの英語原稿を取得する
TECH
2012.02.29
SinatraでTwitterBootstrapを使ってTODOアプリを作ってみよう
TECH
2012.01.30
Lokkaプラグインlokka-twitter_urlを作ってみた