# Meta Marketing API connector

Source: /docs/connectors/facebook-marketing.md

Use this as an implementation starting point: adapt the worked example to the requested dataset and the source documentation. See [Custom API](/docs/connectors/custom-api) for the shared SDK pattern and document-upload workflow.

## What this connector is for [#what-this-connector-is-for]

Facebook and Instagram advertising data for campaigns, audiences, and performance.

A connector owns access to the source. Separate syncs shape selected resources into tables for analysis and downstream transformations using the [Python SDK](/docs/reference/python/connectors-and-syncs).

## Data and tables you can pull [#data-and-tables-you-can-pull]

These are representative dataset families to consider, not a claim that the worked example implements every resource. Access, fields, and availability depend on the source account, product edition, and permissions. Use the [vendor reference](https://developers.facebook.com/docs/marketing-apis/) to select concrete resources.

| Suggested table | One row represents |
| --- | --- |
| `ad_accounts` | a ad account |
| `campaigns` | a campaign |
| `ad_sets` | a ad set |
| `ads` | a ad |
| `creatives` | a creative |
| `insights` | a requested report group |

### Relationships and extraction considerations [#relationships-and-extraction-considerations]

Choose stable object IDs and preserve references between related resources. Nested arrays may need child tables. The listed names are proposed output datasets; validate the actual endpoint, fields, permissions, and pagination before adding each sync.

## Connecting to Meta Marketing API [#connecting-to-meta-marketing-api]

Uses a Graph access token with ads_read and access to the ad account. App approval/business verification may be required. Supply an explicit supported Graph API version.

Additional resources may require additional scopes. Connection settings belong to the connector; dataset filters and resource selection belong to each sync. See the [CLI workflow](/docs/reference/cli/overview) for registration and configuration.

### Connection settings used by the example [#connection-settings-used-by-the-example]

| Setting | Requirement | Purpose |
| --- | --- | --- |
| `access_token` | Required; secret | Platform-supplied access token. Refresh or rotate before expiry. |
| `ad_account_id` | Required | Numeric ID without act_ prefix. |
| `api_version` | Required | Supported version such as v25.0; select a version supported by your app. |

### requirements.in [#requirementsin]

Save these dependencies in `requirements.in` alongside `connector.py`; the example includes packages used by its sync. Install the published `vortexify` package for local development. Keep sync-specific dependencies in the sync's own `requirements.in` when splitting the implementation into separate resources.

```text
vortexify==0.1.1
httpx>=0.27,<1
pandas>=2,<3
```

No separately installed database driver is needed by this HTTP example.

## Worked example: sync `campaigns` [#worked-example-sync-campaigns]

**campaigns** — Full read using the API's native pagination.

The complete files below implement only this example resource. They illustrate the current SDK signatures, a separate preview, bounded DataFrame output, and source-specific extraction. They do not establish complete source coverage. Live credentials and platform ingestion have not been used to validate this guide.

With default paths, place the connector files in `connectors/facebook-marketing/` and sync files in `connectors/facebook-marketing/syncs/campaigns/`. Use your project configuration if it specifies different paths.

### Connection schema: `config.json` [#connection-schema-configjson]

This file contains a JSON Schema, not actual credential values. Provide those through platform configuration.

```json
{
  "type": "object",
  "properties": {
    "access_token": {
      "type": "string",
      "title": "Access Token",
      "description": "Platform-supplied access token. Refresh or rotate before expiry.",
      "minLength": 1,
      "x-vortexify-secret": true,
      "order": 0
    },
    "ad_account_id": {
      "type": "string",
      "title": "Ad Account ID",
      "description": "Numeric ID without act_ prefix.",
      "minLength": 1,
      "order": 1
    },
    "api_version": {
      "type": "string",
      "title": "Graph API Version",
      "description": "Supported version such as v25.0; select a version supported by your app.",
      "minLength": 1,
      "order": 2
    }
  },
  "required": [
    "access_token",
    "ad_account_id",
    "api_version"
  ]
}
```

### Connector: `connector.py` [#connector-connectorpy]

```python
import httpx
from vortexify import Column, Connector, DiscoveredTable


class FacebookMarketingConnector(Connector):
    vendor_domain = "meta.com"

    def client(self):
        if self._client is None or self._client.is_closed:
            self._client = httpx.Client(
                base_url="https://graph.facebook.com/"
                + self.config["api_version"]
                + "/",
                headers={
                    "Authorization": "Bearer " + self.config["access_token"],
                    "Accept": "application/json",
                },
                timeout=60,
                follow_redirects=False,
            )
        return self._client

    def check(self) -> bool:
        cfg = self.config
        page_size = 1
        path = "act_" + cfg["ad_account_id"] + "/campaigns"
        params = {"limit": page_size, "fields": "id,name,status,objective,updated_time"}
        response = self.client().get(path, params=params)
        response.raise_for_status()
        payload = response.json()
        return True

    def discover(self) -> list[DiscoveredTable]:
        return [
            DiscoveredTable(
                name="campaigns",
                schema=[
                    Column(name="id", type="string"),
                    Column(name="name", type="string"),
                    Column(name="status", type="string"),
                    Column(name="objective", type="string"),
                    Column(name="updated_time", type="timestamp"),
                    Column(name="document", type="string"),
                ],
            )
        ]

    def close(self) -> None:
        if self._client is not None:
            try:
                self._client.close()
            finally:
                self._client = None
```

### Sync schema: `syncs/campaigns/config.json` [#sync-schema-syncscampaignsconfigjson]

```json
{
  "type": "object",
  "properties": {},
  "required": []
}
```

### Sync: `syncs/campaigns/sync.py` [#sync-syncscampaignssyncpy]

```python
from collections.abc import Iterator
from math import isfinite
import json
import pandas as pd
from vortexify import Sync


class FacebookMarketingCampaignsSync(Sync):

    def preview(self) -> pd.DataFrame:
        cfg = self.connector.config
        page_size = 100
        path = "act_" + cfg["ad_account_id"] + "/campaigns"
        params = {"limit": page_size, "fields": "id,name,status,objective,updated_time"}
        response = self.client.get(path, params=params)
        response.raise_for_status()
        payload = response.json()
        records = payload["data"]
        if not isinstance(records, list) or any(
            (not isinstance(record, dict) for record in records)
        ):
            raise ValueError(
                "Unexpected API record shape; refusing a partial successful sync"
            )
        records = records[:100]
        rows = []
        for record in records:
            row = {
                "id": record.get("id"),
                "name": record.get("name"),
                "status": record.get("status"),
                "objective": record.get("objective"),
                "updated_time": record.get("updated_time"),
                "document": json.dumps(record, ensure_ascii=False, default=str),
            }
            rows.append(
                {
                    key: (
                        json.dumps(value, ensure_ascii=False, default=str)
                        if isinstance(value, (dict, list))
                        else value
                    )
                    for key, value in row.items()
                }
            )
        return pd.DataFrame(
            rows,
            columns=["id", "name", "status", "objective", "updated_time", "document"],
            dtype=object,
        )

    def extract(
        self, *, avg_row_size_bytes: float | None = None
    ) -> Iterator[pd.DataFrame]:
        memory_mib = self.compute.memory if self.compute else None
        memory_mib = memory_mib if memory_mib is not None and memory_mib > 0 else 1024
        target_bytes = min(16 * 1024 * 1024, max(1, memory_mib * 1024 * 1024 // 20))
        batch_size = 100
        if avg_row_size_bytes is not None:
            if not isfinite(avg_row_size_bytes) or avg_row_size_bytes <= 0:
                raise ValueError("avg_row_size_bytes must be finite and positive")
            batch_size = max(1, int(target_bytes / max(1.0, avg_row_size_bytes) / 4))
        batch_size = min(batch_size, 100)
        cfg = self.connector.config
        page_size = batch_size
        path = "act_" + cfg["ad_account_id"] + "/campaigns"
        params = {"limit": page_size, "fields": "id,name,status,objective,updated_time"}
        seen_pages = set()
        while True:
            response = self.client.get(path, params=params)
            response.raise_for_status()
            payload = response.json()
            records = payload["data"]
            if not isinstance(records, list) or any(
                (not isinstance(record, dict) for record in records)
            ):
                raise ValueError(
                    "Unexpected API record shape; refusing a partial successful sync"
                )
            rows = []
            for record in records:
                row = {
                    "id": record.get("id"),
                    "name": record.get("name"),
                    "status": record.get("status"),
                    "objective": record.get("objective"),
                    "updated_time": record.get("updated_time"),
                    "document": json.dumps(record, ensure_ascii=False, default=str),
                }
                rows.append(
                    {
                        key: (
                            json.dumps(value, ensure_ascii=False, default=str)
                            if isinstance(value, (dict, list))
                            else value
                        )
                        for key, value in row.items()
                    }
                )
            for start in range(0, len(rows), batch_size):
                yield pd.DataFrame(
                    rows[start : start + batch_size],
                    columns=[
                        "id",
                        "name",
                        "status",
                        "objective",
                        "updated_time",
                        "document",
                    ],
                    dtype=object,
                )
            next_url = payload.get("paging", {}).get("next")
            if not next_url:
                break
            next_address = self.client.base_url.join(next_url)
            if (next_address.scheme, next_address.host, next_address.port) != (
                self.client.base_url.scheme,
                self.client.base_url.host,
                self.client.base_url.port,
            ):
                raise ValueError("Unexpected pagination origin")
            next_url = str(next_address)
            if next_url in seen_pages:
                raise ValueError("API repeated a pagination URL")
            seen_pages.add(next_url)
            path, params = (next_url, {})
```

### Running and extending the example [#running-and-extending-the-example]

Register the connector before the sync and commit each resource separately:

```sh
vortexify create connector facebook-marketing
vortexify create sync facebook-marketing/campaigns
```

Edit the files, inspect `vortexify status`, and use the [CLI guide](/docs/reference/cli/overview) to commit and configure them. Registration alone does not run extraction or deploy the connector.

Preview must run with a fresh connector and disposable state. The extraction implementation determines full/incremental behavior; merely setting a mode does not implement change capture. API/driver failures propagate unless explicitly handled in the code. Check source limits and single-record/response sizes as well as output batch size.

## Sources and further reading [#sources-and-further-reading]

- [Vendor API and data reference](https://developers.facebook.com/docs/marketing-apis/) — Resource definitions, authentication, fields, and source-specific limits. Check the selected resource's reference when extending the example.
- [Vortexify connector and sync contracts](/docs/reference/python/connectors-and-syncs) — Client ownership, discovery, preview isolation, and DataFrame extraction.
- [Vortexify CLI workflow](/docs/reference/cli/overview) — Project paths, resource registration, source commits, and credential configuration.
