How to take data in google sheet script via POST request in JSON format? - post

This question is about receiving POST request from somewhere. I'm looking for a google sheet script function that can take and handle data from the POST request in JSON format. Could you suggest any example?
The POST request is here:
https://script.google.com/macros/s/BOdirjv45Dn6FHrx_4GUguuS6NJxnSEeviMHm3HerJl4UsDBnDgfFPO/
{
"p1": "writeTitle",
"p2": [[URL]],
"p3": [[PIC_A]],
"p4": [[PIC_B]],
"p5": [[TITLE]]
}
application/json
doPost() doesn't work:
doPost(e) {
var json = JSON.parse(e.postData.contents);
Logger.log(json);
}

You want to retrieve the value from the request body as an object.
You have already deployed Web Apps.
If my understanding of your situation is correct, how about this modification?
Post and retrieved object:
As a sample, I used the following curl command to POST to Web Apps.
curl -L \
-H 'Content-Type:application/json' \
-d '{"p1": "writeTitle","p2": "[[URL]]","p3": "[[PIC_A]]","p4": "[[PIC_B]]","p5": "[[TITLE]]"}' \
"https://script.google.com/macros/s/#####/exec"
When above command is run, e of doPost(e) is as follows.
{
"parameter": {},
"contextPath": "",
"contentLength": 90,
"queryString": "",
"parameters": {},
"postData": {
"type": "application/json",
"length": 90,
"contents": "{\"p1\": \"writeTitle\",\"p2\": \"[[URL]]\",\"p3\": \"[[PIC_A]]\",\"p4\": \"[[PIC_B]]\",\"p5\": \"[[TITLE]]\"}",
"name": "postData"
}
}
The posted payload can be retrieved by e.postData. From above response, it is found that the value you want can be retrieved by e.postData.contents. By the way, when the query parameter and the payload are given like as follows,
curl -L \
-H 'Content-Type:application/json' \
-d '{"p1": "writeTitle","p2": "[[URL]]","p3": "[[PIC_A]]","p4": "[[PIC_B]]","p5": "[[TITLE]]"}' \
"https://script.google.com/macros/s/#####/exec?key=value"
value can be retrieved by e.parameter or e.parameters. And the payload can be retrieved by e.postData.contents.
Modified script:
In this modified script, the result can be seen at the Stackdriver, and also the result is returned.
function doPost(e) {
var json = JSON.parse(e.postData.contents);
console.log(json);
return ContentService.createTextOutput(JSON.stringify(json));
}
Note:
When you modified your script of Web Apps, please redeploy it as new version. By this, the latest script is reflected to Web Apps. This is an important point.
Reference:
Web Apps
Stackdriver Logging
If this was not what you want, I'm sorry.

Related

calling activities:list fails on using parameter `mine=true` (Youtube Data API V3)

I have been trying to use the API to retrieve my activities but I'm receiving the following JSON error.
{
"error": {
"code": 403,
"message": "The request is not properly authorized.",
"errors": [
{
"message": "The request is not properly authorized.",
"domain": "youtube.activity",
"reason": "forbidden"
}
]
}
}
, although I use https://www.googleapis.com/youtube/v3/activities?mine=true&key={my_api_key}&part=contentDetails and I use OAuth2 client to get an access token which I use on calling the API.
I tried to use the samples but I'm receiving the same error.
Is this a bug or I'm doing something wrong?
More details
I use the given link in postman with the GET method and I put a valid access token in the token field with TYPE=OAuth2 and Prefix=Bearer
According to the official specification of the Activities.list API endpoint, for to be able to use its mine request parameter, you have to issue the call to the endpoint while passing to it proper credentials:
mine (boolean)
This parameter can only be used in a properly authorized request. Set this parameter's value to true to retrieve a feed of the authenticated user's activities.
Therefore, using an API key is not sufficient (neither is required when issuing a properly authorized request).
Do note that the JSON error response obtained from the API agrees entirely with the specification quoted above.
According to the official (programming language agnostic) procedure, for to obtain a valid fresh access token from the API, issue a simple curl instance as follows:
$ curl \
--data 'grant_type=refresh_token' \
--data-urlencode "client_id=$CLIENT_ID" \
--data-urlencode "client_secret=$CLIENT_SECRET" \
--data-urlencode "refresh_token=$REFRESH_TOKEN" \
https://oauth2.googleapis.com/token
Above, $CLIENT_ID and $CLIENT_SECRET are the values of the corresponding properties of your client secrets JSON file you've got from Google's developers console. The $REFRESH_TOKEN is your (long-lived) refresh token you've obtained upon running a successful OAuth2 authentication/authorization flow.
The output obtained from curl when successful would look like:
{
"access_token": "...",
"expires_in": 3599,
"scope": "...",
"token_type": "Bearer"
}
A call to the Activities.list endpoint as yours above using curl is immediate:
$ curl \
--header "Authorization: Bearer $ACCESS_TOKEN" \
'https://www.googleapis.com/youtube/v3/activities?mine=true&part=contentDetails&maxResults=25'
The parameter $ACCESS_TOKEN above is your freshly obtained valid access token; the output of curl would look like:
{
"kind": "youtube#activityListResponse",
"etag": "...",
"items": [
{
"kind": "youtube#activity",
"etag": "...",
"id": "...",
"contentDetails": {
...
}
},
...
],
"pageInfo": {
"totalResults": ...,
"resultsPerPage": 25
}
}
For to run the above curl commands on a Windows machine under CMD.exe -- assuming that you've substitued the $-variables yourself manually --, do replace the backslash character at the end of each line above with the caret character, ^. The percent character % should be doubled, i.e. should be replaced with %%, and the single quote characters ' should be replaced with double-quote characters ".

How to Get Hyperlinks Using Google Sheets API v4

I am trying to access a hyperlink using the v4 API ValueRenderOption param (valueRenderOption=FORMULA). I have tried with both python's gsheets and cURL. Either way, I cannot seem to get the formula that will show a hyperlink. Below is a screenshot of the spreadsheet; note the cell containing the value 2 has its formula shown, as expected, but that the hyperlink to https://example.com is shown as "sup". Is there a new way that we are supposed to access the contents of hyperlinks?
gsheets:
print(worksheet.acell('A2', value_render_option="FORMULA").value)
# sup
cURL:
URL="https://sheets.googleapis.com/v4/spreadsheets/$SHEET_ID/values/%27Sheet1%27%21A2"
curl -X GET "$URL?valueRenderOption=FORMULA" -H "Authorization: Bearer $TOKEN"
# output
{
"range": "Sheet1!A1:Z1001",
"majorDimension": "ROWS",
"values": [
[
"Name",
"Other"
],
[
"sup",
"word"
],
[
"k",
100
],
[
"=AVERAGE(1,2,3)",
"k"
]
]
}
I believe your goal as follows.
You want to retrieve a hyperlink which was set to a cell on Google Spreadsheet.
In this case, in the current stage, the hyperlink can be retrieved using the method of "spreadsheets.get" in Sheets API. And, it is required to use the field parameter for this request. By this, the hyperlink can be retrieved. The sample curl command is as follows.
As the sample situation, it supposes that the URL is set to a cell "A1" of "Sheet1" in Google Spreadsheet.
Sample curl command:
curl \
'https://sheets.googleapis.com/v4/spreadsheets/[SPREADSHEETID]?ranges=Sheet1!A1&fields=sheets(data(rowData(values(hyperlink))))' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--compressed
Result:
{
"sheets": [
{
"data": [
{
"rowData": [
{
"values": [
{
"hyperlink": "https://example.com/"
}
]
}
]
}
]
}
]
}
For gspread:
At gspread, requests library is used as follows. The access token is retrieved from credentials of gspread.authorize(credentials).
gc = gspread.authorize(credentials)
access_token = credentials.access_token
url = 'https://sheets.googleapis.com/v4/spreadsheets/[SPREADSHEETID]?ranges=Sheet1!A1&fields=sheets(data(rowData(values(hyperlink))))'
res = requests.get(url, headers={'Authorization': 'Bearer ' + access_token})
print(res.json())
Result:
{'sheets': [{'data': [{'rowData': [{'values': [{'hyperlink': 'https://example.com/'}]}]}]}]}
Note:
In this sample, sheets(data(rowData(values(hyperlink)))) is used as fields. About this, you can also use sheets. In this case, other values are included in the response values.
At the sample, Sheet1!A1 is used as the range. So please modify this range for your actual situation.
In the current stage, when a hyperlinks is set to a part of texts in a cell and the several hyperlinks are set to a cell, unfortunately, those cannot be directly retrieved using Sheets API. At that time, as the current workaround, it is required to use Google Apps Script. Ref Please be careful this.
References:
Method: spreadsheets.get

Cumulocity - Send Measurement/Alarm/Event using external ID via HTTP

I've been recently exploring Cumulocity and managed to use the external ID to send data (measurements/alarms/events) via MQTT. Its well documented and pretty straight forward.
But I cant find how to send data (measurement/alarm/event) using ExternalID instead of source.
For example, here is how POST of a measurement looks like if you know ClientID of device:
curl -X POST \
https://myTenant.cumulocity.com/measurement/measurements \
-H 'Accept: application/vnd.com.nsn.cumulocity.measurement+json' \
-H 'Authorization: Basic mytoken' \
-H 'Content-Type: application/json' \
-d '{
"c8y_TemperatureMeasurement": {
"T": {
"value": 25,
"unit": "C" }
},
"time":"2019-03-07T10:03:14.000+11:00",
"source": {
"id":"1234567" },
"type": "c8y_TemperatureMeasurement"
}'
Is there a way to replace that "source": {"id":"1234567" }, with external ID?
What would the request look like?
As of today, this is not possible:
Instead you have to first convert the externalID to the source id once (e.g. when the device is booted its done as first actions). Afterwards send all requests (e.g. POSTs to create measurements/alarms/events) using this retrieved sourceID.
This is also described in the Device SDK for HTTP here: https://cumulocity.com/guides/device-sdk/rest#step-1-check-if-the-device-is-already-registered .
Thanks for the good feedback on the documentation!

Failed to exchange a code for an access token for creating zendesk instance in cloud element through API

Please help to create zendesk instance in cloud element by 3rd party api call
Created Zendesk account Created & configure as per in Link
Succesfully got Elements OAuth Information
{
"oauthUrl": "https://yoursubdoamin.zendesk.com/oauth/authorizations/new?response_type=code&client_id=zendesk_unique_identifier&redirect_uri=http://www.my_cool_app.com/auth&scope=read write&state=zendesk",
"element": "zendesk"
}
Getting error in API
curl -X POST
-H 'Authorization: User <INSERT_USER_SECRET>, Organization <INSERT_ORGANIZATION_SECRET>'
-H 'Content-Type: application/json'
-d #instance.json
'https://api.cloud-elements.com/elements/api-v2/instances'
instance.json
{
"element": {
"key": "zendesk"
},
"providerData": {
"code": "Code on Return the URL"
},
"configuration": {
"oauth.api.key": "<INSERT_ZENDESK_UNIQUE_IDENTIFIER>",
"oauth.api.secret": "<INSERT_ZENDESK_CLIENT_SECRET>",
"oauth.callback.url": "https://www.my_cool_app.com",
"zendesk.subdomain": "<INSERT_ZENDESK_SUB_DOMAIN>"
},
"tags": [
"<INSERT_TAGS>"
],
"name": "<INSERT_INSTANCE_NAME>"
}
Getting error "Failed to exchange a code for an access token"
This might be because, you might not have registered an app with zendesk to get back the access token. This can also happen if your element in Cloud Elements is corrupted, make sure you are using the inbuild element instance. Still if you are facing the issue, please mention the steps you followed

How to create remote JIRA Issue with ruby-jira Gem

I'm trying to use the jira-ruby Gem to interface with a remote JIRA server with 5.x REST API.
Accessing data on the server works well, but it seems I can not create a new JIRA issue remotely. The Gem's documentation is minimal, and there are no examples provided.
Can somebody provide a working example on:
how to create a remote JIRA Issue with ruby-jira
how to attach a file to an existing Issue
To create new JIRA Issue use:
CODE:
issue = client.Issue.build
issue.save({"fields"=>{"summary"=>"blarg from in example.rb","project"=>{"id"=>"10001"},"issuetype"=>{"id"=>"3"}}})
issue.fetch
pp issue
Or
You can try REST APIs to create JIRA Issue.
Using IDs
The first example creates an issue by specifying the project ID and issue type ID.
Request
curl -D- -u fred:fred -X POST --data {see below} -H "Content-Type: application/json" http://localhost:8090/rest/api/2/issue/
Data
Here's the JSON:
{
"fields": {
"project":
{
"id": "10110"
},
"summary": "No REST for the Wicked.",
"description": "Creating of an issue using ids for projects and issue types using the REST API",
"issuetype": {
"id": "1"
}
}
}
Response
The response provides the issue ID, issue key, and the URL to the issue (which can then be used to GET additional data, PUT updates, etc).
{
"id":"39001",
"key":"TEST-102",
"self":"http://localhost:8090/rest/api/2/issue/TEST-102"
}
Using Project Key and Field Names
Alternatively, you can create an issue by specifying the project key and field names.
Request
curl -D- -u fred:fred -X POST --data {see below} -H "Content-Type: application/json" http://localhost:8090/rest/api/2/issue/
Data
{
"fields": {
"project":
{
"key": "TEST"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Bug"
}
}
}
Response
{
"id":"39000",
"key":"TEST-101",
"self":"http://localhost:8090/rest/api/2/issue/TEST-101"
}
Source: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+APIs

Resources