How to format a Google Calender API request using HTTParty - ruby-on-rails

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"
}
)

Related

guzzle http post not working with form_params

When I try to send a Guzzle-POST, I always get a error returned:
{"errors":[{"code":"0","status":"400","title":"Bad Request","detail":"The JSON payload is malformed."}]}
As I don't see any error,inside the data-array itself, maybe it can be a wrong header information? It is an simple POST request to shopware 6 API where I try toadd a new article.
$payload= [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
],
'form_params' =>[
"name" => "productname",
"productNumber" => "101003",
"stock" => 2,
"taxId" => "50ee15989533451095c9d7e03d9ce479",
"price" => [
[
"currencyId" => "b7d2554b0ce847cd82f3ac9bd1c0dfca",
"gross" => 15,
"net" => 10,
"linked" => false
]
]
]
];
$response = $client->request('POST', 'http://shopware6.shop.de/api/product',
$data
);
If I use Postman or RESTer or similar tools, I get a positive result, It works. So I guess I am missing sth. inside my guzzle-request (which is a copy of the origin documentation from https://shopware.stoplight.io/docs/admin-api/ZG9jOjEyMzA4NTUy-product-data )
I am using guzzle with kamermans oauth2 middleware
A simple GET-request is working too:
$response = $client->request('GET', 'http://shopware6.shop.de/api/product/{productid}',
[
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]
);
You are missing the entire authentication in your request, which you might've omitted on purpose but I thought I should add it in the following example for the sake of completion.
Aside from that the cause for the bad request is using the key 'form_params', which is only used for Content-Type: multipart/form-data, instead of 'json' for the payload.
$response = $client->request('POST', 'http://localhost/api/oauth/token', [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
],
'json' => [
'grant_type' => 'client_credentials',
'client_id' => '...',
'client_secret' => '...',
],
]);
$token = json_decode($response->getBody()->getContents(), true)['access_token'];
$payload = [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
],
'json' => [
'name' => 'productname',
'productNumber' => '101003',
'stock' => 2,
'taxId' => '...',
'price' => [
[
'currencyId' => '...',
'gross' => 15,
'net' => 10,
'linked' => false,
],
],
],
];
$response = $client->request('POST', 'http://localhost/api/product', $payload);

How to post nested JSON to HTTParty in 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 :)

How to transform an object into an array from REST POST output

I am building an Rails 5 app.
In this app I create a user with customfields. The output I get from the client (Javascript) is a bit wrong (and I have no idea how to change that). How can I "transform" the output I get into the output I must have?
The below is what I get
"user_customfields_attributes" => {
"1533038627616" => {
"customfield_id" => "1", "value" => "test 1"
}, "1533038627617" => {
"customfield_id" => "2", "value" => "test 2"
}
}
The below is what I need
"user_customfields_attributes" => [{
"customfield_id" => 1,
"value" => "test 1"
}, {
"customfield_id" => 2,
"value" => "test 2"
}]
Thankful for all 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) {
}
?>

Resources