Setting spreadsheet title with Guzzle in PHP - php

I am connected to my Google sheets, when I run a post request for https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/create and set no properties, it creates a new spreadsheet.
I would love to add a title so I did this
$options = [
'form_params' => [
'properties' => [
'title' => 'A new title'
]
]
];
$client->post('v4/spreadsheets', $options);
I am using Guzzle to make this call. As a response I'm getting HTTP status code 400 (Bad Request) when adding title to form params.
How can I solve this?

You really should be using Google's SDK for this since they already have support for one in PHP.
According to their docs, sheet properties are set in a Google_Service_Sheets_SpreadsheetProperties instance which takes the title property.
An example from their docs:
<?php
$spreadsheet = new Google_Service_Sheets_Spreadsheet([
'properties' => [
'title' => $title
]
]);
$spreadsheet = $service->spreadsheets->create($spreadsheet, [
'fields' => 'spreadsheetId'
]);
printf("Spreadsheet ID: %s\n", $spreadsheet->spreadsheetId);

Related

Center an image in header with api google doc

i tried to insert an image in my header. it's ok.
And now i want to center the picture but i'm just stuck.
$requests[] = new \Google_Service_Docs_Request(array(
'insertInlineImage' => array(
'uri' => 'https://myPicture.png',
'location' => array(
'segmentId' => $document->getDocumentStyle()->getDefaultHeaderId(),
'index' => 0
),
),
));
You want to insert an inline image at the center of the header in Google Document.
You want to achieve this using google-api-php-client with PHP.
You have already been able to get and put values for Google Document using Google Docs API.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification point:
In order to put the image at the center, please add UpdateParagraphStyleRequest to the request body of the batchUpdate, because InsertInlineImageRequest has no propaty of alignment.
Modified script:
$documentId = '###'; // Please set the Document ID.
$segmentId = $document->getDocumentStyle()->getDefaultHeaderId();
$service = new Google_Service_Docs($client);
$requests = [
new Google_Service_Docs_Request([
'insertInlineImage' => [
'location' => ['index' => 0, 'segmentId' => $segmentId],
'uri' => 'https://icir.int.demedicis.fr/img/logo/veolia.png'
]
]),
new Google_Service_Docs_Request([
'updateParagraphStyle' => [
'range' => ['startIndex' => 0, 'endIndex' => 1, 'segmentId' => $segmentId],
'paragraphStyle' => ['alignment' => 'CENTER'],
'fields' => 'alignment'
]
])
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(['requests' => $requests]);
$result = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
Note:
When $document->getDocumentStyle()->getDefaultHeaderId() cannot be used, please set the header ID like kix.### as the string value.
This is a simple modification. So please reflect this to your actual script.
References:
UpdateParagraphStyleRequest
InsertInlineImageRequest
If I misunderstood your question and this was not the direction you want, I apologize.

Upload a File to a Task on Cerb API

At the moment I am adding a task to Cerb using the API (Docs: https://cerb.ai/docs/api/). I can add and edit comments on the task.
An extension is to add file uploads. The API documentation seems to be extremely limited in terms of file uploads and isn't helping much. I have based my current code on https://cerb.ai/docs/api/endpoints/records/#update, using a custom field linked to the task and posting directly to the API.
The process is as follows:
1 - User inserts information on a Laravel form
2 - Form is submitted, task is created
3 - If the user entered a comment or description, the controller then uses the ID from the newly created task toa dd the comment
4 - If the user adds a file, the controller should then use the same ID from the task to attach the file
Task and comment adding has been done through models, which were previously done directly through the API and reformatted once they worked.
Add Task:
$params = [
'title' => $request->input('title'),
'links' => ['project:'.$request->input('project')],
'priority' => $request->input('priority'),
'status_id' => 2
];
$due_date = $request->input('due');
if(!empty($due_date)){
$params['due'] = strtotime($due_date);
}
$success_task = $task->addUpdateRecord('tasks.add', $params);
Add Comment:
$params = [
'author__context' => 'bot',
'author_id' => 3,
'comment' => empty($comment_input) ? request()->comment : $comment_input,
'target__context' => 'task',
'target_id' => $task_id,
'author' => Auth::user()->name // custom field
];
$success = $comment->addUpdateRecord('comments.add', $params);
The addUpdateRecord() essentially does the same thing as the file upload as below:
$cerb = new CerbApi();
$out = $cerb->put($root.'records/file_bundle/1054.json?expand=custom_', $putfields);
$putfields contains a normal file upload object.
I'm getting the following error on request:
array:2 [▼
"__status" => "error"
"message" => "Unknown command (root/records/task/1054.json)"
]
(root removed for confidentiality)
Has anyone worked with this? Anyone able to assist?
Ended up getting it right by using the attachments record type https://cerb.ai/docs/records/types/attachment/ and creating a model for it with its own addUpdateRecord() method.
I then used the records API to do the post for the file as the first step instead of the last one:
$file_upload = new File;
// Get file contents
$data = file_get_contents($file);
// Base64 encode contents
$data = base64_encode($data);
$file_params = [
'name' => $file->getClientOriginalName(),
'content' => $data
];
// Do upload
$file_success = $file_upload->addUpdateRecord('files.add', $file_params);
// Only need to return the file ID to link it to the task
return $file_success["data"]["id"];
And then using the ID that was being returned to link it to the task:
$task = new Task();
$params = [
'title' => $request->input('title'),
'links' => [
'project:'.$request->input('project'),
'file:'.$file_id
],
'priority' => $request->input('priority'),
'status_id' => 2
];
I hope this helps someone in the future.
Note: Cerb API Version 9.2.0

Post data and file together to Laravel API using Guzzle

I've two working project communicating between each other via an API built in a Laravel. So far there is only simple POST requests made with GuzzleHttp 6.
And I am currently trying to have a new POST request made from 1 to 2, which would send a couple of simple fields along with one file.
Project 1 has a form, on the form submit I handle the data and want to send them to project 2 via a POST request to this new API endpoint.
I've tried different guzzle options 'multipart', 'form_data' etc and realised they may not be combined together. Now I understood that this options are exclusive and using only "multipart" seems the way to go.
But when I send my request to Laravel no data nor file are there.
Here is the code for my request
$options = ‌[
'multipart' =>
[
[
'name' => 'data',
'contents' => '{"field_1":"Test","field_2":"Test","field_3":"Test"}',
'headers' =>
[
'Content-Type' => 'application/json',
],
],
[
'name' => 'file',
'filename' => 'test.pdf',
'Mime-Type' => 'application/pdf',
'contents' => file_get_contents($_FILEs['text_file']['temp_name']),
]
]
];
$this->client->request('POST', "api/test_post", $options)
I also gve this a try:
$options = ‌[
'multipart' =>
[
[
'name' => 'field_1',
'contents' => 'Test',
],
[
'name' => 'field_2',
'contents' => 'Test',
],
[
'name' => 'file',
'filename' => 'test.pdf',
'Mime-Type' => 'application/pdf',
'contents' => fopen($_FILEs['text_file']['temp_name'],'r'),
]
]
];
$this->client->request('POST', "api/test_post", $options)
If I look the request content on the receiving end, nothing is there. No field or file.
I've seen couples posts, some say to include headers some say not too. I kinda got lost and amd now running out of ideas.
I would expecet the infos to be as if they where form post I guess:
$request->inpust('field_1') -> 'test'
$request->inpust('field_2') -> 'test'
$request->inpust('field_3') -> 'test'
$request->file('file') -> my uploaded file
Also I should point out that I am not exactly sure how multipart/form-data works, so that might not help me.
If you can point me to the right direction, that would help a lot
Well I finally figured it out. The second example from above is the way to go also be sure to check the headers of the request and the client...
As this API has been running for quite some time and was only doing json type requests, the Client was instantiated with
$options = [
headers => [ 'Content-Type' => 'application/json']
]
Which, as stated in multiple answers across the internet, prevents Guzzle to automatically set the Content-Type depending of the request options.
In my case, removing this line made Guzzle enable to set it properly when provided with 'multipart' option.
Also, as all other requests are using the 'json' options, Guzzle also works it's magic and set 'Content-Type' => 'application/json' as well.

_update_by_query in elasticserach-php client

I am using elasticsearch 6.2 with elasticsearch-php 6.0 client. There is situation i got stuck. I need to update field userid = 987 where userid = 123. I went through update API, Here in every query we need to pass document ID in API (like POST test/_doc/1/_update). First i need to fetch _id and then i have to make update query with POST test/_doc/{_id}/_update
It won't possible to every time produce _id. It didn't help me.
I found another option to use _update_by_query. In which i got success by using following API:
curl -XPOST 'localhost:9200/my_index/my_type/_update_by_query?pretty' -H 'Content-Type: application/json' -d '
{
"query":{
"term":{
"userid":123
}
},
"script":{
"lang":"painless",
"inline":"ctx._source.userid = params.value",
"params":{
"value":987
}
}
}'
I am not finding any reference which shows how i can use _update_by_query with elasticserach-php client. Plus let me know if you guyz have better way to tackle this. Thanks!
I got solution So i would like to share:
$client = \Elasticsearch\ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
$update = [
'index' => 'my_index',
'type' => 'my_type',
'conflicts' => 'proceed',
'body' => [
'query' => [
'term' => [
"userid" => 987
]
],
'script' => [
'lang' => 'painless',
'inline' => 'ctx._source.userid = params.userid',
'params' => [
'userid' => 123
]
]
]
];
$results = $client->updateByQuery($update);
It solve my problem. I think elasticserach should document this.

elasticsearch-php create index returns \BadRequest400Exception

I have a fresh installation of elasticsearch 5.0.0 and elasticsearch-php . I am trying to create an index.
I run the code from this index management documentation:
$client = ClientBuilder::create()->build();
$params = [
'index' => 'my_index'
];
// Create the index
$response = $client->indices()->create($params);
and it works. I create an index successfully.
I try the next code snippet:
$client = ClientBuilder::create()->build();
$params = [
'index' => 'my_index',
'body' => [
'settings' => [
'number_of_shards' => 3,
'number_of_replicas' => 2
],
'mappings' => [
'my_type' => [
'_source' => [
'enabled' => true
],
'properties' => [
'first_name' => [
'type' => 'string',
'analyzer' => 'standard'
],
'age' => [
'type' => 'integer'
]
]
]
]
]
];
// Create the index with mappings and settings now
$response = $client->indices()->create($params);
and I get:
Elasticsearch\Common\Exceptions\BadRequest400Exception with message 'No handler found for uri [/my_index] and method [POST]'
any ideas why?
This code used to work when I used elasticsearch 2.0
EDIT: I found this question so either it is a problem with elasticsearch-php or I need to update it I guess
I am using elasticquent which I have just realized requires elasticsearch-php version <2.2 so this is what is causing the problem
Looking at the error message:
No handler found for uri [/my_index] and method [POST]
This means that your create index call is using an HTTP POST method under the hood. In previous versions (i.e. pre 5.0), the elasticsearch-php client used to create indices with an HTTP POST but since ES 5.0 only HTTP PUT is accepted to create a new index.
This change back in september made this create call compatible with ES 5.0 again.
The only possible explanation is that you have ES 5.0 installed but you don't have the 5.0 version of the elasticsearch-php client installed.
Since you're running Elasticquent which doesn't yet support ES 5, you can temporarily go around this issue by modifying the Endpoints/Indices/Create.getMethod() method to always return PUT instead of POST and your call will work again, but you might run into other incompatibilities.

Categories