我一直在为我正在处理的项目使用API调用,当我尝试将一些JSON传递给POST请求时遇到问题。该调用在Postman中有效,但是我不知道如何在Ruby中对其进行格式化。这是我的代码:
require 'httparty'
require 'json'
require 'pp'
#use the HTTParty gem
include HTTParty
#base_uri 'https://app.api.com'
#set some basic things to make the call,
@apiUrl = "https://app.api.com/"
@apiUrlEnd = 'apikey=dontStealMePls'
@apiAll = "#{@apiUrl}#{@apiUrlEnd}"
@apiTest = "https://example.com"
def cc_query
HTTParty.post(@apiAll.to_s, :body => {
"header": {"ver": 1,"src_sys_type": 2,"src_sys_name": "Test","api_version": "V999"},
"command1": {"cmd": "cc_query","ref": "test123","uid": "abc01", "dsn": "abcdb612","acct_id": 7777}
})
end
def api_test
HTTParty.post(@apiTest.to_s)
end
#pp api_test()
pp cc_query()
这段代码给我这个错误:
{"fault"=>
{"faultstring"=>"Failed to execute the ExtractVariables: Extract-Variables",
"detail"=>{"errorcode"=>"steps.extractvariables.ExecutionFailed"}}}
我知道该错误,因为如果我尝试通过调用主体中没有任何JSON的方式进行调用,就会得到此错误。因此,我假设上面的代码在进行API调用时未传递任何JSON。我的JSON格式不正确吗?我甚至可以正确格式化.post调用吗?任何帮助表示赞赏! :)
api_test()方法仅对example.com进行POSt调用即可,并且有效(节省了理智)。
答案 0 :(得分:0)
只需在类中使用HTTParty作为mixin即可:
require 'httparty'
class MyApiClient
include HTTParty
base_uri 'https://app.api.com'
format :json
attr_accessor :api_key
def initalize(api_key:, **options)
@api_key = api_key
@options = options
end
def cc_query
self.class.post('/',
body: {
header: {
ver: 1,
src_sys_type: 2,
src_sys_name: 'Test',
api_version: 'V999'
},
command1: {
cmd: 'cc_query',
ref: 'test123',
uid: 'abc01',
dsn: 'abcdb612',
acct_id: 7777
}
},
query: {
api_key: api_key
}
)
end
end
用法示例:
MyApiClient.new(api_key: 'xxxxxxxx').cc_query
当您使用format :json
时,HTTParty将自动设置内容类型并处理JSON编码和解码。我猜那是你失败的地方。