How to post nested JSON to HTTParty in Ruby on Rails - ruby-on-rails

I am trying to work out the correct way to post a nested JSON object to an API using HTTParty.
I am getting a successful response using Postman to test the call:
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"
}
}
}]
}
This returns:
{
"Vehicles": [
{
"Id": "Vehicle1",
"HasError": false,
"Error": null,
"FinanceQuotations": [
{
"HasError": false,
"Error": null,
"Finance": {
"Key": "HP",
"Notifications": [],
"Quote": {
.....
}
}
}
}
]
}
But i'm struggling to replicate the call from my rails app. I have a class set up which i'm calling on 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
But this is returning the following error message from the 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"}}
This is the same error that I get from the api in postman if I remove the Id and Parameters objects which suggests the contents of my VehicleRequests object is formatted incorrectly? Any advice would be great!

Can you please change the syntax like below :-
:body => {
}.to_json
that means you have to use .to_json where the body parenthesis close I think it's only syntax error.
Syntax :-
response = HTTParty.post("your request URL",
headers: {
.....
#your header content
.....
},
body: {
......
#your body content
.....
}.to_json
)
I have just edited in your code please try below code :-
#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
)
Hope this will help you :)

Related

How to format a Google Calender API request using HTTParty

I am getting the following error when I make a request to the Google Calendar API.
{"error"=>{"errors"=>[{"domain"=>"global", "reason"=>"required", "message"=>"Missing end time."}], "code"=>400, "message"=>"Missing end time."}}
What is wrong with my formatting? I've tried a ton of different layouts and can't seem to find much information about using HTTParty to make a request to a Google API.
results = HTTParty.post("https://www.googleapis.com/calendar/v3/calendars/primary/events?key=#{Rails.application.secrets.google_api_key}",
:headers => {
"Authorization" => "Bearer #{response["access_token"]}"
},
:query => {
"end": {
"dateTime" => "2015-05-29T09:00:00-08:00",
"timeZone" => "America/Los_Angeles"
},
"start": {
"dateTime" => "2015-05-29T09:00:00-07:00",
"timeZone" => "America/Los_Angeles"
},
"summary": "TEST POST"
}
)
Thanks in advance!
Figured it out. I needed to use a :body key and also specify JSON in the header
results = HTTParty.post("https://www.googleapis.com/calendar/v3/calendars/primary/events?key=#{Rails.application.secrets.google_api_key}",
:headers => {
"Authorization" => "Bearer #{response["access_token"]}",
"Content-Type" => "application/json"
},
:body => {
"end": {
"dateTime" => "2015-05-29T09:00:00-08:00",
"timeZone" => "America/Los_Angeles"
},
"start": {
"dateTime" => "2015-05-29T09:00:00-07:00",
"timeZone" => "America/Los_Angeles"
},
"summary": "TEST POST"
}
)

Attempted to handle event `loadedData` on while in state rootState.loaded.updated.uncommitted. Called with undefined

I am using ember-data to fetch json response from server side, my embeer model looks like.
App.Field = DS.Model.extend
component: DS.attr 'string'
fieldinfos: DS.hasMany('App.Fieldinfo')
App.Field.reopenClass
forInstitution: (institution)->
App.Field.find { institution_id: institution.id }
and my json response looks like
{
:login_fields => [
[0] {
:component => "ns4:FieldInfoComponent",
:id => 1,
:fieldinfo_ids => [
[0] 1
]
},
[1] {
:component => "ns4:FieldInfoComponent",
:id => 2,
:fieldinfo_ids => [
[0] 2
]
},
[2] {
:component => "ns4:FieldInfoComponent",
:id => 3,
:fieldinfo_ids => [
[0] 3
]
}
],
:fieldinfos => [
[0] {
:field_info_obj => "FieldInfoSingle",
:login_field_id => 1,
:id => 1,
:element_ids => [
[0] 1
]
},
[1] {
:field_info_obj => "FieldInfoSingle",
:login_field_id => 2,
:id => 2,
:element_ids => [
[0] 2
]
},
[2] {
:field_info_obj => "FieldInfoSingle",
:login_field_id => 3,
:id => 3,
:element_ids => [
[0] 3
]
}
]
}
it works perfectly when I call once
App.Field.find { institution_id: 1 }
but in between if I again call for different institution
App.Field.find { institution_id: 2 }
Following is the code that fetch loginfields whenever institution changes
loginFields: (->
return [] unless #get('institution')?
App.LoginField.forInstitution(#get 'institution')
).property 'institution'
It gives me Attempted to handle event loadedData on while in state rootState.loaded.updated.uncommitted. Called with undefined error
what I am doing wrong over here and what I need to do to resolve this error. help!

Google Analytics Referral - Ruby

I am using ruby, and attempting to get referrals from google analytics api. Here is what I have set up:
sa_referral = client.execute(:api_method => analytics.data.ga.get, :parameters => {
'ids' => "ga:" + saprofileID,
'dimensions' => "ga:fullreferrer",
'metrics' => "ga:users",
'sort' => "-ga:users",
'filters' => "ga:source!=(direct);",
'start-date' => startDate,
'end-date' => endDate,
})
sa_referral_data = sa_referral do |row|
row = {
:referral => row['0'],
:members => row['1'],
}
end
send_event('sa_top_referrals', current: sa_referral_data)
This returns no data when called in the widget using sa_top_referrals. Below is the data the API is returning.
"columnHeaders": [
{
"name": "ga:fullreferrer",
"columnType": "DIMENSION",
"dataType": "STRING"
},
{
"name": "ga:users",
"columnType": "METRIC",
"dataType": "INTEGER"
}
],
"totalsForAllResults": {
"ga:users": "35638"
},
"rows": [
[
"m.facebook.com/",
"1009"
],
[
"baidu",
"912"
],
[
"usasexguide.info/forum/showthread.php",
"613"
],
Ideally the information I am looking to pull down is the URL ex: m.facebook.com/ and the user count or "613". Those are the two items I am looking to pull. My question is how do I know what row those are equal to. Above i'm sending it using: :referral => row['0'], I'd assume the issue is that its not actually row 0, is there a way I can confirm this?
This should do it:
sa_referral_data = sa_referral['rows'] do |row|
rows.map{|r| { referrals:r[0], members:r[1] }}
end

Mandrill- Attachments not sending attachment

I am attempting to send a small rtf attachment through Mandrill. I have created the following json and tried it using the API test page. The attachment is base 64 encoded. The API reports no error and the email comes through but with no attachment. What am I doing wrong?
{
"attachments": [
{
"type": "application/rtf",
"name": "test.rtf",
"content": "e1xydGYxXGFuc2lcYW5zaWNwZzEyNTJcZGVmZjBcZGVmbGFuZzIwNTd7XGZvbnR0Ymx7XGYwXGZuaWxcZmNoYXJzZXQwIENhbGlicmk7fX0NCntcKlxnZW5lcmF0b3IgTXNmdGVkaXQgNS40MS4yMS4yNTEwO31cdmlld2tpbmQ0XHVjMVxwYXJkXHNhMjAwXHNsMjc2XHNsbXVsdDFcbGFuZzlcZjBcZnMyMiB0aGlzIGlzIGEgdGVzdCBzZW5kaW5nIGZpbGVccGFyDQp9DQoA"
}
],
"message": {
"html": "<html>\r\n<body>test data</body>\r\n</html>\r\n",
"subject": "Cloud Demo",
"from_email": "jklovanc#hotmail.com",
"preserve_recipients": true,
"text": "",
"to": [
{
"type": "to",
"name": "",
"email": "jklovanc#hotmail.com"
}
],
"from_name": "",
"headers": {
"reply-to": "jklovanc#hotmail.com"
}
},
"key": #mykey#,
"async": false
}
Attachments are part of the message object, so the attachments parameter should be nested under the message instead of at the same level. It should look like this instead:
{
"message": {
"attachments": [
{
"type": "application/rtf",
"name": "test.rtf",
"content": "e1xydGYxXGFuc2lcYW5zaWNwZzEyNTJcZGVmZjBcZGVmbGFuZzIwNTd7XGZvbnR0Ymx7XGYwXGZuaWxcZmNoYXJzZXQwIENhbGlicmk7fX0NCntcKlxnZW5lcmF0b3IgTXNmdGVkaXQgNS40MS4yMS4yNTEwO31cdmlld2tpbmQ0XHVjMVxwYXJkXHNhMjAwXHNsMjc2XHNsbXVsdDFcbGFuZzlcZjBcZnMyMiB0aGlzIGlzIGEgdGVzdCBzZW5kaW5nIGZpbGVccGFyDQp9DQoA"
}
],
"html": "<html>\r\n<body>test data</body>\r\n</html>\r\n",
....
<?php
//It works for me! good luck
/*LIBS*/
include 'lib/mandrill-api-php/src/Mandrill.php';
$mandrill = new Mandrill('YOUR API KEY HERE');
/*ADMIN AND USER EMAIL*/
$admin_email = 'your_email#your_domain.com';
$client_email = 'the_email_of_the_client#mail.com';
/*attach PDF with base64_encode */
$attachment = file_get_contents('the_route_to_your_pdf'); // https://yourdomain/pdf_folder/mypdf.pdf
$attachment_encoded = base64_encode($attachment);
try{
$user_message = array(
'subject' => 'Your subject',
'from_email' => $admin_email,
'from_name' => 'my_domain_for_example',
'html' => '<p>HTML template</p>',
'to' => array(array('email' => $client_email, 'name' => 'Recipient 1')),
'merge_vars' => array(array(
'rcpt' => 'recipient1#domain.com',
'vars' =>
array(
array(
'name' => 'FIRSTNAME',
'content' => 'Recipient 1 first name'),
array(
'name' => 'LASTNAME',
'content' => 'Last name')
))),
'attachments' => array(
array(
'content' => $attachment_encoded,
'type' => "application/pdf",
'name' => 'the_name_of_the_attach.pdf',
))
);
$res_user_mandrill = $mandrill->messages->send($user_message, $async=false, $ip_pool=null, $send_at=null);
} catch(Mandrill_Error $e) {
}
?>

Exclude nil values from ElasticSearch Aggregation

I was using this query to retrieve the most significant values:
keywords = Answer.search(
:size => 5,
:query => {
:match => {
:question_id => 32481
}
},
:aggregations => {
:keywords => {
:significant_terms => {
:field => 'text'
}
}
}
)
The field is :text, but it has nil values, so the answer is always:
2.1.2 :135 > keywords.map(&:text)
=> [nil, nil, nil, nil, nil]
I tried to add a filter, as the documentation suggests, but it gives me a parse error:
keywords = Answer.search(
:size => 5,
:query => {
:match => {
:question_id => 32481
},
:filtered => {
:filter => {
:exists => { :field => 'text' }
}
}
},
:aggregations => {
:keywords => {
:significant_terms => {
:field => 'text'
}
}
}
)
I've tried many combinations, with no success. How can I get only the valid text answers?
I believe your ES query should translate to something like this:
"size": 5,
"query": {
"filtered": {
"query": { "match": { "question_id" : 32481 } },
"filter": {
"exists": {
"field": "text"
}
}
}
},
"aggs": {
"keywords": {
"significant_terms": {
"field": "text"
}
}
}
meaning your "question_id" "match" should be enclosed in the "filtered" element.

Resources