How to Get Hyperlinks Using Google Sheets API v4 - google-sheets

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

Related

Getting names from geo_target_constant in a Ad report

I am using ads API for getting the spends based on state names of USA.
The below query gives segments.geo_target_state will be returned as an ID instead of name
How can I combine this query with
SELECT
geo_target_constant.name,
geo_target_constant.canonical_name
FROM geo_target_constant
WHERE geo_target_constant.id = <<OBTAINED ID FROM THE BELOW QUERY>>
curl "https://googleads.googleapis.com/v10/customers/${CUSTOMER_ID}/googleAds:searchStream" \
--header "Content-Type: application/json" \
--header "developer-token: ${DEVELOPER_TOKEN}" \
--header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \
--header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \
--data '{
"query": "
SELECT
campaign.name,
segments.geo_target_state,
metrics.cost_micros
FROM geographic_view
WHERE
geographic_view.location_type = LOCATION_OF_PRESENCE
AND segments.date BETWEEN 20220101 AND 20220430
"
}'
That is geoTargetConstants/21136 must be decoded to
"name": "New Jersey",
"results": [
{
"campaign": {
"resourceName": "customers/1234/campaigns/1234",
"name": "Display - macines - Leads Display Campaign Test - AA"
},
"metrics": {
"costMicros": "66664821"
},
"segments": {
"geoTargetState": "**geoTargetConstants/21136**"
},
"geographicView": {
"resourceName": "customers/6383148790/geographicViews/2840~LOCATION_OF_PRESENCE"
}
},
If you want to use the API to lookup the geo target constant name you will have to issue another search request using the query you provided.
This is likely okay in one off scenarios but breaks down quickly if you need to retrieve multiple geo target constants.
What I have do to resolve this is pull the list of geo targets, see: https://developers.google.com/google-ads/api/reference/data/geotargets, and store them locally in a database. Then I can pull the name from a must faster source.

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 take data in google sheet script via POST request in JSON format?

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.

BitBucket 1.0 REST API Retrieve all Pull-Requests for repository

When I curl the rest api, I get back an empty response but I know that there are pull-requests open.
What is the setting in bitbucket stash that allows anyone to view/read pull-requests without being authenticated?
curl -X GET https://bitbucket/rest/api/1.0/projects/{project}/repos/{repo}/pull-requests
response:
{
"size": 0,
"limit": 25,
"isLastPage": true,
"values": [],
"start": 0
}
Try
curl -X GET https://bitbucket/rest/api/1.0/projects/{project}/repos/{repo}/pull-requests?state=ALL
You can find more options for this specific API call at https://developer.atlassian.com/static/rest/bitbucket-server/latest/bitbucket-rest.html#idm140236731714560
This worked for me:
curl -D- -u user:password -X GET -H "Content-Type: application/json" -X GET https://bitbucket.com/rest/api/1.0/projects/ONEP/repos/oneplanner/pull-requests?state=OPEN
To check status to particular PR:
curl -X GET https://bitbucket/rest/api/1.0/projects/{project}/repos/{repo}/pull-requests/{pr-id}
DOC https://docs.atlassian.com/bitbucket-server/rest/5.16.0/bitbucket-rest.html#idm8287391664
Paged APIs
Bitbucket uses paging to conserve server resources and limit response size for resources that return potentially large collections of items. A request to a paged API will result in a values array wrapped in a JSON object with some paging metadata, like this:
{
"size": 3,
"limit": 3,
"isLastPage": false,
"values": [
{ /* result 0 */ },
{ /* result 1 */ },
{ /* result 2 */ }
],
"start": 0,
"filter": null,
"nextPageStart": 3
}
Clients can use the limit and start query parameters to retrieve the desired number of results.
The limit parameter indicates how many results to return per page. Most APIs default to returning 25 if the limit is left unspecified. This number can be increased, but note that a resource-specific hard limit will apply. These hard limits can be configured by server administrators, so it's always best practice to check the limit attribute on the response to see what limit has been applied. The request to get a larger page should look like this:
http://host:port/context/rest/api-name/api-version/path/to/resource?limit={desired size of page}
For example:
https://stash.atlassian.com/rest/api/1.0/projects/JIRA/repos/jira/commits?limit=1000
The start parameter indicates which item should be used as the first item in the page of results. All paged responses contain an isLastPage attribute indicating whether another page of items exists.
Important: If more than one page exists (i.e. the response contains "isLastPage": false), the response object will also contain a nextPageStart attribute which must be used by the client as the start parameter on the next request. Identifiers of adjacent objects in a page may not be contiguous, so the start of the next page is not necessarily the start of the last page plus the last page's size. A client should always use nextPageStart to avoid unexpected results from a paged API. The request to get a subsequent page should look like this:
http://host:port/context/rest/api-name/api-version/path/to/resource?start={nextPageStart from previous response}
For example:
https://stash.atlassian.com/rest/api/1.0/projects/JIRA/repos/jira/commits?start=25

YouTube artist charts api?

Does YouTube expose it's artist charts via api or is there a way to get the charts data using the youtube api?
I'm talking about the charts data here https://artists.youtube.com/charts/videos
I don't think it's possible using the official Youtube API, if we look at https://artists.youtube.com/charts/videos, it uses YouTube Internal API (InnerTube) with a specific API key (registered to use youtubei API which is not available to developers)
Of course it's a hack just FYI
The API key has https://artists.youtube.com configured as referer, adding the custom header: x-referer:https://artists.youtube.com make it works :
curl -H 'Content-Type: application/json' \
-H "x-referer:https://artists.youtube.com" \
"https://content.googleapis.com/youtubei/v1/browse?alt=json&key=AIzaSyCzEW7JUJdSql0-2V4tHUb6laYm4iAE_dM" \
-d '{
"context": {
"client": {
"clientName": "WEB_MUSIC_ANALYTICS",
"clientVersion": "0.2",
"theme": "MUSIC",
"hl": "en",
"gl": "FR",
"experimentIds": []
},
"capabilities": {
},
"request": {
"internalExperimentFlags": []
}
},
"browseId": "FEmusic_analytics",
"query": "chart_params_type=WEEK&perspective=CHART&flags=viral_video_chart&selected_chart=VIRAL_VIDEOS"
}'
If it doesn't work, get the API key from the network log of https://artists.youtube.com
In the query field, you can modify the selected_chart parameter :
all video :
selected_chart=VIDEOS
viral videos chart :
selected_chart=VIRAL_VIDEOS
artists :
selected_chart=ARTISTS
tracks :
selected_chart=TRACKS

Resources