GET/POST requests Google Drive API - google-drive-api

I learning currently Google Drive API and developing program in Qt C + + (using OAuth2), so I need to build queries, but I'm not found how to do it.
For example, if I make a request - https://www.googleapis.com/oauth2/v1/userinfo?access_token=MY_ACCESS_TOKEN, everything is working OK - I get the reply.
Question is: how to make a SIMILAR request for the Google Drive?
1) how can I get a list of folders and files
2) how can I create a folder / file
etc.
For example, in a POST request
"https://www.googleapis.com/drive/v1/files&title=pets&mimeType=application/vnd.google-apps.folder"
I get
"error": {
"errors": [{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
how to get a list of folders and files, for example, etc., I do not understand
Any opinions/examples are welcome!
thanks in advance

Unfortunately, the Drive API doesn't let you list folders or files. The only way to retrieve a file is by integrating with the Drive web UI or showing a Google Picker to your user (web app only).
Once you have a File ID, you can simply send an authorized GET request to the drive.files.get endpoint:
GET https://www.googleapis.com/drive/v1/files/id
To insert a file (or a folder), the File's metadata is to be included in the request body, not as query parameter:
POST https://www.googleapis.com/drive/v1/files
Authorization: Bearer {ACCESS_TOKEN}
Content-Type: application/json
...
{
"title": "pets",
"parentsCollection": [{"id":"0ADK06pfg"}]
"mimeType": "application/vnd.google-apps.folder"
}
In the example above, the mimeType specifies that the resource being inserted is a folder. Change the mimeType to your application MIME type when inserting a file.

You should use google docs API for that
Retrieving a list of collections - Google Documents List API version 3.0
In OAuth 2.0 Playground just select both Documents List and Google Drive
And you will get full list of operations:
List FolderContent
GET https://docs.google.com/feeds/default/private/full/{folderResouceId}/contents
Don't forget to add the ?v=3 query parameter to the Document list URI or adding
GData-Version: 3.0
header, otherwise it will return "Invalid request URI".

You advise you to look at the google drive api reference docs in
https://developers.google.com/drive/v3/reference/files/list
i succeeded using many api functions following link above and using curl. But actually i recommend you trying to do http requests with a tool like postman. Anyway after getting access code following the steps link below
list google drive files with curl
try to make following command in the command line.
curl -H 'GData-Version: 3.0' -H "Authorization: Bearer $ACCESS_TOKEN" \
https://www.googleapis.com/drive/v2/files?maxResults=$100

Related

Google Drive API - Searching for files within folders

This question is not how about to search within folders, but why I'm not getting the correct results.
This is how I'm formatting my search request which is basically a search for "mount" inside two folders.
GET: https://www.googleapis.com/drive/v3/files?q=fullText contains 'mount' AND ('{folder_id}' in parents OR '{folder_id}' in parents)
Headers:
Authorization: Bearer {access_token}
Which gets me this response:
{
"kind": "drive#fileList",
"incompleteSearch": false,
"files": []
}
When I make the request with code, I don't get any results nor when I use an API client to manually send the request. But, whenever I use the "Try it now" in the Google Drive files list API I do get results... which is perplexing to me since I'm using the exact same query there (copy/pasting). Can anyone see what I'm doing wrong?
I'm using these permissions
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/drive.appdata
Things I've tried:
Encoded the full query, with and without encoding the single quotation marks.
Copying the full encoded query from the "Try it now" tool.
Reduced the number of folders to search through down to one (it works in this case, anything more than one results zero results).
Changed the position of the search and the folder query.
Lowercased "AND" and "OR" inside the query.
In order to correctly understand your situation, I asked the following 4 questions.
The account of {access_token} of Authorization: Bearer {access_token} is the same as the account you tested But, whenever I use the "Try it now" in the Google Drive files list API I do get results?
When you tested "Try it now", you used other parameters except for q?
As a test case, when you use only the scope of https://www.googleapis.com/auth/drive and retrieve the access token again and test your request, what result will you obtain?
When you test the following curl command by replacing ### with your access token and placing folderId1 and folderId2 with your folder IDs, what result will you obtain?
curl -H "Authorization: Bearer ###" "https://www.googleapis.com/drive/v3/files?q=fullText%20contains%20%27mount%27%20AND%20(%27folderId1%27%20in%20parents%20OR%20%27folderId2%27%20in%20parents)"
As the result, from the section 1, it was found as follows.
I went through your questions again very carefully and I realized that I'm using a Google Service Account and not the main account. So, technically, it was not the same account even though the Google Service Account had access to some folders of the main account, but not all of folders.

Google Drive API failing - Unusual traffic from your computer network

The Google Drive API GET query started to fail (we are using this api in one of our client service):
https://www.googleapis.com/drive/v3/files/1ke4Yoxxxxxxxxxxxxxx?alt=media&access_token=ya29.ImG9BwT.....
We're sorry...
... but your computer or network may be sending automated queries. To protect our users, we can't process your request right now.
See Google Help for more information...
"Unusual traffic from your computer network"
Everything was ok till today.
Just made a couple of tests with curl:
HTTP GET with access_token inside HTTP header:
curl -H "Authorization: Bearer ya29._valid_access_token" https://www.googleapis.com/drive/v3/files/1r5BT2WPrulQ6FyhT8RcqV51TVOThEmhK?alt=media
Result: success, file downloaded.
HTTP GET with access_token as a part of HTTP request:
curl https://www.googleapis.com/drive/v3/files/1r5BT2WPrulQ6FyhT8RcqV51TVOThEmhK?alt=media&access_token=ya29._valid_access_token
Result: error
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "dailyLimitExceededUnreg",
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"extendedHelp": "https://code.google.com/apis/console"
}
],
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
}
Note that the Google API project approved by Google and has a Production state!!!
Hi Google team, any ideas why it is happening?
Thank you
Posting this just for documentation purposes. As per the reference provided by Tanaike, since January 1, 2020:
download calls to files.get, revisions.get and files.export endpoints which authenticate using the access token in the query parameter will no longer be supported.
Only requests that download media content (alt=media) are affected by this change.
The access token should be provided in the HTTP header, like Authorization: Bearer oauth2-token or, if that's not possible, follow the workarounds provided in the referenced documentation:
For file downloads, redirect to the webContentLink which will instruct the browser to download the content. If the application wants to display the file to the user, they can simply redirect to the alternateLink in v2 or webViewLink in v3.
For file exports, redirect to the export link in exportLinks with the desired mime type which will instruct the browser to download the content.
Reference:
Changes in authorization to Google Drive API
Authorization via HTTP header
Posting an addition to the documentation of iamblichus specific for application data in Google Drive.
My App uses the Google Drive API in the backend to store the documents of my users on their own Drive. Importantly, I store the data in an application data folder such that the users can't accidently delete the data.
To let the users retreive their documents I used to redirected the user to the
downloadUrl: https://www.googleapis.com/drive/v2/files/id?alt=media&source=downloadUrl&access_token=ya29.** where I added alt=media and access_token to the query. This worked fine till January 1, 2020. As confirmed above. However, now the request fails with the message:
We're sorry... ... but your computer or network may be sending
automated queries. To protect our users, we can't process your request
right now.
GET request downloadUrl failing
In my efforts to find a solution to this problem I've tried the workarrounds provided by Google but they are in my experience not working for documents in an application data folder.
I tried the webContentLink with the access_token query in v2 but it fails with an 401 Unauthorized error.
The alternateLink in v2 and the webViewLink in v3 fail with the error:
The desired file does not exist.
I can't use the exportLinks because that's only for Google Documents.
The solution I found was to first download the file to the server using the Google Drive PHP SDK and then serve it to my users using a Content-Dispostion header. Such as described here. It is a lot less elegant in my opinion because the end users doesn't download the document directly from the Google Drive API but it works.
It's a shame that Google didn't update their documentation nor notified their users..

Listing files over REST using API Key gives 403

I am simply trying out curl examples from the GDrive API Explorer, specifically this call:
https://developers.google.com/drive/api/v3/reference/files/list
However when I copy the example and execute it with my API key, I get this error:
curl https://www.googleapis.com/drive/v3/files?key=AIzaSyCQfFNMxHVJRaTvXXXXXXXXXX
{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientFilePermissions",
"message": "The user does not have sufficient permissions for this file."
}
],
"code": 403,
"message": "The user does not have sufficient permissions for this file."
}
}
When I try to get a single file using files/{fileId} with the same API key, it works fine and the file metadata is returned.
What is the deal here? Does listing require special permissions, or does API keys have limitations, or..?
Just a hunch, you are trying a file that is not public, that is why you are receiving 403:insufficientFilePermissions. To access this you must authenticate your request using OAuth 2.0.
You can check the documentation About Authorization:
Your application must use OAuth 2.0 to authorize requests. No other
authorization protocols are supported. If your application uses Google
Sign-In, some aspects of authorization are handled for you.

Set up Google Calendar V3 API Push notification via my Google Apps script

I want to use Google CAL API v3 to watch multiple calendars and thus to update all those events from those calendars to a Master Calendar, so I need to use WATCH/PUSH notification in order that whenever there is a new event in those cal’s, those events shd be automatically be pushed/created in my master calendar.
But, I am facing the following issue :Under APIs Explorer. Most of the services return 200 OK, except the Watch request not working.
Services > Calendar API v3 > calendar.events.watch
i got the below request and response
Request
POST https://www.googleapis.com/calendar/v3/calendars/mailid%40domain.com/events/watch?key={YOUR_API_KEY}
{
}
Response
400 OK
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "entity.resource"
}
],
"code": 400,
"message": "entity.resource"
}
}
And then i followed as per the below google documentation
https://developers.google.com/google-apps/calendar/v3/push
Registering Your domain:
Step 1: Verify that you own the domain
Step 2: Register your domain
I verified my domain/notifications in google webmaster tools.
My verified domain look like this:
http://my-domain.com/notifications
And have added my domain name in the webhooks under the PUSH in Google Developer Console, as explained in the doc.
Is there anything i am missing here, plz is there an issue in SSL certificate fr my domain, how can i atleast test in the API explorer, so that i get a return code 200 OK. After that, I need to implement this push/WATCH via Google Apps Script.
Is there any documentation for apps script to use push notification.
Any hint, tip will help me, I am tired with this for the past 1 week in trial and error method.
In the request that you posted the body is empty. In the documentation there is an example where you need to provide the calendar ID, the web_hook and other information:
{
"id": "01234567-89ab-cdef-0123456789ab", // Your channel ID.
"type": "web_hook",
"address": "https://example.com/notifications", // Your receiving URL.
...
"token": "target=myApp-myCalendarChannelDest", // (Optional) Your channel token.
"expiration": 1426325213000 // (Optional) Your requested channel expiration time.
}
Add this information when creating the push notification.
For using apps script you can use URLfetch service with the method "fetch()" then you would need to provide the parameters mentions and make the call as a POST.
Hope this helps.
UPDATE: I will write here to have more space.
Push notifications work in this way.
-You create a push notification with the id, the resource you want to watch, the address where you want to receive the notification and the optional parameters.
-if successful, the server will watch that resource and will send a notification to the address mentioned in the request describing the changes when a change is made to the resource.
-The server needs to know that you received the notification, so from the address mentioned in #1, you need to tell the server that you received the notification returning a HTTP 200 response. (for this you need an app that is listening to the notifications and sending the responses)
for your questions
1.- As the server will make a HTTP request to a url (your web_hook address) Google requires it to be secure, that's why it is required to be HTTPS.
2.- Yes, without that url you won't be able to receive the notification.
3.- Google also needs to verify that the url you provided is actually yours, so you will need to provide the url, then Google will provide you a file, you have to make this file available in that url, then Google will call the url an will retrieve that file. Then you can prove that the URL is yours. I'm not sure if this step can be done with apps script. You can actually deploy a script as web app but i'm not sure if you can use it for this purpose.(here you can find more info and different ways to verify the url)
4.- That's created by yourself. In the documentation is pointed out the recommendations for it.
I hope this clarifies your questions.
You can check here how push notifications work, this example is for Drive but the concept is the same.

How to Get Files And Folders from Box.com by using "access_token" from OAuth2 from Java Application?

I have an "access_token" by requesting "https://www.box.com/api/oauth2/token".
By Using this "access_token" , I need to get the folders and files from box.com.
For this , I am making a request like:
https://www.box.com/api/2.0/folders/0?access_token=" + access_token1
But I am getting Null as response.
Some times, I am getting "In-sufficient Permission" error message. i.e 403 error.
But , if send the same request via browser i am getting all the folders and files.
Where Exactly I am getting problem?
If you post related code, would be useful for me?
Thanks
Sarath.T
Access tokens are sent as part of the authorization header, not as a GET query string parameter. The authorization header looks like this:
Authorization: Bearer
Check out the "Using Your Access Token with API V2" section on http://developers.box.com/oauth/