Skip to main content

A comprehensive Python wrapper for Google APIs with async support, providing clean and intuitive access to Gmail, Google Drive, Google Calendar, and Google Tasks services.

Project description

Google API Client Wrapper

A comprehensive Python wrapper for Google APIs, providing clean and intuitive access to Gmail, Google Drive, Google Calendar, Google Tasks, Google Docs, and Google Sheets services with both synchronous and asynchronous implementations.

Installation

pip install google-api-client-wrapper

or install directly from the GitHub repository:

pip install git+https://github.com/dsmolla/google-api-client-wrapper.git

Features

  • Gmail Service: Send, receive, search, and manage emails
  • Google Drive Service: Upload, download, and manage files and folders
  • Google Calendar Service: Create, update, and manage calendar events
  • Google Tasks Service: Manage tasks and task lists
  • Google Sheets Service: Read, write, format, and batch-mutate spreadsheets
  • Google Docs Service: Create, read, and perform complex batch formatting and structural mutations on Google Documents
  • Async Support: Full async/await support for all services with concurrent batch operations
  • OAuth2 Authentication: Secure authentication flow with token management
  • Query Builders: Intuitive query building for each service
  • Multi-User Authentication: Supports multiple users to be authenticated
  • Dataclass Models: Uses Python dataclasses for clean, type-safe data structures (EmailMessage, Task, CalendarEvent, etc.)
  • Timezone Aware: Proper timezone handling across all services

Quick Start

Authentication

from google_client.auth import GoogleOAuthManager, Scopes
import json

# Initialize OAuth manager
with open('credentials.json', 'r') as f:
    client_secrets = json.load(f)

oauth_manager = GoogleOAuthManager(
    client_secrets_dict=client_secrets,
    redirect_uri='http://localhost:8080/oauth2callback'
)

# Generate authorization URL
auth_url, state = oauth_manager.generate_auth_url(
    scopes=[Scopes.GMAIL, Scopes.DRIVE, Scopes.CALENDAR, Scopes.TASKS, Scopes.SHEETS]
)

# After user authorizes, exchange code for tokens
user_info = oauth_manager.complete_auth_flow(
    code='authorization_code_from_callback',
    scopes=[Scopes.GMAIL, Scopes.DRIVE, Scopes.CALENDAR, Scopes.TASKS, Scopes.SHEETS]
)

# Save user_info for future use
with open('user_token.json', 'w') as f:
    json.dump(user_info, f)

Local Server Authentication (Development Only)

For development and testing, you can use the local server authentication method that automatically handles the OAuth callback:

from google_client.auth import GoogleOAuthManager, Scopes
import json

# Load client secrets
with open('credentials.json', 'r') as f:
    client_secrets = json.load(f)

# Initialize OAuth manager (redirect_uri defaults to localhost:8080)
oauth_manager = GoogleOAuthManager(
    client_secrets_dict=client_secrets
)

# Authenticate using local server - browser opens automatically!
user_info = oauth_manager.authenticate_via_local_server(
    scopes=[Scopes.GMAIL, Scopes.DRIVE, Scopes.CALENDAR, Scopes.TASKS, Scopes.SHEETS]
)

# Save credentials
with open('user_token.json', 'w') as f:
    json.dump(user_info, f)

Important: This method is for NON-PRODUCTION use only. It's perfect for:

  • Local development and testing
  • Personal automation scripts
  • CLI tools for individual use

For production applications, use the manual generate_auth_url() and complete_auth_flow() methods with a secure HTTPS callback endpoint.

Requirements:

  • Add http://localhost:8080 to your Google Cloud Console OAuth2 client's authorized redirect URIs
  • Ensure the port is not already in use

Using Services (Synchronous)

from google_client.api_service import APIServiceLayer
import json

# Load user credentials
with open('user_token.json', 'r') as f:
    user_info = json.load(f)

# Initialize API service layer with timezone
api_service = APIServiceLayer(user_info, timezone='America/New_York')

# Access Gmail service
gmail = api_service.gmail
emails = gmail.list_emails(max_results=10)
email = gmail.get_email(emails[0])
print(f"Subject: {email.subject}")

# Access Drive service
drive = api_service.drive
files = drive.list(max_results=10)
folder = drive.create_folder("My Project")

# Access Calendar service
calendar = api_service.calendar
from datetime import datetime, timedelta
event = calendar.create_event(
    start=datetime.now(),
    end=datetime.now() + timedelta(hours=1),
    summary="Team Meeting"
)

# Access Tasks service
tasks = api_service.tasks
task = tasks.create_task(title="Review documents")

# Access Sheets service
sheets = api_service.sheets
values = sheets.get_values(spreadsheet_id="your_spreadsheet_id", range_name="Sheet1!A1:B2")
sheets.append_values_from_dicts("your_spreadsheet_id", "Sheet1!A1", [{"Name": "Alice", "Role": "Admin"}])

# Access Docs service
docs = api_service.docs
new_doc = docs.create_document(title="Automated Report")
docs.insert_table_with_data(new_doc.document_id, index=1, data=[["Column 1", "Column 2"]])

Using Services (Asynchronous)

import asyncio
from google_client.api_service import APIServiceLayer
import json

async def main():
    # Load user credentials
    with open('user_token.json', 'r') as f:
        user_info = json.load(f)

    # Initialize API service layer
    api_service = APIServiceLayer(user_info, timezone='America/New_York')

    # Access async Gmail service
    gmail = api_service.async_gmail
    message_ids = await gmail.list_emails(max_results=50)

    # Batch get emails concurrently (much faster than sync!)
    emails = await gmail.batch_get_emails(message_ids[:10])
    for email in emails:
        print(f"Subject: {email.subject}")

    # Access async Drive service
    drive = api_service.async_drive
    files = await drive.list(max_results=20)

    # Access async Calendar service
    calendar = api_service.async_calendar
    from datetime import datetime, timedelta
    events = await calendar.list_events(
        start=datetime.now(),
        end=datetime.now() + timedelta(days=7)
    )

    # Access async Tasks service
    tasks = api_service.async_tasks
    all_tasks = await tasks.list_tasks(show_completed=True)

    # Access async Sheets service
    sheets = api_service.async_sheets
    values = await sheets.get_values(spreadsheet_id="your_spreadsheet_id", range_name="Sheet1!A1:B2")

    # Access async Docs service
    docs = api_service.async_docs
    new_doc = await docs.create_document(title="Async Automated Report")
    extracted_text = await docs.get_document_text(new_doc.document_id)

# Run async code
asyncio.run(main())

Synchronous vs Asynchronous APIs

This library provides both synchronous and asynchronous versions of all services:

Synchronous (Blocking)

  • Use for simple scripts, CLIs, or sequential operations
  • Access via: api_service.gmail, api_service.drive, etc.
  • Methods are regular functions that block until complete

Asynchronous (Non-blocking)

  • Use for high-throughput applications or concurrent operations
  • Access via: api_service.async_gmail, api_service.async_drive, etc.
  • Methods are async functions using async/await
  • 10x-100x faster for batch operations (e.g., fetching 100 emails)

Performance Example

import time
import asyncio

# Synchronous - Sequential (slower)
start = time.time()
emails = []
for msg_id in message_ids[:50]:
    emails.append(gmail.get_email(msg_id))
print(f"Sync: {time.time() - start:.2f}s")  # ~15-20 seconds

# Asynchronous - Concurrent (faster)
start = time.time()
emails = await async_gmail.batch_get_emails(message_ids[:50])
print(f"Async: {time.time() - start:.2f}s")  # ~1-2 seconds

Authentication Methods Comparison

Manual OAuth Flow (Production)

Use for: Web applications, mobile apps, production services

# Step 1: Generate auth URL
auth_url, state = oauth_manager.generate_auth_url(scopes=[Scopes.GMAIL])
print(f"Visit: {auth_url}")

# Step 2: User authorizes and you receive callback with code
# Your web server captures the code parameter

# Step 3: Complete the flow
user_info = oauth_manager.complete_auth_flow(
    code='authorization_code_from_callback',
    scopes=[Scopes.GMAIL]
)

Pros:

  • Production-ready with HTTPS
  • Scalable for multiple users
  • Works in web applications
  • Full control over callback handling

Cons:

  • Requires manual code copying/pasting (if not automated)
  • More steps to implement

Local Server Auth (Development)

Use for: Local scripts, testing, development, personal tools

# One-step authentication
user_info = oauth_manager.authenticate_via_local_server(
    scopes=[Scopes.GMAIL]
)
# Browser opens, user authorizes, done!

Pros:

  • Extremely simple one-liner
  • Automatic browser handling
  • No manual code copying
  • Great developer experience
  • Perfect for local automation

Cons:

  • localhost only (NOT for production)
  • Requires browser access
  • Single-user scenarios only
  • Must configure localhost in Google Console

Service Documentation

Each service has detailed documentation with examples and API reference:

Available Scopes

from google_client.auth import Scopes

Scopes.GMAIL      # Full Gmail access
Scopes.DRIVE      # Full Drive access
Scopes.CALENDAR   # Full Calendar access
Scopes.TASKS      # Full Tasks access
Scopes.SHEETS     # Full Sheets access
Scopes.DOCS       # Full Docs access

Token Refresh

from google_client.auth import GoogleOAuthManager

# Refresh expired tokens
refreshed_token = GoogleOAuthManager.refresh_user_token(
    user_info=user_info,
    scopes=[Scopes.GMAIL, Scopes.DRIVE]
)

# Or use the built-in method on APIServiceLayer
api_service = APIServiceLayer(user_info)
refreshed_token = api_service.refresh_token()

Links


See individual service documentation for detailed usage examples and API references.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

google_api_client_wrapper-3.0.0.tar.gz (77.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

google_api_client_wrapper-3.0.0-py3-none-any.whl (107.8 kB view details)

Uploaded Python 3

File details

Details for the file google_api_client_wrapper-3.0.0.tar.gz.

File metadata

File hashes

Hashes for google_api_client_wrapper-3.0.0.tar.gz
Algorithm Hash digest
SHA256 72c27dc3969bfce9ab6f224a68b06d6b9838aea4eab4788d7796a130467ae532
MD5 b2fa9194553415c55a84f145911c514c
BLAKE2b-256 a21ca4cf4d5306922770c502ba08e2dcf4fbae16a5143ac36c86aa40ed35106c

See more details on using hashes here.

Provenance

The following attestation bundles were made for google_api_client_wrapper-3.0.0.tar.gz:

Publisher: python-publish.yml on dsmolla/google-api-client-wrapper

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file google_api_client_wrapper-3.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for google_api_client_wrapper-3.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2b50d36497f586e9d000644e8982e36ea9f35ff9de8fb0053bd748a10162fc2e
MD5 5a886bdd81b02cd3f486f91fbd982d63
BLAKE2b-256 b0e41b4bb171202f6aa072798e3f6f709071848701f6777c07ae45d36aed7f62

See more details on using hashes here.

Provenance

The following attestation bundles were made for google_api_client_wrapper-3.0.0-py3-none-any.whl:

Publisher: python-publish.yml on dsmolla/google-api-client-wrapper

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page