質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.32%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

Q&A

2回答

373閲覧

ルビー いいね数を取得したい

1729

総合スコア0

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

0グッド

0クリップ

投稿2025/03/16 21:57

require 'open-uri' require 'json' # 指定したURLのFacebookいいね数を取得するクラス class FbShareCounter # FacebookグラフAPIのURL BASE_URL = 'http://graph.facebook.com/?id=' # target_urlにいいね数をカウントする対象URLを指定 def initialize(target_url) @request_url = BASE_URL + target_url end def count # グラフAPIにアクセス response = open(@request_url).read # テキストをハッシュに変換 hash = JSON.parse(response) # いいね数を取得 hash['share']['share_count'] end end counter = FbShareCounter.new('http://gihyo.jp') p counter.count

というソースコードで、コマンドプロンプトで実行した結果、

C:/samples/samples/09_03/like_counter.rb:16:in `initialize': Invalid argument @ rb_sysopen - http://graph.facebook.com/?id=http://gihyo.jp (Errno::EINVAL) from C:/samples/samples/09_03/like_counter.rb:16:in `open' from C:/samples/samples/09_03/like_counter.rb:16:in `count' from C:/samples/samples/09_03/like_counter.rb:27:in `<main>'

という結果が帰ってくるのですが、なぜでしょうか?
それで、解決したいことは、プログラムを修正して、いいね数を取得したいのです。
教えていただけると幸いです。よろしくお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

melian

2025/03/18 10:48

質問にあるコードは、以下のページで配布されているサンプルファイルに含まれている samples/09_03/like_counter.rb だと思われます。 サポートページ:3ステップでしっかり学ぶ Ruby入門 技術評論社 https://gihyo.jp/book/2018/978-4-7741-9502-5/support このページには補足情報あって、現在では like_counter.rb は動作しないとのことです。 ========== 補足情報 (2019年6月11日更新) FacebookのAPI変更により、9章3節のコードが動作しなくなっています。 代わりに、同じようにWeb APIを利用するサンプルコードをサンプルファイルとして掲載いたします。 参考としてください。 ==========
1729

2025/03/18 15:01

迅速な回答ありがとうございます。明日、試してみます。又、質問時には、よろしくお願いします。
1729

2025/03/20 14:25

コメントありがとうございます。URL先のサポートページの補足情報の9章3節のコードを試しましたがまだ解決できていません。 コマンドプロンプトで試した結果なのですが、 C:/studyruby/like2.rb:6: warning: already initialized constant OpenSSL::SSL::VERIFY_PEER C:/studyruby/like2.rb:19:in `initialize': Invalid argument @ rb_sysopen - https://en.wikipedia.org/w/api.php?format=json&action=query&list=search&srsearch=ruby (Errno::EINVAL) from C:/studyruby/like2.rb:19:in `open' from C:/studyruby/like2.rb:19:in `search' from C:/studyruby/like2.rb:30:in `<main>' というエラーメッセージが出てきて、それで、 コマンドプロンプトの結果の一部の「 https://en.wikipedia.org/w/api.php?format=json&action=query&list=search&srsearch=ruby 」 の所で、そこに、カーソルを当てると、「Ctrlキーを押しながら、リンクを表示」というのが出てきて、 それを実行すると、マイクロソフトエッジというアプリで、出てきて(URLは、鍵括弧ので囲んだ通りです。「https://en.wikipedia.org/w/api.phpformat=json&action=query&list=search&srsearch=ruby」 (続く)
1729

2025/03/20 14:31

(続き) で、以下のメッセージが出てきました。最初に日本語に翻訳しますか?と聞かれて、日本語に翻訳するを クリックしましたが、日本語翻訳にはなりませんでした。 {"batchcomplete":"","continue":{"sroffset":10,"continue":"-||"},"query":{"searchinfo":{"totalhits":37356,"suggestion":"rugby","suggestionsnippet":"rugby"},"search": [{"ns":0,"title":"Ruby","pageid":43551,"size":37725,"wordcount":3862,"snippet":"\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum (aluminium oxide). \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E is one of the most popular traditional jewelry","timestamp":"2025-03-13T12:31:27Z"},{"ns":0,"title":"Ruby character","pageid":43552,"size":17044,"wordcount":1606,"snippet":"\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E characters or rubi characters (Japanese: ルビ; rōmaji: rubi; Korean: 루비; romaja: rubi) are small, annotative glosses that are usually placed above or","timestamp":"2025-01-17T22:35:06Z"},{"ns":0,"title":"Jack Ruby","pageid":16277,"size":95026,"wordcount":10111,"snippet":"Jack Leon \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E (born Jacob Leon Rubenstein; c. March 25, 1911 – January 3, 1967) was an American nightclub owner who murdered Lee Harvey Oswald on November","timestamp":"2025-03-19T15:21:57Z"},{"ns":0,"title":"Ruby (Jennie album)","pageid":78945812,"size":64045,"wordcount":4864,"snippet":"\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E is the debut solo studio album by South Korean singer and rapper Jennie. Released on March 7, 2025, through Odd Atelier and Columbia Records, the","timestamp":"2025-03-20T08:35:51Z"},{"ns":0,"title":"Ruby Franke","pageid":74732982,"size":28004,"wordcount":2321,"snippet":"\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E Franke (née Griffiths) is an American convicted child abuser and former family vlogger who ran the now defunct YouTube channel 8 Passengers. On August","timestamp":"2025-03-14T12:52:45Z"},{"ns":0,"title":"Ruby (programming language)","pageid":25768,"size":61259,"wordcount":5602,"snippet":"\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E is an interpreted, high-level, general-purpose programming language. It was designed with an emphasis on programming productivity and simplicity.","timestamp":"2025-03-06T22:11:19Z"},{"ns":0,"title":"Ruby (disambiguation)","pageid":25607,"size":8474,"wordcount":1058,"snippet":"Look up \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E or \u003Cspan class=\"searchmatch\"\u003Eruby\u003C/span\u003E in Wiktionary, the free dictionary. A \u003Cspan class=\"searchmatch\"\u003Eruby\u003C/span\u003E is a red gemstone. \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E may also refer to: \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E, Alaska \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E, Arizona \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E, Copiah County","timestamp":"2025-01-22T07:07:23Z"},{"ns":0,"title":"Ruby Rose","pageid":19242083,"size":65946,"wordcount":5145,"snippet":"\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E Rose Langenheim (born 20 March 1986) is an Australian actress, television presenter, and model. She gained prominence for her role in season three","timestamp":"2025-03-12T04:18:34Z"},{"ns":0,"title":"Ruby Bridges","pageid":1143659,"size":28397,"wordcount":2960,"snippet":"\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E Nell Bridges Hall (born September 8, 1954) is an American civil rights activist. She was the first African American child to attend formerly whites-only","timestamp":"2025-03-15T17:33:45Z"},{"ns":0,"title":"Ruby Ridge standoff","pageid":501385,"size":108783,"wordcount":12341,"snippet":"The \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E Ridge standoff was the siege of a cabin occupied by the Weaver family in Boundary County, Idaho, in August 1992. On August 21, deputies of the","timestamp":"2025-03-01T06:39:21Z"}]}} で、整形出力にチェックすると、 (続く)
1729

2025/03/20 14:33

(続き) { "batchcomplete": "", "continue": { "sroffset": 10, "continue": "-||" }, "query": { "searchinfo": { "totalhits": 37356, "suggestion": "rugby", "suggestionsnippet": "rugby" }, "search": [ { "ns": 0, "title": "Ruby", "pageid": 43551, "size": 37725, "wordcount": 3862, "snippet": "\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum (aluminium oxide). \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E is one of the most popular traditional jewelry", "timestamp": "2025-03-13T12:31:27Z" }, { "ns": 0, "title": "Ruby character", "pageid": 43552, "size": 17044, "wordcount": 1606, "snippet": "\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E characters or rubi characters (Japanese: ルビ; rōmaji: rubi; Korean: 루비; romaja: rubi) are small, annotative glosses that are usually placed above or", "timestamp": "2025-01-17T22:35:06Z" }, { "ns": 0, "title": "Jack Ruby", "pageid": 16277, "size": 95026, "wordcount": 10111, "snippet": "Jack Leon \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E (born Jacob Leon Rubenstein; c. March 25, 1911 – January 3, 1967) was an American nightclub owner who murdered Lee Harvey Oswald on November", "timestamp": "2025-03-19T15:21:57Z" }, { "ns": 0, "title": "Ruby (Jennie album)", "pageid": 78945812, "size": 64045, "wordcount": 4864, "snippet": "\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E is the debut solo studio album by South Korean singer and rapper Jennie. Released on March 7, 2025, through Odd Atelier and Columbia Records, the", "timestamp": "2025-03-20T08:35:51Z" }, { "ns": 0, "title": "Ruby Franke", "pageid": 74732982, "size": 28004, "wordcount": 2321, "snippet": "\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E Franke (née Griffiths) is an American convicted child abuser and former family vlogger who ran the now defunct YouTube channel 8 Passengers. On August", "timestamp": "2025-03-14T12:52:45Z" }, { "ns": 0, "title": "Ruby (programming language)", "pageid": 25768, "size": 61259, "wordcount": 5602, "snippet": "\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E is an interpreted, high-level, general-purpose programming language. It was designed with an emphasis on programming productivity and simplicity.", "timestamp": "2025-03-06T22:11:19Z" }, { "ns": 0, "title": "Ruby (disambiguation)", "pageid": 25607, "size": 8474, "wordcount": 1058, "snippet": "Look up \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E or \u003Cspan class=\"searchmatch\"\u003Eruby\u003C/span\u003E in Wiktionary, the free dictionary. A \u003Cspan class=\"searchmatch\"\u003Eruby\u003C/span\u003E is a red gemstone. \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E may also refer to: \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E, Alaska \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E, Arizona \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E, Copiah County", "timestamp": "2025-01-22T07:07:23Z" }, { "ns": 0, "title": "Ruby Rose", "pageid": 19242083, "size": 65946, "wordcount": 5145, "snippet": "\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E Rose Langenheim (born 20 March 1986) is an Australian actress, television presenter, and model. She gained prominence for her role in season three", "timestamp": "2025-03-12T04:18:34Z" }, { "ns": 0, "title": "Ruby Bridges", "pageid": 1143659, "size": 28397, "wordcount": 2960, "snippet": "\u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E Nell Bridges Hall (born September 8, 1954) is an American civil rights activist. She was the first African American child to attend formerly whites-only", "timestamp": "2025-03-15T17:33:45Z" }, { "ns": 0, "title": "Ruby Ridge standoff", "pageid": 501385, "size": 108783, "wordcount": 12341, "snippet": "The \u003Cspan class=\"searchmatch\"\u003ERuby\u003C/span\u003E Ridge standoff was the siege of a cabin occupied by the Weaver family in Boundary County, Idaho, in August 1992. On August 21, deputies of the", "timestamp": "2025-03-01T06:39:21Z" } ] } } となりました。これは、どういう事なのでしょうか?教えていただけると幸いです。 もし、説明不足でしたら、随時補足しますし、聞き返して頂けると嬉しいです。
Eggpan

2025/03/21 18:07

一般的なAPIの利用方法を学びたいのか、Facebook APIでいいね数を取得したいのか、やりたい事はどちらになりますか? 書籍の情報が古すぎて、Rubyのopen-uri は3.0で既に廃止となった書き方をしています。 Facebook APIについては、2016年頃からアクセストークンが必須になっているはずで、まずはアプリの作成とトークンの取得が必要なはずです。
1729

2025/03/22 04:52

迅速な回答ありがとうございます。 それは、どちらにしても、 「Facebook APIについては、2016年頃からアクセストークンが必須になっているはずで、まずはアプリの作成とトークンの取得が必要なはずです。」 は、どうしてもやらなければいけないという事でしょうか? 教えて頂けると嬉しいです。
Eggpan

2025/03/22 08:25

一般的なAPIの利用方法を学びたいだけであれば、補足情報の通りWikipediaのAPIの利用方法をしっておくだけでいいと思いますよ。 その場合はFacebook APIを使うわけではないのでアプリの作成も不要でしょう。
guest

回答2

0

C:/studyruby/like2.rb:19:in initialize: Invalid argument @ rb_sysopen - …
:
というエラーメッセージが出てきて、...

library open-uri (Ruby 3.4 リファレンスマニュアル) を確認してみると、URI オブジェクト(インスタンス)を利用する方法が記載されています。

URI オブジェクトは直接読み込むことができます。戻り値の文字列は、OpenURI::Meta で拡張されています。

str = uri.read
p str.base_uri

ruby

1require 'open-uri' 2require 'json' 3 4# 検索ワードを渡してWikipediaで検索するクラス 5class WikipediaSearcher 6 # Wikipediaの検索用URL 7 BASE_URL = 'https://en.wikipedia.org/w/api.php?format=json&action=query&list=search&srsearch=' # srsearchの後に検索ワードを指定 8 # search_wordで検索したい語を指定する 9 def initialize(search_word) 10 @request_url = URI(BASE_URL + search_word) # URI オブジェクト 11 end 12 13 def search 14 # APIにアクセス 15 response = @request_url.read 16 17 # JSON形式のテキストをハッシュに変換 18 hash = JSON.parse(response) 19 20 # 検索結果の中ではじめにヒットしたものを表示。 21 hash['query']['search'][0] # 検索結果を一覧で表示したい場合は[0]を省略。 22 end 23end 24 25searcher = WikipediaSearcher.new('ruby') # rubyで検索する 26pp searcher.search 27 28# 29# {"ns"=>0, 30# "title"=>"Ruby", 31# "pageid"=>43551, 32# "size"=>37725, 33# "wordcount"=>3862, 34# "snippet"=> 35# "<span class=\"searchmatch\">Ruby</span> is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum (aluminium oxide). <span class=\"searchmatch\">Ruby</span> is one of the most popular traditional jewelry", 36# "timestamp"=>"2025-03-13T12:31:27Z"}

投稿2025/03/20 16:49

melian

総合スコア21038

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

1729

2025/03/21 17:15

回答ありがとうございます。 すみません。疑問点が2つほどあって、 疑問①「OpenURI::Meta で拡張されています。 str = uri.read p str.base_uri」 の所で、 「str = uri.read p str.base_uri」 は、Rubyプログラムのどこに追加すれば良いのでしょうか? 疑問②26行目の「pp」で、これは、「require 'pp'」が必要になるのではないのでしょうか? 以上2点について教えて頂けると嬉しいです。
melian

2025/03/21 17:31

> 疑問① 〜は、Rubyプログラムのどこに追加すれば良いのでしょうか 上記のソースコードで言えば、15行目の "response = @request_url.read" がそうです。"p str.base_uri" に関してはアクセスしている URL を表示するので今回の件では必要ないかと思います。(追加しても構いませんが) > 疑問②26行目の「pp」で、これは、「require 'pp'」が必要になるのではないのでしょうか? pp ライブラリは標準で組み込まれていますので不要です。
1729

2025/03/22 11:23

すみません。ppライブラリが標準で組み込まれているのは、Rubyのバージョンが、「Ruby 2.5 以降」からという事でしょうか? 教えて頂けると嬉しいです。
guest

0

ruby

1open(@request_url)

ruby

1URI.open(@request_url)

に変更すると当該エラーはなくなります

投稿2025/03/18 09:36

satoshih

総合スコア831

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

1729

2025/03/20 13:59

回答ありがとうございます。試してみましたが解決できませんでした。 コマンドプロンプトで実行した結果、 C:/Ruby33-x64/lib/ruby/3.3.0/open-uri.rb:376:in `open_http': 400 Bad Request (OpenURI::HTTPError) from C:/Ruby33-x64/lib/ruby/3.3.0/open-uri.rb:770:in `buffer_open' from C:/Ruby33-x64/lib/ruby/3.3.0/open-uri.rb:220:in `block in open_loop' from C:/Ruby33-x64/lib/ruby/3.3.0/open-uri.rb:218:in `catch' from C:/Ruby33-x64/lib/ruby/3.3.0/open-uri.rb:218:in `open_loop' from C:/Ruby33-x64/lib/ruby/3.3.0/open-uri.rb:158:in `open_uri' from C:/Ruby33-x64/lib/ruby/3.3.0/open-uri.rb:750:in `open' from C:/Ruby33-x64/lib/ruby/3.3.0/open-uri.rb:29:in `open' from C:/studyruby/like.rb:16:in `count' from C:/studyruby/like.rb:27:in `<main>' というエラーメッセージが出てきました。 この場合どの辺りに原因がありそうでしょうか?教えていただけると嬉しいです。
satoshih

2025/03/20 17:50

URLへGETリクエストした結果、BadRequestが返ってきているということです。 リクエスト先のサーバーで受け付けられない形でリクエストを行っているので URLが間違っているか、パラメータなど必要なものが足りないなどではないでしょうか
1729

2025/03/21 17:17

プログラムは、ちゃんとコピーして実行したのですがね。原因は、不明です。 すみません。
1729

2025/03/21 18:43 編集

追記 迅速な回答ありがとうございます! 所で、なぜ、ブラウザが、「グーグルクローム」でやっているのに、「マイクロソフトエッジ」が、開かれて、エラープログラムが表示されたのでしょうか?原因は、何なのでしょうか? 教えて頂けると嬉しいです。
1729

2025/03/21 21:16 編集

追記 エラープログラムが表示されたのですが、正確に言うと、エラープログラムみたいなもの(エラーメッセージ?)が表示されるというのが、個人的な実行結果(感想)です。
satoshih

2025/03/24 01:06

> ちゃんとコピーして実行したのですがね 何をコピーしたんでしょうか? 参考にしたサイトなどがあれば質問の本文に追記してください > 所で、なぜ、ブラウザが、「グーグルクローム」でやっているのに、「マイクロソフトエッジ」が、開かれて、エラープログラムが表示されたのでしょうか?原因は、何なのでしょうか? すみませんが、何を聞かれてるかわかりません。 このページの質問と関係ないと思います > エラープログラムが表示されたのですが エラープログラムとはなんでしょうか? 前述しましたが、リクエスト自体はできていてAPIからBadRequestが返ってきているのでAPIの仕様を確認し、curl や POSTMAN で実際にAPIを期待した形でリクエストできるようになってから実装すべきです
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.32%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問