Search code examples
pythongoogle-drive-apigoogle-api-python-clientservice-accounts

Drive folder not being created


So i am trying to create a folder on google drive using python. I followed the documentation and everything and also used 0Auth2 authentication. For reference this is the code i am trying to debug

import os
import google.auth
from googleapiclient.discovery import build
from google.oauth2 import service_account
from googleapiclient.http import MediaFileUpload
from googleapiclient.errors import HttpError

SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = 'assets/key/key.json'

def Authenticate():
    creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    print('Authentication Successful')
    return creds

def CreateFolder():
    creds = Authenticate();
    
    try:
        service = build("drive", "v3", credentials=creds);
    
        folder_metadata = {
            "name" : "AutoUpload",
            "mimeType": "application/vnd.google-apps.folder",
        }
        folder = service.files().create(body=folder_metadata, fields="id").execute()
        print(f'Folder created successfully! Folder ID: "{folder.get("id")}".')
        return folder.get("id")
    
    except HttpError as error:
        print(f'An error occured: {error}')
        return None
CreateFolder();

Duringe the debugging i get the expected results like the authentication being successfull and even getting back the folder id. But upon checking my drive, the folder is no where to be found. Even if i search for the folder directly on my drive it doesnt seem to be there. Can i get some help on what could be the problem


Solution

  • Answer: Your not seeing the file in your personal drive account because that's not where your uploading it to.

    The metadata you are setting

    folder_metadata = {
            "name" : "AutoUpload",
            "mimeType": "application/vnd.google-apps.folder",
        }
    

    Shows that you are creating a folder and giving it a mime type of folder. You are not setting a directory so there for it will go in to the root directory of the currently authenticated user.

    As you are using a service account

    creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    

    The file will be uploaded to the service accounts google drive account.

    You can see this by doing a files.list

    folder = service.files().list().execute()
    

    If you want to upload the file to your personal drive account you need to share a folder with the service account and then set parents in the metadata to be that of the folder your uploading to on your account.