Google Drive API in Python | Getting Started

3 min read 2 hours ago
Published on Jan 18, 2025 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial provides a comprehensive guide to getting started with the Google Drive API in Python. It is designed for developers looking to integrate Google Drive functionality into their applications, allowing for enhanced cloud storage capabilities. You will learn how to set up your environment, install necessary libraries, and begin using the Google Drive API.

Step 1: Set Up Your Google Cloud Project

  1. Create a Google Cloud Project

    • Go to the Google Cloud Console.
    • Click on the project dropdown and select "New Project."
    • Name your project and click "Create."
  2. Enable the Google Drive API

    • In your Google Cloud Project dashboard, navigate to "APIs & Services."
    • Click on "Library."
    • Search for "Google Drive API" and click on it.
    • Click "Enable" to activate the API for your project.
  3. Create Credentials

    • Go to "APIs & Services" > "Credentials."
    • Click "Create Credentials" and select "OAuth client ID."
    • Configure the consent screen by providing necessary app details.
    • Select "Desktop app" as the application type and click "Create."
    • Download the credentials.json file and store it securely.

Step 2: Install Required Libraries

  1. Open your terminal or command prompt.
  2. Install the Google Client library by running the following command:
    pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
    
    • This command installs the necessary libraries to interact with the Google Drive API.

Step 3: Authenticate and Access Google Drive

  1. Create a Python script (e.g., google_drive_api.py).
  2. Add the following code to authenticate and access the Google Drive API:
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from google.auth.transport.requests import Request
    import os.path
    
    # If modifying these SCOPES, delete the file token.json.
    SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
    
    def main():
        creds = None
        # The file token.json stores the user's access and refresh tokens.
        if os.path.exists('token.json'):
            creds = Credentials.from_authorized_user_file('token.json', SCOPES)
        # If there are no (valid) credentials available, let the user log in.
        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(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open('token.json', 'w') as token:
                token.write(creds.to_json())
    
        # Call the Drive API
        from googleapiclient.discovery import build
        service = build('drive', 'v3', credentials=creds)
    
        # Print the names and ids of the first 10 files
        results = service.files().list(pageSize=10, fields="nextPageToken, files(id, name)").execute()
        items = results.get('files', [])
    
        if not items:
            print('No files found.')
        else:
            print('Files:')
            for item in items:
                print(f'{item["name"]} ({item["id"]})')
    
    if __name__ == '__main__':
        main()
    
  3. Run the script to authenticate and access your Google Drive files:
    python google_drive_api.py
    

Conclusion

You have successfully set up the Google Drive API in Python, created a project on Google Cloud, and authenticated to access your Google Drive files. You can expand this foundation by exploring additional API functionalities to upload, download, and manage files. As next steps, consider implementing file creation, sharing, or updating functionalities using the API.