16

Ruby の HTTParty ライブラリを使用して API エンドポイントに POST リクエストを送信するのが困難です。私がやり取りしている API はGittip APIであり、そのエンドポイントには認証が必要です。HTTParty を使用して、認証済みの GET リクエストを正常に作成できました。

サンプル コードで確認できます。

user = "gratitude_test"
api_key = "5962b93a-5bf7-4cb6-ae6f-aa4114c5e4f2"
# I have included real credentials since the above is merely a test account.

HTTParty.get("https://www.gittip.com/#{user}/tips.json", 
             { :basic_auth => { :username => api_key } })

そのリクエストは機能し、期待どおりに次を返します。

[
  {
    "amount" => "1.00",
    "platform" => "gittip",
    "username" => "whit537"
  },
  {
    "amount" => "0.25",
    "platform" => "gittip",
    "username" => "JohnKellyFerguson"
  }
]

しかし、HTTParty を使用して POST リクエストを成功させることができませんでした。Gittip API では、curl を使用して POST リクエストを作成する方法が次のように説明されています。

curl https://www.gittip.com/foobar/tips.json \
  -u API_KEY: \
  -X POST \
  -d'[{"username":"bazbuz", "platform":"gittip", "amount": "1.00"}]' \
  -H"Content-Type: application/json"

次のように、HTTParty を使用してコードを構造化しようとしました (失敗しました)。

user = "gratitude_test"
api_key = "5962b93a-5bf7-4cb6-ae6f-aa4114c5e4f2"

HTTParty.post("https://www.gittip.com/#{user}/tips.json",
              { 
                :body => [ { "amount" => "0.25", "platform" => "gittip", "username" => "whit537" } ],
                :basic_auth => { :username => api_key },
                :headers => { 'Content-Type' => 'application/json' }
               })

最初の引数は URL で、2 番目の引数はオプション ハッシュです。上記のコードを実行すると、次のエラーが発生します。

NoMethodError: undefined method `bytesize' for [{"amount"=>"0.25", "platform"=>"gittip", "username"=>"whit537"}]:Array
  from /Users/John/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http/generic_request.rb:179:in `send_request_with_body'

API 呼び出しを構造化する他のさまざまな組み合わせを試しましたが、それを機能させる方法がわかりません。別の例を次に示します。ここでは、配列を本体の一部として使用せず、内容を変換しますto_json

user = "gratitude_test"
api_key = "5962b93a-5bf7-4cb6-ae6f-aa4114c5e4f2"

HTTParty.post("https://www.gittip.com/#{user}/tips.json",
          {
            :body => { "amount" => "0.25", "platform" => "gittip", "username" => "whit537" }.to_json,
            :basic_auth => { :username => api_key },
            :headers => { 'Content-Type' => 'application/json' }
           })

以下を返します (500 エラー):

<html>
  <head>
    <title>500 Internal Server Error</title>
  </head>
  <body>\n        Internal server error, program!\n        <pre></pre>  
  </body>
</html>

私は curl にあまり詳しくないので、間違って HTTParty に変換しているかどうかはわかりません。

どんな助けでも大歓迎です。ありがとう。

4

1 に答える 1