我正在尝试找出使用HTTParty将嵌套的JSON对象发布到API的正确方法。
我正在使用Postman进行成功测试以测试呼叫:
POST:http://service.net/api
标题:x-api-key : apikey123
Body:
{
"VehicleRequests": [{
"Id": "Vehicle1",
"Parameters": {
"Term": 60,
"CashDeposit": 10,
"DepositType": "Percentage",
"AnnualMileage": 10000
},
"PhysicalVehicle": {
"ExternalVehicleId": "12345",
"Type": "Car",
"Status": "PreOwned",
"OnTheRoadPrice": "30000",
"Mileage": "12345",
"Registration": {
"RegistrationNumber": "REGN0",
"DateRegisteredWithDvla": "01/01/2018"
}
}
}]
}
此返回:
{
"Vehicles": [
{
"Id": "Vehicle1",
"HasError": false,
"Error": null,
"FinanceQuotations": [
{
"HasError": false,
"Error": null,
"Finance": {
"Key": "HP",
"Notifications": [],
"Quote": {
.....
}
}
}
}
]
}
但是我正在努力从Rails应用程序复制呼叫。我设置了一个要在create上调用的类
class Monthlyprice
def initialize()
@response = HTTParty.post('http://service.net/api',
:body =>{
:VehicleRequests=> [{
:Id => "Vehicle1",
:Parameters => {
:Term => 60,
:CashDeposit => 10,
:DepositType => "Percentage",
:AnnualMileage => 10000
},
:PhysicalVehicle => {
:ExternalVehicleId => "12345",
:Type => "Car",
:Status => "PreOwned",
:OnTheRoadPrice => "30000",
:Mileage => "12345",
:Registration => {
:RegistrationNumber => "REGN0",
:DateRegisteredWithDvla => "01/01/2018"
}
}
}].to_json
},
:headers => {"x-api-key" => "apikey123"})
puts(@response)
end
end
但是这会从API返回以下错误消息:
{"Error"=>{"UserMessage"=>"Request is invalid.", "TechnicalMessage"=>"Request Validation failed. Request had 2 error(s). 1: request.VehicleRequests[0].Id - The Id field is required.\r\n2: request.VehicleRequests[0].Parameters - The Parameters field is required.", "Code"=>"80000"}}
这是我从邮递员的api中收到的相同错误,如果我删除Id和Parameters对象,这表明我的VehicleRequests对象的内容格式不正确?任何建议都很好!
您能否通过如下方式更改语法:-
:body => {:Id => "Vehicle1"
}.to_json
这意味着您必须在主体结尾处使用.to_json
,我认为这只是语法错误。
语法:-
response = HTTParty.post("your request URL",
headers: {
"Content-Type" => "application/json"
},
body: {
......
your body content
.....
}.to_json
)
我刚刚在您的代码中进行了编辑,请尝试以下代码:-
@response = HTTParty.post('http://service.net/api',
:headers => {"x-api-key" => "apikey123"},
:body =>{
:VehicleRequests=> [{
:Id => "Vehicle1",
:Parameters => {
:Term => 60,
:CashDeposit => 10,
:DepositType => "Percentage",
:AnnualMileage => 10000
},
:PhysicalVehicle => {
:ExternalVehicleId => "12345",
:Type => "Car",
:Status => "PreOwned",
:OnTheRoadPrice => "30000",
:Mileage => "12345",
:Registration => {
:RegistrationNumber => "REGN0",
:DateRegisteredWithDvla => "01/01/2018"
}
}
}]
}.to_json
)
希望这对您有帮助:)