Skip to main content

ETL module for Facebook Ads API v22 with database-optimized DataFrame processing

Project description

Facebook Ads Reports Helper

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

PyPI version Last Commit Issues License

Features

  • Facebook Marketing API v23: Latest API version support with full compatibility
  • Robust Error Handling: Comprehensive error handling with retry logic and specific exceptions
  • Multiple Report Types: Pre-configured report models for common use cases
  • Custom Reports: Create custom report configurations
  • Database-Ready DataFrames: Optimized data types and encoding for seamless database storage
  • 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
  • Type Hints: Full type hint support for better IDE experience

Installation

pip install facebook-ads-reports

Quick Start

1. Set up credentials

Option A: Configuration file

Create a secrets/fb_business_config.json file with your Facebook Ads API credentials:

{
  "app_id": "YOUR_APP_ID",
  "app_secret": "YOUR_APP_SECRET",
  "access_token": "YOUR_ACCESS_TOKEN",
  "ad_account_id": "act_1234567890",
  "base_url": "https://graph.facebook.com/v23.0"
}

Option B: Environment variable

Set the FACEBOOK_ADS_CONFIG_JSON environment variable with your credentials as JSON:

export FACEBOOK_ADS_CONFIG_JSON='{"app_id": "YOUR_APP_ID", "app_secret": "YOUR_APP_SECRET", "access_token": "YOUR_ACCESS_TOKEN", "ad_account_id": "act_1234567890", "base_url": "https://graph.facebook.com/v23.0"}'

2. Basic usage

from datetime import date, timedelta
from facebook_ads_reports import MetaAdsReport, MetaAdsReportModel, load_credentials

# Load credentials
credentials = load_credentials()
client = MetaAdsReport(credentials_dict=credentials)

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

# Extract report data with database optimization
df = client.get_insights_report(
        ad_account_id=ad_account_id,
        report_model=MetaAdsReportModel.ad_performance_report,
        start_date=start_date,
        end_date=end_date
)

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

Available Report Models

  • MetaAdsReportModel.ad_dimensions_report - Ad dimensions and metadata
  • MetaAdsReportModel.ad_performance_report - Ad performance and actions metrics

Custom Reports

Create custom report configurations:

from facebook_ads_reports import create_custom_report

custom_report = create_custom_report(
    report_name="my_custom_report",
    select=["ad_id", "impressions", "spend"],
    from_table="ad_insights"
)

# Usage:
# df = client.get_insights_report(ad_account_id, custom_report, start_date, end_date)

Database Optimization Features

  • Automatic Date Conversion: String dates → datetime64[ns]
  • Dynamic Metrics Conversion: Object metrics → int64 or float64 based on data
  • Preserve NULL Compatibility: NaN/NaT preserved for database NULL mapping
  • Safe Conversion: Invalid values gracefully ignored
  • ASCII Sanitization: Removes non-ASCII characters for database compatibility
  • Length Limiting: Truncates text to 255 characters (configurable)
  • Whitespace Trimming: Removes leading/trailing whitespace

Examples

Check the examples/ directory for comprehensive usage examples:

  • basic_usage.py - Simple report extraction

Requirements

  • Python 3.10-3.12
  • pandas >= 2.0.0
  • python-dotenv >= 1.0.0
  • requests >= 2.32.4
  • tqdm >= 4.65.0

License

GPL License. See LICENSE file for details.

Support

Contributing

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

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

facebook_ads_reports-1.0.1.tar.gz (26.8 kB view details)

Uploaded Source

Built Distribution

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

facebook_ads_reports-1.0.1-py3-none-any.whl (28.1 kB view details)

Uploaded Python 3

File details

Details for the file facebook_ads_reports-1.0.1.tar.gz.

File metadata

  • Download URL: facebook_ads_reports-1.0.1.tar.gz
  • Upload date:
  • Size: 26.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.4 CPython/3.12.3 Linux/5.15.167.4-microsoft-standard-WSL2

File hashes

Hashes for facebook_ads_reports-1.0.1.tar.gz
Algorithm Hash digest
SHA256 f8cf049119909cd969b51262d499571f0981a4e1c625143e51ce8c673fc1a0a3
MD5 9d244bc82793dab907c27ac0531167eb
BLAKE2b-256 7db0fbc7dc1cd123e706a8b61365e677dbeae2be360567554d7f7570c3775cb5

See more details on using hashes here.

File details

Details for the file facebook_ads_reports-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: facebook_ads_reports-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 28.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.4 CPython/3.12.3 Linux/5.15.167.4-microsoft-standard-WSL2

File hashes

Hashes for facebook_ads_reports-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 93131a75ecf66d8fe6a04e16f8b7d0a10b7aea45030ddda9c98f7fb24a544db4
MD5 0ece80e0092759c12694d99db58cc15a
BLAKE2b-256 2cf03cb5d6af26b59edde09994c9ce14db2dae35c2f47c3eca983dbc521bcd1b

See more details on using hashes here.

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