Yahoo! WebサービスAPIサンプル(画像検索)

概要

Yahoo!画像検索WebサービスAPIサンプル
http://developer.yahoo.co.jp/search/image/V1/image...
Ruby on Railsで作成しています。

サンプルページ

キーワードを入力してボタンをクリックすると検索結果を表示します。
http://sample.sakura-computer.co.jp/yahooimage

参考文献・リンク


Rails API ドキュメント
逆引きRuby

サンプル作成手順

Ruby on Railsをインストールした環境にてサンプルを作成します。
各アプリケーションのバージョンは以下の通りです。
Ruby 1.8.6
Rails 1.2.3

アプリケーションの作成

% rails samples

コントローラ・ビューの作成

% cd samples
samples% ruby script/generate controller yahooimage index
上記コマンド実行後、samples/app/controllers/yahooimage_controller.rb、samples/app/views/yahooimage/index.rhtml、samples/app/views/layouts/yahooimage.rhtmlが作成されるのでそれを編集します。

ソースコード

samples/app/controllers/yahooimage_controller.rb

require "cgi"
require "open-uri"
require "rexml/document"

class YahooimageController < ApplicationController

  REQUEST_URL = "http://api.search.yahoo.co.jp/ImageSearchService/V1/imageSearch"

  def index
    if request.post?
      query = params[:query]
      if query && query.length > 0
        url = REQUEST_URL +
          "?appid=" + "appid" +
          "&query=" + CGI.escape(query)
        xml = REXML::Document.new(open(url))
        logger.debug("#{__FILE__}:#{__LINE__}:xml=#{xml}")

        #検索結果を確認し、結果HTMLを作成する。
        if xml.elements["ResultSet"].attributes["totalResultsReturned"].to_i > 0 then
          xml.elements.each("ResultSet/Result") { |result|
            (@results ||= []) << {
              :title => result.elements["Title"].text,
              :summary => result.elements["Summary"].text,
              :click_url => result.elements["ClickUrl"].text,
              :url => result.elements["Url"].text
            }
          }
        end
      else
        flash[:notice] = "キーワードを入力してください"
      end
    end
  end
end

samples/app/views/yahooimage/index.rhtml

<style type="text/css">
  #notice {
    border: 2px solid red;
    padding: 1em;
    margin-bottom: 2em;
    background-color: #f0f0f0;
    font: bold smaller sans-serif;
  }
</style>
<h2>キーワードを入力してボタンをクリック</h3>
<% if flash[:notice] -%>
  <div id = "notice"><%= flash[:notice] %></div>
<% end -%>
<% form_tag :action =>:index do %>
  <%= text_field_tag :query, params[:query], {"size" => 20} %>
  <%= submit_tag "検索する" %>
<% end %>
<% if @results %>
  <h3>解析結果</h3>
  <table cellpadding="5" cellspacing="1" border="1">
    <% for result in @results %>
      <tr>
        <td><a href="<%= result[:click_url] %>"><%= h(result[:title]) %></a></td>
        <td><%= h(result[:summary]) %></td>
      </tr>
    <% end %>
  </table>
<% end %>

samples/app/views/layouts/yahooimage.rhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
  <head>
    <title>Yahoo!検索 画像検索APIサンプル</title>
  </head>
  <body>
    <h1>Yahoo!検索 画像検索APIサンプル</h1>
    <%= yield :layout %>
    <!-- Begin Yahoo! JAPAN Web Services Attribution Snippet -->
    <a href="http://developer.yahoo.co.jp/about"><img src="http://i.yimg.jp/images/yjdn/yjdn_attbtn1_125_17.gif" title="Webサービス by Yahoo! JAPAN" alt="Web Services by Yahoo! JAPAN" width="125" height="17" border="0" style="margin:15px 15px 15px 15px"></a>
    <!-- End Yahoo! JAPAN Web Services Attribution Snippet -->
    <h5><a href="http://wiki.livedoor.jp/y_tabira/d/FrontPage" target="_blank">WebサービスAPIサンプルWiki</a></h5>
    <h6>$Id: yahooimage.rhtml 39 2008-03-01 20:09:18Z tabi $</h>
  </body>
</html>

railsサーバの起動

以下のコマンドを実行します。
samples% ruby script/server
2008年03月02日(日) 05:27:07 Modified by y_tabira




スマートフォン版で見る