google-ads-reports


Namegoogle-ads-reports JSON
Version 2.0.1 PyPI version JSON
download
home_pagehttps://github.com/machado000/google-ads-reports
SummarySimple Google Ads API client with automatic retries, exception handling, and flexible report generation
upload_time2025-09-01 11:43:37
maintainerNone
docs_urlNone
authorJoao Brito
requires_python<3.13,>=3.12
licenseMIT
keywords google-ads etl data-extraction reports serverless
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Google Ads Reports Helper

A Python ETL driver for Google Ads API v20 data extraction and transformation. Simplifies the process of extracting Google Ads data and converting it to database-ready pandas DataFrames with comprehensive optimization features.

[![PyPI version](https://img.shields.io/pypi/v/google-ads-reports)](https://pypi.org/project/google-ads-reports/)
[![Issues](https://img.shields.io/github/issues/machado000/google-ads-reports)](https://github.com/machado000/google-ads-reports/issues)
[![Last Commit](https://img.shields.io/github/last-commit/machado000/google-ads-reports)](https://github.com/machado000/google-ads-reports/commits/main)
[![License](https://img.shields.io/badge/License-GPL-yellow.svg)](https://github.com/machado000/google-ads-reports/blob/main/LICENSE)

## Features

- **Google Ads API v20**: Latest API version support with full compatibility
- **Database-Ready DataFrames**: Optimized data types and encoding for seamless database storage
- **Flexible Column Naming**: Choose between snake_case or camelCase column conventions
- **Smart Type Detection**: Dynamic conversion of metrics to appropriate int64/float64 types
- **Configurable Missing Values**: Granular control over NaN/NaT handling by column type
- **Character Encoding Cleanup**: Automatic text sanitization for database compatibility
- **Zero Impression Filtering**: Robust filtering handling multiple zero representations
- **Multiple Report Types**: Pre-configured report models for common use cases
- **Custom Reports**: Create custom report configurations with full GAQL support
- **Robust Error Handling**: Comprehensive error handling with retry logic and specific exceptions
- **Pagination Support**: Automatic handling of large datasets with pagination
- **Type Hints**: Full type hint support for better IDE experience

## Installation

```bash
pip install google-ads-reports
```

## Quick Start

### 1. Set up credentials

Create a `secrets/google-ads.yaml` file with your Google Ads API credentials:

```yaml
developer_token: "YOUR_DEVELOPER_TOKEN"
client_id: "YOUR_CLIENT_ID"
client_secret: "YOUR_CLIENT_SECRET"
refresh_token: "YOUR_REFRESH_TOKEN"
```
References:\
https://developers.google.com/google-ads/api/docs/get-started/introduction
https://developers.google.com/google-ads/api/docs/get-started/dev-token
https://developers.google.com/workspace/guides/create-credentials#service-account


### 2. Basic usage

```python
from datetime import date, timedelta
from google_ads_reports import GAdsReport, GAdsReportModel, load_credentials

# Load credentials
credentials = load_credentials()
client = GAdsReport(credentials)

# Configure report parameters
customer_id = "1234567890"
start_date = date.today() - timedelta(days=7)
end_date = date.today() - timedelta(days=1)

# Extract report data with database optimization
df = client.get_gads_report(
    customer_id=customer_id,
    report_model=GAdsReportModel.keyword_report,
    start_date=start_date,
    end_date=end_date,
    filter_zero_impressions=True,  # Remove rows with zero impressions
    column_naming="snake_case"     # Choose column naming: "snake_case" or "camelCase"
)

# Save to CSV
df.to_csv("keyword_report.csv", index=False)
```

### Column Naming Options

Choose between snake_case (database-friendly) or camelCase (API-consistent) column names:

```python
# Snake case (default) - metrics.impressions → impressions
df_snake = client.get_gads_report(
    customer_id=customer_id,
    report_model=GAdsReportModel.keyword_report,
    start_date=start_date,
    end_date=end_date,
    column_naming="snake_case"  # Default
)

# CamelCase - metrics.impressions → metricsImpressions  
df_camel = client.get_gads_report(
    customer_id=customer_id,
    report_model=GAdsReportModel.keyword_report,
    start_date=start_date,
    end_date=end_date,
    column_naming="camelCase"
)
```

## Available Report Models

- `GAdsReportModel.adgroup_ad_report` - Ad group ad performance
- `GAdsReportModel.keyword_report` - Keyword performance
- `GAdsReportModel.search_terms_report` - Search terms analysis
- `GAdsReportModel.conversions_report` - Conversion tracking
- `GAdsReportModel.video_report` - Video ad performance
- `GAdsReportModel.assetgroup_report` - Asset group performance

## Custom Reports

Create custom report configurations:

```python
from google_ads_reports import create_custom_report

custom_report = create_custom_report(
    report_name="campaign_performance",
    select=[
        "campaign.name",
        "campaign.status", 
        "segments.date",
        "metrics.impressions",
        "metrics.clicks",
        "metrics.cost_micros"
    ],
    from_table="campaign",
    where="metrics.impressions > 100"
)

df = client.get_gads_report(customer_id, custom_report, start_date, end_date)
```

## Database Optimization Features

The package automatically optimizes DataFrames for database storage:

### Data Type Optimization
- **Automatic Date Conversion**: String dates → `datetime64[ns]`
- **Dynamic Metrics Conversion**: Object metrics → `int64` or `float64` based on data
- **Smart Integer Detection**: Whole numbers become `int64`, decimals become `float64`

### Missing Value Handling
- **Preserve NULL Compatibility**: NaN/NaT preserved for database NULL mapping
- **Configurable by Type**: Different strategies for numeric, datetime, and text columns
- **Safe Conversion**: Invalid values gracefully ignored

### Character Encoding Cleanup
- **ASCII Sanitization**: Removes non-ASCII characters for database compatibility  
- **Null Byte Removal**: Strips problematic null bytes (`\x00`)
- **Length Limiting**: Truncates text to 255 characters (configurable)
- **Whitespace Trimming**: Removes leading/trailing whitespace

### Zero Impression Filtering
Handles multiple zero representations:
```python
df = client.get_gads_report(
    customer_id=customer_id,
    report_model=report_model,
    start_date=start_date,
    end_date=end_date,
    filter_zero_impressions=True  # Removes: 0, "0", 0.0, "0.0", None, NaN
)
```

### Flexible Column Naming
Choose your preferred column naming convention:

**Snake Case (Default - Database Friendly):**
- `metrics.impressions` → `impressions`
- `segments.date` → `date`  
- `adGroupCriterion.keyword` → `keyword`

**CamelCase (API Consistent):**
- `metrics.impressions` → `metricsImpressions`
- `segments.date` → `segmentsDate`
- `adGroupCriterion.keyword` → `adGroupCriterionKeyword`

```python
# Choose naming convention
df = client.get_gads_report(
    customer_id=customer_id,
    report_model=report_model,
    start_date=start_date,
    end_date=end_date,
    column_naming="snake_case"  # or "camelCase"
)
```

## Error Handling

The package provides specific exception types for different scenarios:

```python
from google_ads_reports import (
    GAdsReport, 
    AuthenticationError, 
    ValidationError, 
    APIError,
    DataProcessingError,
    ConfigurationError
)

try:
    df = client.get_gads_report(customer_id, report_model, start_date, end_date)
except AuthenticationError:
    # Handle credential issues
    pass
except ValidationError:
    # Handle input validation errors
    pass
except APIError:
    # Handle API errors (after retries)
    pass
```

## Examples

Check the `examples/` directory for comprehensive usage examples:

- `basic_usage.py` - Simple report extraction
- `multiple_reports.py` - Batch report processing  
- `custom_reports.py` - Custom report creation
- `error_handling.py` - Error handling patterns

## Configuration

### Retry Settings

API calls automatically retry on transient errors with configurable settings:

- **Max attempts**: 3 (default)
- **Base delay**: 1 second
- **Backoff factor**: 2x exponential
- **Max delay**: 30 seconds

### Logging

Configure logging level:

```python
from google_ads_reports import setup_logging
import logging

setup_logging(level=logging.DEBUG)  # Enable debug logging
```

## Requirements

- Python 3.9-3.12
- google-ads >= 24.0.0 (Google Ads API v20 support)
- pandas >= 2.0.0
- PyYAML >= 6.0.0
- python-dotenv >= 1.0.0
- tqdm >= 4.65.0

## Development

For development installation:

```bash
git clone https://github.com/machado000/google-ads-reports
cd google-ads-reports
pip install -e ".[dev]"
```

## License

GPL License. See [LICENSE](LICENSE) file for details.

## Support

- [Documentation](https://github.com/machado000/google-ads-reports#readme)
- [Issues](https://github.com/machado000/google-ads-reports/issues)
- [Examples](examples/)

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/machado000/google-ads-reports",
    "name": "google-ads-reports",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<3.13,>=3.12",
    "maintainer_email": null,
    "keywords": "google-ads, etl, data-extraction, reports, serverless",
    "author": "Joao Brito",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/70/bc/7041002b7887a517237989c1f933b17d6325b15d163d504ea6e989ac9f58/google_ads_reports-2.0.1.tar.gz",
    "platform": null,
    "description": "# Google Ads Reports Helper\n\nA Python ETL driver for Google Ads API v20 data extraction and transformation. Simplifies the process of extracting Google Ads data and converting it to database-ready pandas DataFrames with comprehensive optimization features.\n\n[![PyPI version](https://img.shields.io/pypi/v/google-ads-reports)](https://pypi.org/project/google-ads-reports/)\n[![Issues](https://img.shields.io/github/issues/machado000/google-ads-reports)](https://github.com/machado000/google-ads-reports/issues)\n[![Last Commit](https://img.shields.io/github/last-commit/machado000/google-ads-reports)](https://github.com/machado000/google-ads-reports/commits/main)\n[![License](https://img.shields.io/badge/License-GPL-yellow.svg)](https://github.com/machado000/google-ads-reports/blob/main/LICENSE)\n\n## Features\n\n- **Google Ads API v20**: Latest API version support with full compatibility\n- **Database-Ready DataFrames**: Optimized data types and encoding for seamless database storage\n- **Flexible Column Naming**: Choose between snake_case or camelCase column conventions\n- **Smart Type Detection**: Dynamic conversion of metrics to appropriate int64/float64 types\n- **Configurable Missing Values**: Granular control over NaN/NaT handling by column type\n- **Character Encoding Cleanup**: Automatic text sanitization for database compatibility\n- **Zero Impression Filtering**: Robust filtering handling multiple zero representations\n- **Multiple Report Types**: Pre-configured report models for common use cases\n- **Custom Reports**: Create custom report configurations with full GAQL support\n- **Robust Error Handling**: Comprehensive error handling with retry logic and specific exceptions\n- **Pagination Support**: Automatic handling of large datasets with pagination\n- **Type Hints**: Full type hint support for better IDE experience\n\n## Installation\n\n```bash\npip install google-ads-reports\n```\n\n## Quick Start\n\n### 1. Set up credentials\n\nCreate a `secrets/google-ads.yaml` file with your Google Ads API credentials:\n\n```yaml\ndeveloper_token: \"YOUR_DEVELOPER_TOKEN\"\nclient_id: \"YOUR_CLIENT_ID\"\nclient_secret: \"YOUR_CLIENT_SECRET\"\nrefresh_token: \"YOUR_REFRESH_TOKEN\"\n```\nReferences:\\\nhttps://developers.google.com/google-ads/api/docs/get-started/introduction\nhttps://developers.google.com/google-ads/api/docs/get-started/dev-token\nhttps://developers.google.com/workspace/guides/create-credentials#service-account\n\n\n### 2. Basic usage\n\n```python\nfrom datetime import date, timedelta\nfrom google_ads_reports import GAdsReport, GAdsReportModel, load_credentials\n\n# Load credentials\ncredentials = load_credentials()\nclient = GAdsReport(credentials)\n\n# Configure report parameters\ncustomer_id = \"1234567890\"\nstart_date = date.today() - timedelta(days=7)\nend_date = date.today() - timedelta(days=1)\n\n# Extract report data with database optimization\ndf = client.get_gads_report(\n    customer_id=customer_id,\n    report_model=GAdsReportModel.keyword_report,\n    start_date=start_date,\n    end_date=end_date,\n    filter_zero_impressions=True,  # Remove rows with zero impressions\n    column_naming=\"snake_case\"     # Choose column naming: \"snake_case\" or \"camelCase\"\n)\n\n# Save to CSV\ndf.to_csv(\"keyword_report.csv\", index=False)\n```\n\n### Column Naming Options\n\nChoose between snake_case (database-friendly) or camelCase (API-consistent) column names:\n\n```python\n# Snake case (default) - metrics.impressions \u2192 impressions\ndf_snake = client.get_gads_report(\n    customer_id=customer_id,\n    report_model=GAdsReportModel.keyword_report,\n    start_date=start_date,\n    end_date=end_date,\n    column_naming=\"snake_case\"  # Default\n)\n\n# CamelCase - metrics.impressions \u2192 metricsImpressions  \ndf_camel = client.get_gads_report(\n    customer_id=customer_id,\n    report_model=GAdsReportModel.keyword_report,\n    start_date=start_date,\n    end_date=end_date,\n    column_naming=\"camelCase\"\n)\n```\n\n## Available Report Models\n\n- `GAdsReportModel.adgroup_ad_report` - Ad group ad performance\n- `GAdsReportModel.keyword_report` - Keyword performance\n- `GAdsReportModel.search_terms_report` - Search terms analysis\n- `GAdsReportModel.conversions_report` - Conversion tracking\n- `GAdsReportModel.video_report` - Video ad performance\n- `GAdsReportModel.assetgroup_report` - Asset group performance\n\n## Custom Reports\n\nCreate custom report configurations:\n\n```python\nfrom google_ads_reports import create_custom_report\n\ncustom_report = create_custom_report(\n    report_name=\"campaign_performance\",\n    select=[\n        \"campaign.name\",\n        \"campaign.status\", \n        \"segments.date\",\n        \"metrics.impressions\",\n        \"metrics.clicks\",\n        \"metrics.cost_micros\"\n    ],\n    from_table=\"campaign\",\n    where=\"metrics.impressions > 100\"\n)\n\ndf = client.get_gads_report(customer_id, custom_report, start_date, end_date)\n```\n\n## Database Optimization Features\n\nThe package automatically optimizes DataFrames for database storage:\n\n### Data Type Optimization\n- **Automatic Date Conversion**: String dates \u2192 `datetime64[ns]`\n- **Dynamic Metrics Conversion**: Object metrics \u2192 `int64` or `float64` based on data\n- **Smart Integer Detection**: Whole numbers become `int64`, decimals become `float64`\n\n### Missing Value Handling\n- **Preserve NULL Compatibility**: NaN/NaT preserved for database NULL mapping\n- **Configurable by Type**: Different strategies for numeric, datetime, and text columns\n- **Safe Conversion**: Invalid values gracefully ignored\n\n### Character Encoding Cleanup\n- **ASCII Sanitization**: Removes non-ASCII characters for database compatibility  \n- **Null Byte Removal**: Strips problematic null bytes (`\\x00`)\n- **Length Limiting**: Truncates text to 255 characters (configurable)\n- **Whitespace Trimming**: Removes leading/trailing whitespace\n\n### Zero Impression Filtering\nHandles multiple zero representations:\n```python\ndf = client.get_gads_report(\n    customer_id=customer_id,\n    report_model=report_model,\n    start_date=start_date,\n    end_date=end_date,\n    filter_zero_impressions=True  # Removes: 0, \"0\", 0.0, \"0.0\", None, NaN\n)\n```\n\n### Flexible Column Naming\nChoose your preferred column naming convention:\n\n**Snake Case (Default - Database Friendly):**\n- `metrics.impressions` \u2192 `impressions`\n- `segments.date` \u2192 `date`  \n- `adGroupCriterion.keyword` \u2192 `keyword`\n\n**CamelCase (API Consistent):**\n- `metrics.impressions` \u2192 `metricsImpressions`\n- `segments.date` \u2192 `segmentsDate`\n- `adGroupCriterion.keyword` \u2192 `adGroupCriterionKeyword`\n\n```python\n# Choose naming convention\ndf = client.get_gads_report(\n    customer_id=customer_id,\n    report_model=report_model,\n    start_date=start_date,\n    end_date=end_date,\n    column_naming=\"snake_case\"  # or \"camelCase\"\n)\n```\n\n## Error Handling\n\nThe package provides specific exception types for different scenarios:\n\n```python\nfrom google_ads_reports import (\n    GAdsReport, \n    AuthenticationError, \n    ValidationError, \n    APIError,\n    DataProcessingError,\n    ConfigurationError\n)\n\ntry:\n    df = client.get_gads_report(customer_id, report_model, start_date, end_date)\nexcept AuthenticationError:\n    # Handle credential issues\n    pass\nexcept ValidationError:\n    # Handle input validation errors\n    pass\nexcept APIError:\n    # Handle API errors (after retries)\n    pass\n```\n\n## Examples\n\nCheck the `examples/` directory for comprehensive usage examples:\n\n- `basic_usage.py` - Simple report extraction\n- `multiple_reports.py` - Batch report processing  \n- `custom_reports.py` - Custom report creation\n- `error_handling.py` - Error handling patterns\n\n## Configuration\n\n### Retry Settings\n\nAPI calls automatically retry on transient errors with configurable settings:\n\n- **Max attempts**: 3 (default)\n- **Base delay**: 1 second\n- **Backoff factor**: 2x exponential\n- **Max delay**: 30 seconds\n\n### Logging\n\nConfigure logging level:\n\n```python\nfrom google_ads_reports import setup_logging\nimport logging\n\nsetup_logging(level=logging.DEBUG)  # Enable debug logging\n```\n\n## Requirements\n\n- Python 3.9-3.12\n- google-ads >= 24.0.0 (Google Ads API v20 support)\n- pandas >= 2.0.0\n- PyYAML >= 6.0.0\n- python-dotenv >= 1.0.0\n- tqdm >= 4.65.0\n\n## Development\n\nFor development installation:\n\n```bash\ngit clone https://github.com/machado000/google-ads-reports\ncd google-ads-reports\npip install -e \".[dev]\"\n```\n\n## License\n\nGPL License. See [LICENSE](LICENSE) file for details.\n\n## Support\n\n- [Documentation](https://github.com/machado000/google-ads-reports#readme)\n- [Issues](https://github.com/machado000/google-ads-reports/issues)\n- [Examples](examples/)\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Simple Google Ads API client with automatic retries, exception handling, and flexible report generation",
    "version": "2.0.1",
    "project_urls": {
        "Documentation": "https://github.com/machado000/google-ads-reports#readme",
        "Homepage": "https://github.com/machado000/google-ads-reports",
        "Issues": "https://github.com/machado000/google-ads-reports/issues"
    },
    "split_keywords": [
        "google-ads",
        " etl",
        " data-extraction",
        " reports",
        " serverless"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e47b3ec46c67d30081f067cbdeb154a971ffd1884f458a21326e3f3f879472d5",
                "md5": "6911178ec9dc3fd5d464163fb3ba1fd5",
                "sha256": "0d571820036eea4ec4e93aa555815b532abfd82e66322bb11c8bdc10aa983dae"
            },
            "downloads": -1,
            "filename": "google_ads_reports-2.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6911178ec9dc3fd5d464163fb3ba1fd5",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<3.13,>=3.12",
            "size": 30384,
            "upload_time": "2025-09-01T11:43:32",
            "upload_time_iso_8601": "2025-09-01T11:43:32.667170Z",
            "url": "https://files.pythonhosted.org/packages/e4/7b/3ec46c67d30081f067cbdeb154a971ffd1884f458a21326e3f3f879472d5/google_ads_reports-2.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "70bc7041002b7887a517237989c1f933b17d6325b15d163d504ea6e989ac9f58",
                "md5": "b4812cd45a63f7129aa5655936d14f90",
                "sha256": "463cbd48d7b69b92a9d842ccdd170055fddf7305f1a7e0f3800866d5dfba25f2"
            },
            "downloads": -1,
            "filename": "google_ads_reports-2.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "b4812cd45a63f7129aa5655936d14f90",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<3.13,>=3.12",
            "size": 30068,
            "upload_time": "2025-09-01T11:43:37",
            "upload_time_iso_8601": "2025-09-01T11:43:37.648268Z",
            "url": "https://files.pythonhosted.org/packages/70/bc/7041002b7887a517237989c1f933b17d6325b15d163d504ea6e989ac9f58/google_ads_reports-2.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-09-01 11:43:37",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "machado000",
    "github_project": "google-ads-reports",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "google-ads-reports"
}
        
Elapsed time: 1.75085s