Renaming Google Slides Presentation (google slides API) - python

I'm trying to figure out how to rename a google slides presentation (ie. the document, not an individual slide). I've gone through a good amount of the Google Slide API Request documentation, but am still struggling to find the correct request. In my example, the objective is to rename the google presentation to "hello-world".
Being that I can't locate the right fields, when i go to execute the code below I keep receiving the following error:
<HttpError 400 when requesting https://slides.googleapis.com/v1/presentations/[PRESENTATION ID]:batchUpdate?alt=json returned "Invalid JSON payload received. Unknown name "Presentation" at 'requests[0]': Cannot find field.". Details: "[{'#type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'requests[0]', 'description': 'Invalid JSON payload received. Unknown name "Presentation" at \'requests[0]\': Cannot find field.'}]}]">
I've tried playing around with the request as much as possible, but still can't seem to figure it out. Provided below is the code. Any help is greatly appreciated.
slides_service = build('slides', 'v1', credentials=credentials)
presentationId = '####'
body = {
"requests": [{
"Presentation": {
"properties": {
"title": {
"description": "hello-world",
"type": "string"
}
}
}
}]
}
response = slides_service.presentations().batchUpdate(presentationId=presentationId,body=body).execute()

As per Yuri mentioned, Drive API would be much more reasonable instead.
Code:
new_title = 'hello-world'
file = {'title': new_title}
response = service.files().patch(fileId=file_id,
body=file,
fields='title').execute()
Reference:
Python Sample

Related

Twitter Ads API Unauthorized Issue

I am trying to access twitter ads API for fetching ad analytics. So when I tried to access the API : https://ads-api.twitter.com/11/stats/accounts/18ce55gz0e6?entity=LINE_ITEM&entity_ids=8u94t&start_time=2017-05-19&end_time=2017-05-26&granularity=TOTAL&placement=ALL_ON_TWITTER&metric_groups=ENGAGEMENT and gave Authorization : Bearer <bearer_token> as header. I got an Unauthorized error. This is the error that I got:
{
"errors": [
{
"code": "UNAUTHORIZED_ACCESS",
"message": "This request is not properly authenticated"
}
],
"request": {
"params": {}
}
}
Then I came across twitter-ads library https://github.com/twitterdev/twitter-python-ads-sdk
but I did'nt understand how to fetch campaign analytics using this. Can anyone please mention any solution?

YouTube API v3 - Python - how to batch insert playlistItems

I've been using the Youtube API to add multiple playlistItems to playlists on my profile, but doing so with loops tends to use up my daily request quota and I've hundreds to add.
I'm sending <50 video IDs per batch
the video IDs are all valid, and can be added succesfully one at a time
The new_batch_http_request method seems to be the solution but roughly 1 in every 4 video ids within the batch ends up failing. On Googling the problem it might be related to the position leading to overwrites?
Using this example, the first and third items were successful but the 2nd failed:
from Google import Create_Service
CLIENT_SECRET_FILE = 'client_secret_file.json'
API_NAME = 'youtube'
API_VERSION = 'v3'
SCOPES = ['https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.force-ssl']
service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)
playlistItemsList = ['eDTnKLqFuYU', 'TT7plfxWK6E','oMbL_7lpD1w']
batch = service.new_batch_http_request(callback=insert_video)
for videoId in playlistItemsList:
batch.add(
service.playlistItems().insert(part="snippet",
body={"snippet": {
"playlistId": "PLs7sB4wt2IftzifT5G4cdjQlXZQpEk2Go",
"position": 0,
"resourceId": {"kind": "youtube#video", "videoId": videoId},
}
},
),
)
request = batch.execute()
Using the callback function I can see that the failed attempts are returning:
<HttpError 500 when requesting https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&alt=json returned "Internal error encountered.". Details: "Internal error encountered.">
{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"errors": [
{
"message": "The request is missing a valid API key.",
"domain": "global",
"reason": "forbidden"
}
],
"status": "PERMISSION_DENIED"
}
}
Is there a way to sequentially add to playlist but utilising a batch method?
I noticed a serialise batch request within Google API docs - could this be what I'm looking for?
https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http.BatchHttpRequest-class.html#_execute
My code is based on this:
https://learndataanalysis.org/copy-videos-from-any-youtube-playlist-to-your-own-playlist-with-python-and-youtube-api/

Azure Cognitive text analytics Tool returns 400 Bad request Python

I am trying to use Azure Text analytics tool to extract topics but getting the 400 Bad request error: My code below:
account_key = '546e6162da424e6f991d03b7f6acxxx'
headers = {
'Ocp-Apim-Subscription-Key': account_key,
'Content-Type': 'application/json',
'Accept': 'application/json'}
import requests
tufani={
"documents": [
{
"language": "en",
"id": "1",
"text": "First document"
},
{
"language": "en",
"id": "100",
"text": "Final document"
}
]
}
print('Starting topic detection.')
uri = base_url + 'text/analytics/v2.0/topics'
r=requests.post('https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/topics',data=str(tufani),headers =headers)
print(r.status_code, r.reason)
(400, 'Bad Request')
What am I doing wrong in this?
Thanks!
I tried to reproduce your issue, and I discovered the 400 Bad Request error for your code was caused by as below if using print(r.text).
u'{"code":"BadRequest","message":"Invalid request","innerError":{"code":"InvalidRequestContent","message":"Requests to this API should contain at least 100 documents, where each document is not null or empty","minimumNumberOfDocuments":100}}'
It also show in the offical tutorial Task 3 - Detect topics in a corpus of text, as below.
This API requires a minimum of 100 text records to be submitted, but is designed to detect topics across hundreds to thousands of records. Any non-English records or records with less than 3 words will be discarded and therefore will not be assigned to topics. For topic detection, the maximum size of a single document that can be submitted is 30KB, and the total maximum size of submitted input is 30MB. Topic detection is rate limited to 5 submissions every 5 minutes.
So please add the enough text records for using the API.
You should not use str(tufani) to encode data for POST request, instead requests will automatically encode dict data for you:
r=requests.post('https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/topics',data=tufani,headers =headers)
P.S. If server accepts JSON-Encoded POST/PATCH data, you could use json.dumps(payload) to do the job.
The solution suggested by Shane and Peter both are the errors I was missing and these suggestion solved the issue.
Thanks!

Why does Google Drive API returns incomplete response?

I'm using google-api-python-client to call the Google Drive API.
According to the API's spec, get should return a JSON with many fields. But my program only returns id, name, mimeType and kind as follows:
{
"id": <omitted>,
"name": "myfile.txt",
"mimeType": "text/plain",
"kind": "drive#file"
}
How do I get other metadata about a file using this API?
All right. I found the answer. The info on the spec page is incomplete. As pointed out in another page, the API calls accept a fields parameter which specify the fields to return.

YouTube api Error

I am a little confuse! I am trying to develop a script that can pull youtube video id in python. So I went ahead and set up my youtube API key.I use this page to generate the URL.
https://developers.google.com/youtube/v3/docs/search/list
This page generated a sample JSON table with the video ID. But when I put this url in my browser
https://www.googleapis.com/youtube/v3/search?part=id&q=gullybop&key={YOUR_API_KEY}
and yes I filled in my api. I expected to get back a JSON table with the vid ids but I get this instead
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "keyInvalid",
"message": "Bad Request"
}
],
"code": 400,
"message": "Bad Request"
}
}
I don't think my API key is invalid
I expected when I put the URL in the browser it would return a JSON table with vid ids but instead I got that error above.
Why am I getting this error ?
Thank you Sean
I got JSON results when I accessed this URL with my API Key. So your API key will be invalid nothing else. Try to create another project in API console and create a key without any referrer no server IP. Only generate 1 key in a project. Dont forget to enable YouTube Data API v3 in API manager.

Categories