Create folders in google drive with rest api interface and python requests - python

I'm struggled with Google Drive REST API interface.
I need to create a folder programmatically. Reading api documents (https://developers.google.com/drive/v3/reference/files/create) it's possible to create a folder with a POST method to https://www.googleapis.com/drive/v3/files, a request body with folder name and mime type as 'application/vnd.google-apps.folder'
so I write this python function:
def createFolder(self,folderName):
if not self.authorization:
self.get_authorization()
url = 'https://www.googleapis.com/drive/v3/files'
headers = { 'Authorization':'Bearer {}'.format(self.access_token)}
metadata = {
"name": folderName,
"mimeType": 'application/vnd.google-apps.folder'
}
response = requests.post( url, headers = headers, params = metadata)
return response.json()
that outputs a response object like this:
{
u'mimeType': u'application/json',
u'kind': u'drive#file',
u'id': u'0B350e2U7rvyvR0k3NjJmTTVuWUE',
u'name': u'Untitled'
}
A file is created, but the folder metadata are not applied.
When I do the same with "Try it!" APIs Explorer I get a correct behaviour, so I can't understand where my code is wrong.
I'm writing a portable plugin and I don't want to deal with google library so I would prefer a simple Http approach.
I'll appreciate if you can give me any suggestions.

Thanks. I finally got it: (SOLVED)
def createFolder(self,folderName):
if not self.authorization:
self.get_authorization()
url = 'https://www.googleapis.com/drive/v3/files'
headers = {
'Authorization':'Bearer {}'.format(self.access_token),
'Content-Type': 'application/json'
}
metadata = {
'name': folderName,
'mimeType': 'application/vnd.google-apps.folder'
}
response = requests.post( url, headers = headers, data = json.dumps(metadata))
return response.json()
Google Drive API wants the needed parameters in {request body}, so metadata must be passed as json string and header "content-type" carefully set to "application/json", otherwise the API will not like very much python requests default to 'application/x-www-form-urlencoded'

There is a problem with your URL. Lose the ?uploadType=multipart as this isn't appropriate for creating a folder - "upload" is a reference to a file's content and a folder has no content.

Have you tried using postman to send rest API POST call? I work with rest API and python all day long. I first test it with postman. If that works, just have postman convert it to Python code. From there, you can create your variables, create your function. Run your python script and verify the folder was created.

Related

Azure DevOps: How to download a file from git using REST API?

Following the example here: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/items/get?view=azure-devops-rest-6.1
I can query a dev ops organization and get a response like so:
{
"count": 1,
"value": [
{
"objectId": "61a86fdaa79e5c6f5fb6e4026508489feb6ed92c",
"gitObjectType": "blob",
"commitId": "23d0bc5b128a10056dc68afece360d8a0fabb014",
"path": "/MyWebSite/MyWebSite/Views/Home/_Home.cshtml",
"url": "https://dev.azure.com/fabrikam/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/items/MyWebSite/MyWebSite/Views/Home/_Home.cshtml?versionType=Branch&versionOptions=None"
}
]
}
How can I use Python to, I guess, download that url? The file should be an XML file. I want to read (download) it directly from Python.
If I take the url returned above and insert it into yet another GET request, I get sent in loops basically.
Edit:
I figured out that if I paste the URL that it gives me, I can download the file with my web browser. However, when I insert that same URL into a new request, I get the same meta-data over and over, trying:
response = requests.get(url=(url), headers=headers, stream=True)
response.text
response.content
response = requests.get(url=(url), headers=headers, stream=False)
response.text
response.content
I have solved the problem, as both comments and previous answer are incorrect and will not lead you to the right answer for future visitors.
Following the example here as originally posted, it presumes that download=True: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/items/get?view=azure-devops-rest-6.1
However, you then need to query the file of interest and set this flag: &includeContent=true to actually get the file content from the devops GIT.
Like so:
https://dev.azure.com/fabrikam/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/items?scopePath=/MyWebSite/MyWebSite/Views/Home/_Home.cshtml&includeContent=true&api-version=6.1-preview.1
or you will send as many GET requests as you like and get nothing of value in return.

how to get access tokens from refresh token? does refresh token expire?

I'm trying to create a python script which takes a (.csv with access tokens and a file) as input and uploads that file to multiple google drives whose access tokens are in that csv
but after sometime access tokens get expired and I have to get them again...just saw there's something called refresh and it refreshes access token
Is it possible to do this from python script, please explain.
Do refresh token expire?
import json
import requests
import pandas as pd
headers = {}
para = {
"name": "update",
}
files = {
'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
'file': open("./update.txt", "rb")
}
tokens = pd.read_csv('tokens.csv')
for i in tokens.token:
headers={"Authorization": i}
r = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers=headers,
files=files
)
print(r.text)
In order to be able to get a new access_token programmatically using a refresh_token, you must have set access_type to offline when redirecting the user to Google's OAuth 2.0 server.
If you did that, you can get a new access_token if you do the following POST request to https://oauth2.googleapis.com/token:
POST /token HTTP/1.1
Host: oauth2.googleapis.com
Content-Type: application/x-www-form-urlencoded
client_id=your_client_id&
client_secret=your_client_secret&
refresh_token=refresh_token&
grant_type=refresh_token
The corresponding response would be something like:
{
"access_token": "1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in": 3920,
"scope": "https://www.googleapis.com/auth/drive",
"token_type": "Bearer"
}
Note:
You can find code snippets for several languages in the reference I provide below, including Python, but considering you are not using the Python library, I think the HTTP/REST snippet I provided might be more useful in your situation.
Reference:
Refreshing an access token (offline access)

How can I fix a parse error when making a post request with python?

request = {
"parents": ["1zaxxxxxxxxxxxxxxxZo"],
"name": selected_name
}
headers = {
"Authorization": "Bearer "+creds.token,
"Accept": "application/json",
"Content-Type": "application/json"
}
data = {
"fileId": file_id,
"request": request,
"fields": "files(id)",
"supportsAllDrives": True,
"ignoreDefaultVisibility": True
}
response = requests.post("https://www.googleapis.com/drive/v3/files/"+file_id+"/copy", data=data, headers=headers)
response = response.json()
I am trying to make a request to copy the file_id to the parent folder listed in my request. I am new to both google drive's api and making post requests, I can't understand what I'm doing wrong. I have been working on this issue for multiple hours now, and I'm getting a error response code 400, Parse Error. From what I have gathered, it means I'm formatting my request improperly. I've been trying different things for a long time now, I can't figure out how to make it properly. If anyone could help me it would be greatly appreciated, or point me to where to look to fix this issue on my own. I've been reading the docs, maybe I've bitten off more then I can chew. Thank you.
I believe your goal and situation as follows.
You want to copy a file on Google Drive using Drive API v3 with requests of python.
You have already had the access token for copying the file using Drive API.
In order to achieve your goal, I would like to propose the following modification.
Modification points:
Please set the values of fields, supportsAllDrives and ignoreDefaultVisibility to the query parameters.
Please modify fields from files(id) to id.
Request body is as follows.
data = {
"parents": ["1zaxxxxxxxxxxxxxxxZo"],
"name": selected_name
}
Please modify data=data to data=json.dumps(data).
When above points are reflected to your script, it becomes as follows.
Modified script:
import json
import requests
file_id = "###" # Please set the source file ID.
selected_name = "###" # Please set the filename.
headers = {
"Authorization": "Bearer "+creds.token,
"Accept": "application/json",
"Content-Type": "application/json"
}
data = {
"parents": ["1zaxxxxxxxxxxxxxxxZo"], # Please set the folder ID.
"name": selected_name
}
params = {
"fields": "id",
"supportsAllDrives": True,
"ignoreDefaultVisibility": True
}
response = requests.post("https://www.googleapis.com/drive/v3/files/"+file_id+"/copy", data=json.dumps(data), params=params, headers=headers)
response = response.json()
print(response)
Result:
When above script is run, the following value is shown.
{'id': '###'}
Note:
This modified script supposes that your access token creds.token can be used for copying the file using Drive API. Please be careful this.
Reference:
Files: copy

HTTP Triggering Cloud Function with Cloud Scheduler

I have a problem with a job in the Cloud Scheduler for my cloud function. I created the job with next parameters:
Target: HTTP
URL: my trigger url for cloud function
HTTP method: POST
Body:
{
"expertsender": {
"apiKey": "ExprtSender API key",
"apiAddress": "ExpertSender APIv2 address",
"date": "YYYY-MM-DD",
"entities": [
{
"entity": "Messages"
},
{
"entity": "Activities",
"types":[
"Subscriptions"
]
}
]
},
"bq": {
"project_id": "YOUR GCP PROJECT",
"dataset_id": "YOUR DATASET NAME",
"location": "US"
}
}
The real values has been changed in this body.
When I run this job I got an error. The reason is caused by processing body from POST request.
However, when I take this body and use it as Triggering event in Testing I don't get any errors. So I think, that problem in body representation for my job but I havn't any idea how fix it. I'll be very happy for any idea.
Disclaimer:
I have tried to solve the same issue using NodeJS and I'm able to get a solution
I understand that this is an old question. But I felt like its worth to answer this question as I have spent almost 2 hours figuring out the answer for this issue.
Scenario - 1: Trigger the Cloud Function via Cloud Scheduler
Function fails to read the message in request body.
Scenario - 2: Trigger the Cloud Function via Test tab in Cloud Function interface
Function call always executes fine with no errors.
What did I find?
When the GCF routine is executed via Cloud Scheduler, it sends the header content-type as application/octet-stream. This makes express js unable to parse the data in request body when Cloud scheduler POSTs the data.
But when the exact same request body is used to test the function via the Cloud Function interface, everything works fine because the Testing feature on the interface sends the header content-type as application/json and express js is able to read the request body and parses the data as a JSON object.
Solution
I had to manually parse the request body as JSON (explicitly using if condition based on the content-type header) to get hold of data in the request body.
/**
* Responds to any HTTP request.
*
* #param {!express:Request} req HTTP request context.
* #param {!express:Response} res HTTP response context.
*/
exports.helloWorld = (req, res) => {
let message = req.query.message || req.body.message || 'Hello World!';
console.log('Headers from request: ' + JSON.stringify(req.headers));
let parsedBody;
if(req.header('content-type') === 'application/json') {
console.log('request header content-type is application/json and auto parsing the req body as json');
parsedBody = req.body;
} else {
console.log('request header content-type is NOT application/json and MANUALLY parsing the req body as json');
parsedBody = JSON.parse(req.body);
}
console.log('Message from parsed json body is:' + parsedBody.message);
res.status(200).send(message);
};
It is truly a feature issue which Google has to address and hopefully Google fixes it soon.
Cloud Scheduler - Content Type header issue
Another way to solve the problem is this:
request.get_json(force=True)
It forces the parser to treat the payload as json, ingoring the Mimetype.
Reference to the flask documentation is here
I think this is a bit more concise then the other solutions proposed.
Thank you #Dinesh for pointing towards the request headers as a solution! For all those who still wander and are lost, the code in python 3.7.4:
import json
raw_request_data = request.data
# Luckily it's at least UTF-8 encoded...
string_request_data = raw_request_data.decode("utf-8")
request_json: dict = json.loads(string_request_data)
Totally agree, this is sub-par from a usability perspective. Having the testing utility pass a JSON and the cloud scheduler posting an "application/octet-stream" is incredibly irresponsibly designed.
You should, however, create a request handler, if you want to invoke the function in a different way:
def request_handler(request):
# This works if the request comes in from
# requests.post("cloud-function-etc", json={"key":"value"})
# or if the Cloud Function test was used
request_json = request.get_json()
if request_json:
return request_json
# That's the hard way, i.e. Google Cloud Scheduler sending its JSON payload as octet-stream
if not request_json and request.headers.get("Content-Type") == "application/octet-stream":
raw_request_data = request.data
string_request_data = raw_request_data.decode("utf-8")
request_json: dict = json.loads(string_request_data)
if request_json:
return request_json
# Error code is obviously up to you
else:
return "500"
One of the workarounds that you can use is to provide a header "Content-Type" set to "application/json". You can see a setup here.

How to consume the Github GraphQL API using Python?

I want to access details from Github using Github GraphQl v4 API. I found Graphene library, but I'm not sure how to authenticate with a personal access token in Python.
I tried to search on Google but couldn't found any example. It's Python library that can create graphical schema's and are not for consuming them, I tried with `requests' but failed. How can i authenticate and can find list of repositories?
I have used Github GraphQl explorer to find list of repositories via this code:
viewer {
repositories(first: 30) {
totalCount
pageInfo {
hasNextPage
endCursor
}
edges {
node {
name
}
}
}
Unlike rest, graphql has only one end point. You just need to do a POST with your query as a json object. You should provide your api_token you get from github as part of the headers.
import requests
url = 'https://api.github.com/graphql'
json = { 'query' : '{ viewer { repositories(first: 30) { totalCount pageInfo { hasNextPage endCursor } edges { node { name } } } } }' }
api_token = "your api token here..."
headers = {'Authorization': 'token %s' % api_token}
r = requests.post(url=url, json=json, headers=headers)
print (r.text)
Graphene is for building GraphQL APIs not for consuming them.
Did you see that: https://github.com/graphql-python/gql ?
It's a GraphQL client for Python.
Hope that's helpful.
As previous answers mentioned, calling GraphQL is as simple has making a POST request with the query string.
However, if you're on Python3 want something more advanced that'll also verify your queries during build and generate typed data-class response classes for you check out the new GQL library:
https://github.com/ekampf/gql
Exactly for GitHub, there is an example on using the Github GraphQL API with Python 3
https://gist.github.com/gbaman/b3137e18c739e0cf98539bf4ec4366ad
(check link as it has a lot of comments including better code for authentication)
# An example to get the remaining rate limit using the Github GraphQL API.
import requests
headers = {"Authorization": "Bearer YOUR API KEY"}
def run_query(query): # A simple function to use requests.post to make the API call. Note the json= section.
request = requests.post('https://api.github.com/graphql', json={'query': query}, headers=headers)
if request.status_code == 200:
return request.json()
else:
raise Exception("Query failed to run by returning code of {}. {}".format(request.status_code, query))
# The GraphQL query (with a few aditional bits included) itself defined as a multi-line string.
query = """
{
viewer {
login
}
rateLimit {
limit
cost
remaining
resetAt
}
}
"""
result = run_query(query) # Execute the query
remaining_rate_limit = result["data"]["rateLimit"]["remaining"] # Drill down the dictionary
print("Remaining rate limit - {}".format(remaining_rate_limit))
And there are many Python GraphQL client libraries:
https://github.com/graphql-python/gql (aka https://github.com/ekampf/gql)
https://github.com/graphql-python/gql-next
https://github.com/prodigyeducation/python-graphql-client
Official list is at https://graphql.org/code/#python
(just scroll down, client libraries are after server libraries)

Categories