To make requests to Google APIs the work flow is in essence the following:

  1. Go to developer console, log in if you haven't.
  2. Create a Cloud Platform project.
  3. Enable for your project, the APIs you are interested in using with you projects' apps (for example: Google Drive API).
  4. Create and download OAuth 2.0 Client IDs credentials that will allow your app to gain authorization for using your enabled APIs.
  5. Head over to OAuth consent screen, click on and add your scope using the button. (scope: https://www.googleapis.com/auth/drive.readonly for you). Choose Internal/External according to your needs, and for now ignore the warnings if any.
  6. To get the valid token for making API request the app will go through the OAuth flow to receive the authorization token. (Since it needs consent)
  7. During the OAuth flow the user will be redirected to your the OAuth consent screen, where it will be asked to approve or deny access to your app's requested scopes.
  8. If consent is given, your app will receive an authorization token.
  9. Pass the token in your request to your authorized API endpoints.[2]
  10. Build a Drive Service to make API requests (You will need the valid token)[1]

NOTE:

The available methods for the Files resource for Drive API v3 are here.

When using the Python Google APIs Client, then you can use export_media() or get_media() as per Google APIs Client for Python documentation


IMPORTANT:

Also, check that the scope you are using, actually allows you to do what you want (Downloading Files from user's Drive) and set it accordingly. ATM you have an incorrect scope for your goal. See OAuth 2.0 API Scopes


Sample Code References:

  1. Building a Drive Service:
import google_auth_oauthlib.flow
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
 
 
class Auth:
 
    def __init__(self, client_secret_filename, scopes):
        self.client_secret = client_secret_filename
        self.scopes = scopes
        self.flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(self.client_secret, self.scopes)
        self.flow.redirect_uri = 'http://localhost:8080/'
        self.creds = None
 
    def get_credentials(self):
        flow = InstalledAppFlow.from_client_secrets_file(self.client_secret, self.scopes)
        self.creds = flow.run_local_server(port=8080)
        return self.creds

 
# The scope you app will use. 
# (NEEDS to be among the enabled in your OAuth consent screen)
SCOPES = "https://www.googleapis.com/auth/drive.readonly"
CLIENT_SECRET_FILE = "credentials.json"
 
credentials = Auth(client_secret_filename=CLIENT_SECRET_FILE, scopes=SCOPES).get_credentials()
 
drive_service = build('drive', 'v3', credentials=credentials)
  1. Making the request to export or get a file
request = drive_service.files().export(fileId=file_id, mimeType='application/pdf')

fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print("Download %d%%" % int(status.progress() * 100))

# The file has been downloaded into RAM, now save it in a file
fh.seek(0)
with open('your_filename.pdf', 'wb') as f:
    shutil.copyfileobj(fh, f, length=131072)
Answer from Aerials on Stack Overflow
🌐
The Python Code
thepythoncode.com › article › using-google-drive--api-in-python
How to Use Google Drive API in Python - The Python Code
Learn how you can use Google Drive API to list files, search for specific files or file types, download and upload files from/to Google Drive in Python.
Top answer
1 of 2
26

To make requests to Google APIs the work flow is in essence the following:

  1. Go to developer console, log in if you haven't.
  2. Create a Cloud Platform project.
  3. Enable for your project, the APIs you are interested in using with you projects' apps (for example: Google Drive API).
  4. Create and download OAuth 2.0 Client IDs credentials that will allow your app to gain authorization for using your enabled APIs.
  5. Head over to OAuth consent screen, click on and add your scope using the button. (scope: https://www.googleapis.com/auth/drive.readonly for you). Choose Internal/External according to your needs, and for now ignore the warnings if any.
  6. To get the valid token for making API request the app will go through the OAuth flow to receive the authorization token. (Since it needs consent)
  7. During the OAuth flow the user will be redirected to your the OAuth consent screen, where it will be asked to approve or deny access to your app's requested scopes.
  8. If consent is given, your app will receive an authorization token.
  9. Pass the token in your request to your authorized API endpoints.[2]
  10. Build a Drive Service to make API requests (You will need the valid token)[1]

NOTE:

The available methods for the Files resource for Drive API v3 are here.

When using the Python Google APIs Client, then you can use export_media() or get_media() as per Google APIs Client for Python documentation


IMPORTANT:

Also, check that the scope you are using, actually allows you to do what you want (Downloading Files from user's Drive) and set it accordingly. ATM you have an incorrect scope for your goal. See OAuth 2.0 API Scopes


Sample Code References:

  1. Building a Drive Service:
import google_auth_oauthlib.flow
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
 
 
class Auth:
 
    def __init__(self, client_secret_filename, scopes):
        self.client_secret = client_secret_filename
        self.scopes = scopes
        self.flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(self.client_secret, self.scopes)
        self.flow.redirect_uri = 'http://localhost:8080/'
        self.creds = None
 
    def get_credentials(self):
        flow = InstalledAppFlow.from_client_secrets_file(self.client_secret, self.scopes)
        self.creds = flow.run_local_server(port=8080)
        return self.creds

 
# The scope you app will use. 
# (NEEDS to be among the enabled in your OAuth consent screen)
SCOPES = "https://www.googleapis.com/auth/drive.readonly"
CLIENT_SECRET_FILE = "credentials.json"
 
credentials = Auth(client_secret_filename=CLIENT_SECRET_FILE, scopes=SCOPES).get_credentials()
 
drive_service = build('drive', 'v3', credentials=credentials)
  1. Making the request to export or get a file
request = drive_service.files().export(fileId=file_id, mimeType='application/pdf')

fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print("Download %d%%" % int(status.progress() * 100))

# The file has been downloaded into RAM, now save it in a file
fh.seek(0)
with open('your_filename.pdf', 'wb') as f:
    shutil.copyfileobj(fh, f, length=131072)
2 of 2
0

I usually do it using two files for modularity:

gdrive_credentials.py

from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
import os

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive.readonly'] # Or drive if you need write access

def get_credentials(credentials_json = "credentials.json", token_json = "token.json"):
    """Gets or creates Google Drive API credentials.

    Args:
        credentials_json: The filename of the credentials file.
        token_json: The filename of the token file

    Returns:
        A Credentials object, or None if an error occurred.
    """
    creds = None

    if os.path.exists(token_json):
        creds = Credentials.from_authorized_user_file(token_json, SCOPES)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            try:
                creds.refresh(Request())
            except Exception as e: # Catch exceptions during refresh
                print(f"Error refreshing credentials: {e}")
                return None
        else:
            if not os.path.exists(credentials_json):
                print(f"Credentials file '{target}' not found. Please download it from Google Cloud Console.")
                return None
            flow = InstalledAppFlow.from_client_secrets_file(credentials_json, SCOPES)
            try:
                creds = flow.run_local_server(port=0)
            except Exception as e: # Catch exceptions during auth flow
                print(f"Error during authorization flow: {e}")
                return None
        with open(token_json, 'w') as token_file:
            token_file.write(creds.to_json())
    return creds

if __name__ == '__main__':
    _ = get_credentials()

gdrive_wget.py

import google_auth_oauthlib.flow
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
import io
import shutil

def download_file_from_drive(file_id, output_filename, drive_service):
    try:
        file_metadata = drive_service.files().get(fileId=file_id, fields='mimeType, name').execute()
        mime_type = file_metadata.get('mimeType')
        file_name = file_metadata.get('name')
        print(f"Downloading file: {file_name} (Mime Type: {mime_type})")

        if mime_type == 'application/vnd.google-apps.document':
            request = drive_service.files().export(fileId=file_id, mimeType='text/plain')
        elif mime_type == 'application/vnd.google-apps.spreadsheet':
            request = drive_service.files().export(fileId=file_id, mimeType='text/csv') # Example for Sheets
        elif mime_type == 'application/vnd.google-apps.presentation':
            request = drive_service.files().export(fileId=file_id, mimeType='application/pdf') # Example for Slides
        else:
            request = drive_service.files().get_media(fileId=file_id)

        # Download the file into RAM
        fh = io.BytesIO()
        downloader = MediaIoBaseDownload(fh, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print("Download %d%%" % int(status.progress() * 100))

        # The file has been downloaded into RAM, now save it in a file
        fh.seek(0)
        with open(output_target, 'wb') as f:
            shutil.copyfileobj(fh, f, length=131072)

    except HttpError as error:
        print(f'An HTTP error occurred: {error}')
    except Exception as e:
        print(f'A general error occurred: {e}')
    return None

if __name__ == '__main__': 
    import scryb_credentials
    credentials = scryb_credentials.get_credentials() 

    drive_service = build('drive', 'v3', credentials=credentials)

    import sys
    file_id = sys.argv[1]
    output_target = sys.argv[2]

    download_file_from_drive(file_id, output_target, drive_service)
Discussions

python: How do i download a file from Google drive using api - Stack Overflow
I would like to download a file in google drive to my system,using google drive api. How can i implement this ? according to example given at https://developers.google.com/drive/v2/reference/files... More on stackoverflow.com
🌐 stackoverflow.com
December 21, 2016
Python: download files from google drive using url - Stack Overflow
For those who are interested in the link to download via HTTP, the Google API and most clients provide a webContentLink field containing it (note the file permissions to use it) ... Save this answer. ... Show activity on this post. as of Python 3.11 below code using webContentLink, please note atleast ... service = build('drive... More on stackoverflow.com
🌐 stackoverflow.com
Downloading A File with Google Drive API - Stack Overflow
I'm trying to download a file from Google Drive using the Python API. I'm looking through the documentation and I'm seeing a def that takes two args, the service instance and a Drive File instance.... More on stackoverflow.com
🌐 stackoverflow.com
March 24, 2017
Google Drive API downloading files with Python - Stack Overflow
I am trying to make a program that downloads files stored in Google Drive, I have looked for how to do it in many places, but I cannot make my program work correctly. This is my code: from __future__ More on stackoverflow.com
🌐 stackoverflow.com
🌐
Deepnote
deepnote.com › guides › google-cloud › how-to-download-files-from-google-drive-in-python
How to download files from Google Drive in Python
To download files from Google Drive using Python, you'll typically want to use the `google-api-python-client` and `google-auth-httplib2` libraries to interact with the Google Drive API.
🌐
Medium
hansheng0512.medium.com › download-folders-and-files-using-google-drive-api-and-python-1ad086e769b
Download Folders and Files using Google Drive API and Python | by Liang Han Sheng | Medium
December 25, 2022 - python download.py -i 1ZyjCpwSb9EtkWYnWB6k_PerulHhBxkRA -n folder_1 · When you run the download.pyfor the first time, you will have to verify your Gmail account to connect to the Google Drive API. ... Choose ‘Continue’ to confirm access. ... You will receive this message when you connect successfully. Then the download.py will continue to download the folders or files and you don’t have to reconnect the next time, token_drive_v3.pickle saves the connection.
🌐
YouTube
youtube.com › watch
Google Drive API in Python | Download Files - YouTube
In this Google Drive API in Python tutorial, I will be covering how to use Google Drive API to download files from your Google Drive.PS: You can also downloa...
Published   July 27, 2020
🌐
GitHub
gist.github.com › swyoon › 5601cd17bcc2ada8599bfa7549e6f698
A script for downloading all files in a Google Drive folder. · GitHub
A script for downloading all files in a Google Drive folder. - download_files_from_googledrive.py
Find elsewhere
🌐
Tanaikech
tanaikech.github.io › 2023 › 02 › 28 › resumable-download-of-file-from-google-drive-using-drive-api-with-python
Resumable Download of File from Google Drive using Drive API with Python · tanaike
Download the file content by requests. When this flow is reflected in a sample script of python, it becomes as follows. service = build("drive", "v3", credentials=creds) # Here, please use your client. file_id = "###" # Please set the file ID of the file you want to download.
🌐
GeeksforGeeks
geeksforgeeks.org › python › upload-and-download-files-from-google-drive-storage-using-python
Upload and Download files from Google Drive storage using Python - GeeksforGeeks
July 23, 2025 - In this article, we are going to see how can we download files from our Google Drive to our PC and upload files from our PC to Google Drive using its API in Python. It is a REST API that allows you to leverage Google Drive storage from within your app or program.
Top answer
1 of 16
140

If by "drive's url" you mean the shareable link of a file on Google Drive, then the following might help:

import sys
import requests


def download_file_from_google_drive(file_id, destination):
    URL = "https://docs.google.com/uc?export=download&confirm=1"

    session = requests.Session()

    response = session.get(URL, params={"id": file_id}, stream=True)
    token = get_confirm_token(response)

    if token:
        params = {"id": file_id, "confirm": token}
        response = session.get(URL, params=params, stream=True)

    save_response_content(response, destination)


def get_confirm_token(response):
    for key, value in response.cookies.items():
        if key.startswith("download_warning"):
            return value

    return None


def save_response_content(response, destination):
    CHUNK_SIZE = 32768

    with open(destination, "wb") as f:
        for chunk in response.iter_content(CHUNK_SIZE):
            if chunk:  # filter out keep-alive new chunks
                f.write(chunk)


def main():
    if len(sys.argv) >= 3:
        file_id = sys.argv[1]
        destination = sys.argv[2]
    else:
        file_id = "TAKE_ID_FROM_SHAREABLE_LINK"
        destination = "DESTINATION_FILE_ON_YOUR_DISK"
    print(f"dowload {file_id} to {destination}")
    download_file_from_google_drive(file_id, destination)


if __name__ == "__main__":
    main()

The snipped does not use pydrive, nor the Google Drive SDK, though. It uses the requests module (which is, somehow, an alternative to urllib2).

When downloading large files from Google Drive, a single GET request is not sufficient. A second one is needed - see wget/curl large file from google drive.

2 of 16
102

I recommend the gdown package.

pip install gdown

Take your share link

https://drive.google.com/file/d/0B9P1L--7Wd2vNm9zMTJWOGxobkU/view?usp=sharing

and grab the id - eg. 1TLNdIufzwesDbyr_nVTR7Zrx9oRHLM_N by pressing the download button (look for at the link), and swap it in after the id below.

import gdown

url = 'https://drive.google.com/uc?id=0B9P1L--7Wd2vNm9zMTJWOGxobkU'
output = '20150428_collected_images.tgz'
gdown.download(url, output, quiet=False)
🌐
ProjectPro
projectpro.io › recipes › upload-files-to-google-drive-using-python
How to Upload File to Google Drive using Python Script? -
August 17, 2023 - The below codes can be run in Jupyter notebook or any python console · Get Closer To Your Dream of Becoming a Data Scientist with 70+ Solved End-to-End ML Projects · from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive · Follow the steps to Get Authentication for Google Service API in the below link: Get Authentication for Google Service API · Download ...
🌐
GitHub
gist.github.com › tanaikech › dfdad37859d591526b2fba8fb4390cf5
Resumable Download of File from Google Drive using Drive API with Python · GitHub
When this flow is reflected in a sample script of python, it becomes as follows. service = build("drive", "v3", credentials=creds) # Here, please use your client. file_id = "###" # Please set the file ID of the file you want to download.
🌐
Omi AI
omi.me › blogs › api-guides › how-to-manage-google-drive-files-with-google-drive-api-in-python
How to Manage Google Drive Files with Google Drive API in Python – Omi AI
October 31, 2024 - Downloading involves using `files().get_media()` after specifying the `fileId`. This retrieves the media contents from Drive. To save the file, you can use Python standard library's `io` and `open` functions to write the contents received. from ...
🌐
Medium
medium.com › @aalam-info-solutions-llp › downloading-files-from-google-drive-link-to-a-target-folder-using-python-93b8c67f1304
Downloading files from Google Drive Link to a target folder using python | by Aalam Info Solutions LLP | Medium
August 26, 2024 - SCOPES = ['https://www.googleapis.com/auth/drive.readonly'] # Hard-coded inputs DRIVE_URL = 'https://drive.google.com/drive/folders/1eHdmkbaVUtHaTV-mMWn3N5h4KR_FGnDc' OUTPUT_FOLDER = 'Z:/GDRIVE/' def authenticate(): """Authenticate the user and return the service object.""" creds = None credentials_path = 'credentials.json' if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file(credenti
🌐
Rafael Huerta's Blog
blog.zephyrok.com › google-drive-api-with-python
Google Drive API with Python - Rafael Huerta's Blog
February 22, 2022 - Depending on the operation we want to perform, we will need to use the appropriate scope, for example, to download a file it will be enough to use https://www.googleapis.com/auth/drive.readonly, but for these code snippets, I will be using https://www.googleapis.com/auth/drive to have full access, available scopes can be found here.
🌐
PyPI
pypi.org › project › PyDrive
PyDrive · PyPI
PyDrive is a wrapper library of google-api-python-client that simplifies many common Google Drive API tasks. ... Simplifies OAuth2.0 into just few lines with flexible settings. Wraps Google Drive API into classes of each resource to make your program more object-oriented. Helps common operations else than API calls, such as content fetching and pagination control. You can install PyDrive with regular pip command. ... Download client_secrets.json from Google API Console and OAuth2.0 is done in two lines.
      » pip install PyDrive
    
Published   Oct 24, 2016
Version   1.3.1
🌐
Google
developers.google.com › google workspace › google drive › method: files.download
Method: files.download | Google Drive | Google for Developers
August 26, 2025 - Downloads the content of a file. For more information, see Download and export files. Operations are valid for 24 hours from the time of creation. POST https://www.googleapis.com/drive/v3/files/{fileId}/download