【发布时间】:2020-01-05 14:36:30
【问题描述】:
我正在尝试找出使用 HTTParty 将嵌套 JSON 对象发布到 API 的正确方法。
我正在使用 Postman 测试呼叫成功响应:
发帖:http://service.net/api
标题:x-api-key : apikey123
身体:
{
"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 应用程序中复制调用。我有一个班级设置,我正在调用创建
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"}}
如果我删除了表明我的 VehicleRequests 对象的内容格式不正确的 Id 和 Parameters 对象,这与我从邮递员中的 api 得到的错误相同吗?任何建议都会很棒!
【问题讨论】:
标签: ruby-on-rails json httparty