LoginSignup
14
12

More than 5 years have passed since last update.

cinii の API を叩くクラスの実装

Last updated at Posted at 2015-06-09

1 はじめに

こんにちは。今回は cinii から論文のメタデータを取得するためのクラスを実装しました。研究で論文のアブストラクトが欲しかったので実装しました。

2 実装

やることはシンプル。API を叩いて、論文のメタデータを @items に配列でセットするだけ。一応 API を叩くときのパラメータは変更可能にしてある。
どんなパラメータがあるかは下記を参照ください。
http://support.nii.ac.jp/ja/cia/api/a_opensearch

lang=cinii.rb
require "net/http"
require "uri"
require "json"

# cinii からデータを取得するためクラス
class Cinii
  attr_reader :items

  # 検索キーワードは欲しいので new したときに指定するようにする
  def initialize(q)
    # cinii を叩く際の初期パラメータ
    @params = {
      q: q,
      format: "json", # データフォーマット
      count: "100", # 取得データの上限数
      lang: "ja", # 言語
      start: 1 # 何ページ目か
    }
  end

  # パラメータを変更可能にする
  def merge_params(params)
    @params.merge!(params)
  end

  # API を叩いてデータを fetch
  def fetch
    # 結果セットを取得
    result = get_result
    # 論文情報が入った配列を取得
    # @items にセットする
    @items = result["@graph"].first["items"]
  end


  # 以下 private method たち
  private

    # cinii を叩いた結果を返す
    def get_result
      json = Net::HTTP.get(get_uri)
      JSON.parse(json)
    end

    # cinii の API を叩く際の uri を返す 
    def get_uri
      # uri のクエリ部分を作成する
      queries = []
      @params.each{|key, val| queries.push("#{key}=#{val}")}

      uri = URI.escape("http://ci.nii.ac.jp/opensearch/search?#{queries.join("&")}")
      URI.parse(uri)
    end
end

# テストしてみる
q = "景観生態"
cinii = Cinii.new(q)
cinii.fetch
p cinii.items

3 終わりに

取得したデータには割と重複があった。ユニークな論文情報が欲しい方は要注意です。

14
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
12