我正在使用RocketPants gem编写api客户端,并尝试使用gem中包含的HTTParty来读取,创建,更新和销毁资源。
阅读和销毁工作正常,但我在创建和更新资源时遇到问题(在下面的示例中,事件)。
具体来说,我正在尝试以下方法:
def create_event params
post "events", :body => { :event => params }, :transformer => Event
end
但是在API方面,它总是给我
Rendering error for ActionController::ParameterMissing:
key not found: event
即使我确实将其包含在帖子请求中。
但是,当我尝试直接使用HTTParty时,就像这样:
HTTParty.post(
"http://localhost:3000/1/events",
:headers => {
'Authorization' => ActionController::HttpAuthentication::Token.encode_credentials("test token")
},
:body => {
:event => {
:name => "test"
}
}
)
它有效,所以它不能是不起作用的API。这种方法有两个缺点:我需要手动传递授权,结果不会被包装为事件。
我错过了正确发送帖子和提出请求的任何内容吗?我还查看了文档和规范,但在发布/推送时找不到任何内容(例如,请参阅https://github.com/filtersquad/rocket_pants/blob/master/spec/rocket_pants/client_spec.rb)。
这是我的完整代码:
require "ticket_gate/version"
require "rocket_pants"
module TicketGate
class Client < RocketPants::Client
# ---- Setup -----------------------------------
# ----------------------------------------------
version 1
base_uri 'http://localhost:3000'
def initialize access_token = nil
raise 'Please initialize with your api access token' unless access_token
@access_token = access_token
end
def base_request_options
{ :headers => { 'Authorization' => ActionController::HttpAuthentication::Token.encode_credentials(@access_token) } }
end
# ---- Events -----------------------------------
# -----------------------------------------------
class Event < APISmith::Smash
property :created_at
property :end_at
property :id
property :name
property :parent_id
property :start_at
property :ticket_limit
property :updated_at
end
def list_events
get "events", :transformer => Event
end
def get_event id
get "events/#{id}", :transformer => Event
end
#### HERE IS THE PROBLEM
def create_event params
post "events", :body => { :event => params }, :transformer => Event
end
#### HERE IS THE PROBLEM
def update_event id, params
put "events/#{id}", :body => { :event => params }, :transformer => Event
end
def destroy_event id
delete "events/#{id}", :transformer => Event
end
end
end
答案 0 :(得分:1)
RocketPants在内部使用API Smith来处理HTTP请求。
从API Smith documentation我试图弄清楚如何正确传递POST参数,我猜这是你应该做的:
post "events", :extra_body => { :event => params }, :transformer => Event