我为此推出了自己的解决方案,并认为它会有所帮助。我编写了一个模块,它使用 json、curb 和 addressable gem 向 localhost:3000 发送 GET、PUT、POST 和 DELETE 请求。它可以请求 XML(如原始问题所要求的)或 json。它将响应正文作为哈希返回。它主要是一个包装器,我认为它有可怕的语法。
请注意,我会自动加载我的api_key。这可以通过传递:api_key => false 禁用或使用api_key => "wrong" 破坏。您可能希望忽略它或对其进行修改以适合您的身份验证方案。
这是模块:
module ApiTesting
# requres the json, curb, and addressable gems
require "addressable/uri"
def api_call(path, verb, query_hash={}, options={})
options.reverse_merge! :api_key => "abc1234", :format => "xml"
query_hash.reverse_merge!({:api_key => options["api_key"]}) if options[:api_key]
query = to_query_string(query_hash)
full_path = "http://localhost:3000/#{path}.#{options[:format]}?#{query}"
response = case verb
when :get
Curl::Easy.perform(full_path)
when :post
Curl::Easy.http_post("http://localhost:3000/#{path}.#{options[:format]}", query)
when :put
Curl::Easy.http_put(full_path, nil)
when :delete
Curl::Easy.http_delete(full_path)
end
case options[:format]
when "xml"
Hash.from_xml(response.body_str)
when "json"
JSON.parse(response.body_str)
end
end
private
def to_query_string(val)
uri = Addressable::URI.new
uri.query_values = val
uri.query
end
end
这里有一些简单的例子:
使用 GET 请求资源属性:
api_call("calls/41", :get)
使用 POST 创建资源:
api_call("people", :post, {:person => {:first => "Robert", :last => "Smith" } })
使用 PUT 更新资源:
api_call("people/21", :put, {:person => { :first => "Bob" } })
使用 DELETE 删除资源:
api_call("calls/41", :delete)
关闭api_key的自动插入:
api_call("calls/41", :get, {}, {:api_key => false})
使用错误的 api_key:
api_call("calls/41", :get, {}, {:api_key => "wrong"})
用作json(默认为xml):
api_call("calls/41", :get, {}, {:format => "json"})