:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
from typing import Optional, cast
import requests
from products.warehouse_sources.sources.appsflyer._config import AppsFlyerSourceConfig
from products.warehouse_sources.sources.appsflyer.appsflyer import (
AppsFlyerCredentialsError,
AppsFlyerResumeConfig,
AppsFlyerRetryableError,
appsflyer_source,
validate_credentials as validate_appsflyer_credentials,
)
from products.warehouse_sources.sources.appsflyer.settings import ENDPOINTS, INCREMENTAL_FIELDS, SHOULD_SYNC_DEFAULT
from products.warehouse_sources.sources.sdk import (
CanonicalDescriptions,
DataWarehouseSourceCategory,
ExternalDataSourceType,
FieldType,
ReleaseStatus,
ResumableSource,
ResumableSourceManager,
SourceConfig,
SourceFieldInputConfig,
SourceFieldInputConfigType,
SourceInputs,
SourceRegistry,
SourceResponse,
SourceSchema,
build_endpoint_schemas,
detect,
)
@SourceRegistry.register
class AppsFlyerSource(ResumableSource[AppsFlyerSourceConfig, AppsFlyerResumeConfig]):
codebase_detection = detect(
env=("^APPSFLYER_",),
script_hosts=("websdk.appsflyersdk.com",),
npm=("react-native-appsflyer", "cordova-plugin-appsflyer-sdk"),
cocoapods=(
"AppsFlyerFramework",
"AppsFlyer-Core",
"AppsFlyer-SDK",
"AppsFlyerAdobeExtension",
"AppsFlyerDynamicFramework",
"AppsFlyerFWTestBuild",
"AppsFlyerFramework-MacCatalyst",
"AppsFlyerTracker",
"AppsFlyerTvOsLib",
"AppsFlyerTvOsLibStaging",
"AppsFlyerURLResolver",
"Beta-AppsFlyerFramework",
"appsflyer-apple-sdk-qa",
"appsflyer-apple-sdk-qa-MacCatalyst",
"segment-appsflyer-ios",
),
maven=(
"com.appsflyer:af-android-sdk",
"com.appsflyer:AppsFlyerAdobeExtension",
"com.appsflyer:AppsflyerLib",
"com.appsflyer:appsflyer-adobe-aep-sdk-extension",
"com.appsflyer:appsflyer-adobe-aep-sdk-extension-beta",
"com.appsflyer:appsflyer-adobe-sdk-extension",
"com.appsflyer:appsflyer-adobe-sdk-extension-beta",
"com.appsflyer:appsflyer-url-resolver",
),
pub=("appsflyer_sdk",),
swiftpm=(
"github.com/appsflyersdk/appsflyerframework",
"github.com/appsflyersdk/appsflyer-adobe-mobile-ios-swift-extension",
"github.com/appsflyersdk/appsflyer-apple-migration-helper",
"github.com/appsflyersdk/appsflyer-apple-purchase-connector",
"github.com/appsflyersdk/appsflyer-apple-rpc",
"github.com/appsflyersdk/appsflyer-apple-sdk-qa",
"github.com/appsflyersdk/appsflyer-capacitor-plugin",
"github.com/appsflyersdk/appsflyer-urlresolver-client",
"github.com/appsflyersdk/appsflyerframework-dynamic",
"github.com/appsflyersdk/appsflyerframework-static",
"github.com/appsflyersdk/appsflyerframework-strict",
"github.com/appsflyersdk/appsflyersdk-qa-spm-dynamic",
"github.com/appsflyersdk/appsflyersdk-qa-spm-static",
"github.com/appsflyersdk/appsflyersdk-qa-spm-strict",
"github.com/appsflyersdk/segment-appsflyer-ios",
),
)
api_docs_url = "https://support.appsflyer.com/hc/en-us/articles/207034366-Pull-APIs-aggregate-and-raw-data"
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.APPSFLYER
@property
def connection_host_fields(self) -> list[str]:
# app_id selects which AppsFlyer app the stored token is used against; changing it must
# require re-entering the secret so a preserved token can't be retargeted at another app.
return ["app_id"]
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
"401 Client Error: Unauthorized for url: https://hq1.appsflyer.com": "AppsFlyer authentication failed. Please check your API token (V2).",
"403 Client Error: Forbidden for url: https://hq1.appsflyer.com": "AppsFlyer denied access. Please check that your account's subscription includes the report being synced and the app id is correct.",
"404 Client Error: Not Found for url: https://hq1.appsflyer.com": "AppsFlyer app not found. Please check the app id.",
# A 400 from the Pull API is always a rejected request shape: the daily report quota is
# used up, the date range predates the raw-data lookback limit, or the row cap is
# invalid. None of those change if we send the identical call again.
"400 Client Error: Bad Request for url: https://hq1.appsflyer.com": "AppsFlyer rejected the report request. Your account's daily quota for this report may be used up, which resets at 00:00 UTC. Otherwise please check that your subscription includes this report.",
# Raw-data pulls redirect to a signed download URL on this host once the request is
# accepted, so a raw-data rejection surfaces here instead of on hq1.appsflyer.com.
"400 Client Error: Bad Request for url: https://rawdata.appsflyer.com": "AppsFlyer rejected the report request. Your account's daily quota for this report may be used up, which resets at 00:00 UTC. Otherwise please check that your subscription includes this report.",
# AppsFlyer overloads 416 as a catch-all for request/authorization validation failures on
# the aggregate Pull API (e.g. the account isn't authorized for this report or app id). The
# request shape is fixed, so retrying the identical call can never satisfy it.
"416 Client Error: Requested Range Not Satisfiable for url: https://hq1.appsflyer.com": "AppsFlyer rejected the report request. Please check that your account's subscription is authorized for this report and that the app id is correct.",
}
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.APPSFLYER,
category=DataWarehouseSourceCategory.ADVERTISING,
label="AppsFlyer",
caption="""Enter your AppsFlyer credentials to pull aggregate performance reports and raw event data into the PostHog Data warehouse.
You can find your API token (V2) in AppsFlyer under your account menu > Security center > AppsFlyer API tokens. You can find your app ID in AppsFlyer on the My apps page, under the app name (e.g. `id123456789` for iOS or the package name for Android). Add one source per app.
Raw data tables (installs, in-app events, uninstalls, retargeting conversions, ad revenue and the Protect360 fraud reports) and the Master API report need an AppsFlyer subscription that covers them. Protect360 is a separate add-on. AppsFlyer limits raw data to the last 90 days.""",
iconPath="/static/services/appsflyer.png",
docsUrl="https://posthog.com/docs/cdp/sources/appsflyer",
releaseStatus=ReleaseStatus.GA,
fields=cast(
list[FieldType],
[
SourceFieldInputConfig(
name="app_id",
label="App ID",
type=SourceFieldInputConfigType.TEXT,
required=True,
placeholder="id123456789",
caption="In AppsFlyer, open My apps and copy the ID under your app name, such as `id123456789` for iOS or `com.example.app` for Android.",
secret=False,
),
SourceFieldInputConfig(
name="api_token",
label="API token (V2)",
type=SourceFieldInputConfigType.PASSWORD,
required=True,
placeholder="",
secret=True,
),
],
),
)
def get_canonical_descriptions(self) -> CanonicalDescriptions:
from products.warehouse_sources.sources.appsflyer.canonical_descriptions import CANONICAL_DESCRIPTIONS
return CANONICAL_DESCRIPTIONS
def get_schemas(
self,
config: AppsFlyerSourceConfig,
team_id: int,
with_counts: bool = False,
names: list[str] | None = None,
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, should_sync_default=SHOULD_SYNC_DEFAULT)
def validate_credentials(
self,
config: AppsFlyerSourceConfig,
team_id: int,
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
try:
# validate_credentials returns True or raises — it never returns False — so an
# unexpected status surfaces its real cause instead of a conflated credential error.
validate_appsflyer_credentials(config.api_token, config.app_id)
return True, None
except AppsFlyerCredentialsError as e:
# The token or app id was rejected — surface which one rather than a conflated message.
return False, str(e)
except (AppsFlyerRetryableError, requests.RequestException):
# A rate-limit, 5xx, or network blip isn't a bad credential — don't mislabel it.
return (
False,
"Could not reach AppsFlyer to validate credentials. This may be a temporary rate-limit or network issue — please try again.",
)
def resume_covers_run(self, *, incremental_or_append: bool, schema_name: str | None = None) -> bool:
return incremental_or_append
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AppsFlyerResumeConfig]:
return ResumableSourceManager[AppsFlyerResumeConfig](inputs, AppsFlyerResumeConfig)
def source_for_pipeline(
self,
config: AppsFlyerSourceConfig,
resumable_source_manager: ResumableSourceManager[AppsFlyerResumeConfig],
inputs: SourceInputs,
) -> SourceResponse:
return appsflyer_source(
api_token=config.api_token,
app_id=config.app_id,
endpoint=inputs.schema_name,
logger=inputs.logger,
resumable_source_manager=resumable_source_manager,
should_use_incremental_field=inputs.should_use_incremental_field,
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
else None,
)