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

Question

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.


Show source
| rest   | python   | api   | python-requests   | google-drive-sdk   2016-12-06 17:12 2 Answers

Answers to Create folders in google drive with rest api interface and python requests ( 2 )

  1. 2016-12-06 21:12

    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.

  2. 2016-12-07 12:12

    Thanks. I finally I get 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'

Leave a reply to - Create folders in google drive with rest api interface and python requests

◀ Go back