Davide
Davide

Reputation: 71

Drive API 404 creating file inside a folder

I am trying to create a file in a folder on my drive.

The folder exists in my drive and it's shared with the account I'm using (in the code I will refer to it with the fake ID: 1AKIQHcwQVYgGcinp335Uu5C24kI1tJaq)

This is my code to create the file

from apiclient import errors
from apiclient.http import MediaFileUpload

def create_file(service, title, description, parent_id, mime_type, filename):

  media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
  body = {
          'name': title,
          'title': title,
          'description': description,
          'mimeType': mime_type,
          'parents': [parent_id]
          }
  try:
      file = service.files().create(
              body=body,
              media_body=media_body,
              fields='id').execute()
      return file
  except errors.HttpError as error:
      print('An error occurred: %s' % error)
      return None

But I'm always getting this error:

<HttpError 404 when requesting https://www.googleapis.com/upload/drive/v3/files?fields=id&alt=json&uploadType=resumable returned "File not found: 1AKIQHcwQVYgGcinp335Uu5C24kI1tJaq.">

I based my code on this, is there something I'm missing? Can the problem to the fact that the folder is inside of a gsuite shared drive?

Upvotes: 0

Views: 723

Answers (1)

Davide
Davide

Reputation: 71

I've found the solution!

To use a folder in a shared drive you have to provide the driveId:

from apiclient import errors
from apiclient.http import MediaFileUpload

def create_file(service, title, description, parent_id, drive_id, mime_type, filename):

  media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
  body = {
          'name': title,
          'title': title,
          'description': description,
          'mimeType': mime_type,
          'parents': [parent_id],
          'driveId': drive_id
          }
  try:
      file = service.files().create(
              body=body,
              media_body=media_body,
              fields='id').execute()
      return file
  except errors.HttpError as error:
      print('An error occurred: %s' % error)
      return None

Upvotes: 1

Related Questions