2011-06-09 69 views
5

作爲我目前參與的人員搜索項目的一部分,我需要編寫一個ruby腳本,可以將搜索查詢發送到Google Custom Search API並存儲搜索結果進行處理。我找到了Ruby google-api-client gem(http://code.google.com/p/google-api-ruby-client/)並安裝了它,但是,儘管已經徹底閱讀了文檔,但我很遺憾至於如何執行自定義搜索API調用。這是我第一次嘗試使用Google API,我發現這個過程有點令人難以置信,有沒有人可以提供一些示例代碼供我學習?由於在Google中使用Google Custom Search API google-api-client

回答

2

雖然我沒有測試過這一點,這樣的事情應該工作:

require 'google/api_client' 
# Creates an instance of the client. 
client = Google::APIClient.new 
# Authorization setup goes here. 
# Fetch the discovery document and obtain a reference to the API we care about. 
search = client.discovered_api('customsearch') 
# Make an API call using a reference to a discovered method. 
response = client.execute(
    search.cse.list, 'q' => 'your query' 
) 
status, headers, body = response 

請注意,我省略了所有的認證,您可以在文檔爲Ruby客戶找到安裝代碼。

+0

我認爲我陷入困境的是我不明白髮現文件是什麼。任何資源來了解它們以及我需要怎樣處理它們? – 2011-06-13 12:20:31

+0

@Richard我認爲除了構建查詢之外,您不需要對它們進行任何操作,因爲它在gem文檔中顯示。看起來發現文檔處理位全部在gem中抽象出來,但是這裏有一個鏈接解釋了它們是什麼:http://code.google.com/apis/discovery/v1/using.html#discovery-doc – 2011-06-13 14:09:30

+0

是啊實質上,它是以機器可讀方式描述API的資源。這允許客戶端準確理解如何爲特定的API進行API調用。所有你需要知道的是API的標識符和你想要獲得發現文檔參考的版本。然後,您可以使用此發現文檔引用來獲取方法引用,然後將相應的參數傳遞給API調用。 – 2011-06-14 07:41:19

1

在使用api密鑰時,有一些與身份驗證相關的細節問題,而不是在the code abode中概述的OAuth。

在構建客戶端時,您必須明確設置authorzation參數爲nil,否則gem會嘗試使用OAuth進行身份驗證,所以如果僅使用api鍵從服務器調用,您將始終獲得401 Unauthorized。完整的代碼使用customsearch API給出(複製粘貼到IRB)。 the code abode - google-api-client for ruby