Google Slides Batch Update Errors - "Invalid JSON payload received. Unknown name" & " Cannot bind query parameter" - google-apis-explorer

I'm trying to write to a slide element.
I keep getting the error responses of "Invalid JSON payload received. Unknown name" and " Cannot bind query parameter. Field"
My request is
{
"requests": [
{
"deleteText": {
"objectId": "g33c4ea3b90_0_9",
"textRange": {
"type": "FROM_START_INDEX",
"startIndex": 0
}
}
},
{
"insertText": {
"objectId": "g33c4ea3b90_0_9",
"text": "$8.23",
"insertionIndex": 0
}
}
]
}
I am posting to: https://slides.googleapis.com/v1/presentations/PRESENTATION_ID:batchUpdate?access_token=ACCESS_TOKEN
I am manually cURLing the request in PHP:
$params = '
{
"requests": [
{
"deleteText": {
"objectId": "'.$page_object_id.'",
"textRange": {
"type": "FROM_START_INDEX",
"startIndex": 0
}
}
},
{
"insertText": {
"objectId": "'.$page_object_id.'",
"text": "$8.23",
"insertionIndex": 0
}
}
]
}
';
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
CURLOPT_CUSTOMREQUEST => 'POST' ,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false ,
CURLINFO_HEADER_OUT => true ,
CURLOPT_VERBOSE => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
$obj = json_decode($content, true);
print_r( $obj );
When I call it from the API Explorer it works perfectly, but not from my server.

So the problem was the use of double quotes instead of single quotes in the request parameter json string.
So the following works:
{
'requests': [
{
'deleteText': {
'objectId': 'g33c4ea3b90_0_9',
'textRange': {
'type': 'FROM_START_INDEX',
'startIndex': 0
}
}
},
{
'insertText': {
'objectId': 'g33c4ea3b90_0_9',
'text': '$44.23',
'insertionIndex': 0
}
}
]
}
I had been working on this for two days.

Related

Perl Create JSON string in a specific format

I have a table with 3 fields that I query and put the values in a JSON. The table has hostname to application name and application id. I currently have a perl script that outputs the following json string.
[
{
"app_id" : "1234",
"app_name" : "Managed File Transfer",
"ci_name" : "hosta7"
},
{
"app_name" : "Patrtol",
"app_id" : "1235",
"ci_name" : "hosta7"
},
{
"app_id" : "1236",
"app_name" : "RELATIONAL DATA WAREHOUSE",
"ci_name" : "hosta7"
},
{
"ci_name" : "hosta7",
"app_id" : "1237",
"app_name" : "Managed File Transfer"
},
{
"app_id" : "1238",
"app_name" : "Initio Application",
"ci_name" : "hosta7"
},
{
"app_id" : "1239",
"app_name" : "Data Warehouse Operations Infrastructure",
"ci_name" : "hosta7"
},
{
"app_id" : "2345",
"app_name" : "Tableou",
"ci_name" : "hostb"
}
]
I want the resulting json string like the following where if the ci_name already exists, I want the new item to be added to the current entry of the host in the JSON string. So essentially, I want this JSON string
{
"hosts" : [{
"hosta" :[
{
"app_id": "1234",
"app_name": "Managed File Transfer"
},
{
"app_id": "1235",
"app_name": "Patrol"
},
{
"app_id": "1236",
"app_name": "RELATIONAL DATA WAREHOUSE"
},
{
"app_id": "1237",
"app_name": "Managed File Transfer"
},
{
"app_id": "1238",
"app_name": "Initio Application"
},
{
"app_id": "1239",
"app_name": "Data Warehouse Operations Infrastructure"
}
],
"hostb" : [
{
"app_id": "2345",
"app_name": "Tableou"
}
]
}]
}
#!/usr/bin/perl
use strict;
use warnings;
use JSON;
my $hosts = [
{
'app_id' => '1234',
'app_name' => 'Managed File Transfer',
'ci_name' => 'hosta7'
},
{
'app_name' => 'Patrtol',
'app_id' => '1235',
'ci_name' => 'hosta7'
},
{
'app_id' => '1236',
'app_name' => 'RELATIONAL DATA WAREHOUSE',
'ci_name' => 'hosta7'
},
{
'ci_name' => 'hosta7',
'app_id' => '1237',
'app_name' => 'Managed File Transfer'
},
{
'app_id' => '1238',
'app_name' => 'Initio Application',
'ci_name' => 'hosta7'
},
{
'app_id' => '1239',
'app_name' => 'Data Warehouse Operations Infrastructure',
'ci_name' => 'hosta7'
},
{
'app_id' => '2345',
'app_name' => 'Tableou',
'ci_name' => 'hostb'
}
];
my $output;
foreach my $row (#$hosts) {
push #$output, $row;
}
my $json = new JSON;
$json->pretty(1);
print $json->encode($output);
You don't want to push directly, you want to push under a key taken from the ci_name, and you only want to copy the app id and name.
for my $element (#$hosts) {
push #{ $output->{ $element->{ci_name} } },
{ map { $_ => $element->{$_} } qw( app_id app_name ) };
}
Probably the code will look like following snippet
#!/usr/bin/perl
use strict;
use warnings;
use JSON;
use Data::Dumper;
my $debug = 0;
my %data;
while( <DATA> ) {
chomp;
next if /app_id/;
my ($app_id,$ci_name,$app_name) = split /,/;
push #{$data{hosts}{$ci_name}}, {app_id => $app_id, app_name => $app_name };
}
print Dumper(\%data) if $debug;
my $json = encode_json \%data;
print $json;
__DATA__
app_id,ci_name,app_name
1234,hosta7,Managed File Transfer
1235,hosta7,Patrtol
1236,hosta7,RELATIONAL DATA WAREHOUSE
1237,hosta7,Managed File Transfer
1238,hosta7,Initio Application
1239,hosta7,Data Warehouse Operations Infrastructure
2345,hostb,Tableou

file_get_contents parse json insert database

Hi I encountered a problem. I will record the data I received from the database.
JSON=>
{
"success": true,
"timestamp": 1565251506,
"base": "EUR",
"date": "2019-08-08",
"rates": {
"AED": 4.119657,
"AFN": 87.689574,
"ALL": 121.192477,
"AMD": 533.113395,
"ANG": 1.998509,
"AOA": 398.760307,
"ARS": 51.036305,
"AUD": 1.654423
}
}
After Json decode
array:5 [
"success" => true
"timestamp" => 1565205306
"base" => "EUR"
"date" => "2019-08-07"
"rates" => array:168 [
"AED" => 4.118588
"AFN" => 87.74397
"ALL" => 121.002609
"AMD" => 534.279745
"ANG" => 2.001014
]
]
I want this=> But How do I get quote and rate?
$response = file_get_contents("rate.json");
$datas = json_decode($response, true);
foreach ($datas as $data) {
$rates = new Rate();
$rates->base = $datas['base'];
$rates->quote = 'AED';
$rates->rate = '4.119657';
$rates->save();
}
You're looping over the wrong thing here, you should be looping over the rates and saving the corresponding key and value:
$response = file_get_contents("rate.json");
$data = json_decode($response, true);
foreach ($data['rates'] as $quote => $rate) {
$rates = new Rate();
$rates->base = $data['base'];
$rates->quote = $quote;
$rates->rate = $rate;
$rates->save();
}

cakephp 3 rest errors return as html CrudJsonApi

I'm adding a REST API onto an existing cakephp codebase.
It is working as I expect. I hit /api/v1/contacts/12312 and get json data back for contact 12312. If put an id of a contact that doesn't exist then I get the html 404 page error rather than json.
This happens internally on the contacts->get($id) line.
In the api app controller I have
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Crud.Crud', [
'actions' => [
'Crud.Index',
'Crud.View',
'Crud.Add',
'Crud.Edit',
'Crud.Delete'
],
'listeners' => [
'CrudJsonApi.JsonApi',
'CrudJsonApi.Pagination', // Pagination != ApiPagination
'Crud.ApiQueryLog',
],
'Error' => [
'errorLevel' => E_ALL,
'exceptionRenderer' => 'CrudJsonApi\Error\JsonApiExceptionRenderer',
'skipLog' => [],
'log' => true,
'trace' => true,
],
]);
$this->Crud->config(['listeners.jsonApi.exceptionRenderer' => 'CrudJsonApi\Error\JsonApiExceptionRenderer']);
$this->setJsonResponse();
}
public function beforeRender(Event $event)
{
$this->RequestHandler->renderAs($this, 'json');
$this->response->type('application/json');
$this->set('_serialize', true);
}
I thought using the JsonApiExceptionRenderer 404 errors would be handled with json output.
Also the Pagination works but the Pagination data isnt returned with the response...
{
"viewVar": "crmContacts",
"crmContacts": [
{
"id": 1,
"lastname": "testname1"
},
{
"id": 2,
"lastname": "smith"
}
],
"success": true
}
Any ideas?
Thanks

Appending data to JSON

I'm returning some json data as response in a Controller, i want to add some information to
In my DriversController extend's Apicontroller in DriversController i'm returning some data on api call, i want to appent the status code information to below response
if ($request->wantsJson()) {
return Response::json([
'data' => [
'user_details' => $agent_percentage,
'dropdown_data' => [
'employment_types' => $employment_types->all(),
'roles' => $roles->all(),
'vehicle_brands' => $vehicle_brands->all(),
'vehicle_types' => $vehicle_types->all()
]
]
]);
}
//to the above response
return Response::json([
$this->respondSuccess(), // i am append this information
'data' => [
'user_details' => $agent_percentage,
'dropdown_data' => [
'employment_types' => $employment_types->all(),
'roles' => $roles->all(),
'vehicle_brands' => $vehicle_brands->all(),
'vehicle_types' => $vehicle_types->all()
]
]
]);
In ApiControllre I'm setting all the status code and messages
class ApiController extends Controller
{
protected $statusCode = 200;
//getter status code
public function getStatusCode()
{
return $this->statusCode;
}
//setter status code
public function setStatusCode($statusCode)
{
$this->statusCode = $statusCode;
return $this;
}
//failure messages
public function respondFailure($message='Account is not active contact admin', $status='failure')
{
return $this->setStatusCode(400)->respondWithMessage($message, $status);
}
//success messages
public function respondSuccess($message='Agent is active', $status='success')
{
return $this->setStatusCode(200)->respondWithMessage($message, $status);
}
//a layer of abstraction to avoide repetation
public function respond($data, $headers = [])
{
return Response::json($data, $this->getStatusCode(), $headers);
}
//get ststus code and message parse it for errors
public function respondWithMessage($message, $status)
{
return $this->respond([
'status_code' => $this->getStatusCode(),
'status' => $status,
'message' => $message
]);
}
}
But the response i'm getting is different as expected
//expected result
{
"status_code": "200",
"status": "success",
"message": "User details with dropdown data",
"data": {
"user_details": {
"id": 2017001,
"name": "User Name",
"email": "user#email.com",
},
"dropdown_data": {
}
}
}
//getting response
{
"0": {
"headers": {},
"original": {
"status_code": 200,
"status": "success",
"message": "Agent is active"
},
"exception": null
},
"data": {
"user_details": {
"id": 2017001,
"name": "User Name",
"email": "user#email.com",
},
"dropdown_data": {
}
}
}
the middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Response;
use App\Http\Controllers\ApiController;
class UserStatus extends ApiController
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->user() === null)
{
return $this->respondFailure();
}
if($request->user()->isActive($request->user()))
{
return $next($request);
}
return $this->respondFailure();
}
}
You are only appending the response from the respondSuccess() and not merging the response.
$this->setStatusCode(200)->respondWithMessage($message, $status);
on this response:
return Response::json([
$this->respondSuccess(), // i am append this information
'data' => [
'user_details' => $agent_percentage,
'dropdown_data' => [
'employment_types' => $employment_types->all(),
'roles' => $roles->all(),
'vehicle_brands' => $vehicle_brands->all(),
'vehicle_types' => $vehicle_types->all()
]
]
]);
It gives the response as you got not the response you expected.
To get the expected response you need to do something like this:
public function respondWithMessage($message, $status)
{
return [
'status_code' => $this->getStatusCode(),
'status' => $status,
'message' => $message
];
}
I have used only array and not $this->respond() because you only have this message:
"status_code": "200",
"status": "success",
"message": "User details with dropdown data",
For the type of response, you might need to merge the two arrays into one.
Look on array_merge() to get more understanding.
$responseMessage= $this->respondSuccess();
$data = ['data' => [
'user_details' => $agent_percentage,
'dropdown_data' => [
'employment_types' => $employment_types->all(),
'roles' => $roles->all(),
'vehicle_brands' => $vehicle_brands->all(),
'vehicle_types' => $vehicle_types->all()
]
]
];
$responseArray = array_merge(responseMessage, data);
return Response::json($responseArray);
I have not yet tested the code but this might give you some understanding of how to get the expected array response you want.
If I am wrong anyone could suggest the edit.

How to send JSON via JavaScript and decode it in Perl?

I am trying to POST JSON using JavaScript and read the POST results using a Perl script. I have written this code but am unable to get the Perl script to read in the JSON text.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Testing ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var d = {
"name": "Bob",
"sex": "Male",
"address": {
"city": "San Jose",
"state": "California"
},
"friends": [
{
"name": "Alice",
"age": "20"
},
{
"name": "Laura",
"age": "23"
},
{
"name": "Daniel",
"age": "30"
}
]
};
$(document).ready(function() {
$("#test").click(function() {
$.ajax({
type: 'POST',
url: '/cgi-bin/Raghav_test/Apollo/read_ajax3.pl',
data: "r=" + d,
success: function(res) { alert("data" + res); },
error: function() { alert("did not work"); }
});
});
});
</script>
</head>
<body>
<button id="test">Testing</button>
</body>
</html>
Perl:
#!/usr/bin/perl -w
use CGI;
#use DBD;
use DBI;
use JSON::PP;
use Data::Dumper;
use DBD::Oracle qw(:ora_types);
use lib "/var/www/cgi-bin/ICE_LIBRARY/";
require '/var/www/cgi-bin/import_scripts/library/common_lib.pl';
require "/var/www/cgi-bin/import_scripts/library/script_log.pl";
use database_conf;
my $db = new database_conf;
#my $EP_dev_conn = $db->db_eportal_dev;
my $EP_prod_conn = $db->db_eportal_prod;
my $cgi = CGI->new;
my $id = $cgi->param("r");
#my $data = $cgi->param('POSTDATA');
print "Content-type:text/html\n\n";
#my $value = $ddata->{'address'}{'city'} ;
# Here I'd like to receive data from jQuery via ajax.
#my $id = $cgi->param('apiKey');
#$json = qq{{"ID" : "$id"}};
#my $method = $cgi->param('method');
#my $ip = $cgi->param('ip');
$json = qq{"$id"};
print $json;
exit;
You need to call JSON.stringify() on your object before making the request:
$.ajax({
type: 'POST',
url: '/cgi-bin/Raghav_test/Apollo/read_ajax3.pl',
data: { "r": JSON.stringify(d) },
success: function(res) { alert("data" + res); },
error: function() { alert("did not work"); }
});
And then you need to call decode_json() on the string to parse it and turn it into a Perl data structure:
my $q = CGI->new;
my $json = $q->param("r");
my $href = decode_json($json);
print Dumper($href);
Output:
$VAR1 = {
'address' => {
'state' => 'California',
'city' => 'San Jose'
},
'name' => 'Bob',
'friends' => [
{
'name' => 'Alice',
'age' => '20'
},
{
'age' => '23',
'name' => 'Laura'
},
{
'name' => 'Daniel',
'age' => '30'
}
],
'sex' => 'Male'
};