Cohort API

At a glance: Cohort reporting API provides advertisers a programmatic way to get Cohort data. Use the API to integrate Cohort data into BI, and marketing automation systems.

Example cohort report in the AppsFlyer dashboard

CohortEg_us-en.jpg

Cohort reporting API

The Cohort reporting API is used to get cohorted campaign performance data from the AppsFlyer platform. It is functionally equivalent to the Cohort dashboard

Related reading: Differences between Cohort flavors

Considerations for developers

  • Dates: Dates or date ranges refer to lifetime value (LTV) dates, meaning the date the user attributed (converted) and not the date of the activity itself.
  • Boolean values: Being true or false (case sensitive).
  • Transparent and non-transparent agency traffic: The media source of agency-driven traffic is always the agency and not the original media source. At present, the UI version of cohort behaves differently. 
  • Single app: Cohort API is a single app solution. This is in contrast to the Cohort dashboard which supports multiple apps in a single call. 
  • Data freshness: See traits and limitations

API instructions

The sections contain the information necessary for you to generate and use the Cohort API. 

Cohort API facts

Overview The API call consists of the path, headers, and a JSON containing the data query. Data is returned by default in a CSV file.
Path

https://hq1.appsflyer.com/api/cohorts/v1/data/app/app_id

Path parameters  (mandatory)
  • app_id: Is the app identifier as found in the AppsFlyer dashboard. Insert it exactly as it appears in the dashboard.

Query parameters

(optional)

Results return as CSV or JSON. The CSV file structure is tabular while that of the JSON record orientated.

  • [Default] csv the file name depends on the query.
  • json containing a query and results section
  • Example: format=json
  • https://hq1.appsflyer.com/api/cohorts/v1/data/app/app_id?format=json
HTTP method POST
Accepted content types application/json
Authorization
  • Bearer token in the request header
  • Reach out to your CSM to enable Cohort API and then Get the token in the dashboard
    • The same token is used for all apps in the account
Date limitations
  • Earliest date supported: 730 days before the current date. Meaning 2 years)
  • Maximum query range: 60 days.
Rate limitation
  • API call-rate limit-to 60 calls per minute and 50,000 calls day per account
  • Queries return up to 10,000 rows
Boolean values Always in lower case: true, false
Cohort API facts

Request headers

Key

Value Mandatory
Content-Type application/json Yes 
Authorization Bearer api_token_placeholder Yes 
Accept application/json Yes 

Filtering and grouping parameters

Use filter parameters to get the necessary data. 

Filter parameters

Parameter name

Description Mandatory 

cohort _type

Cohort attribution (conversion) type is one of the following: user_acquisitionretargetingunified

  • Unified combines the performance of user acquisition and retargeting campaigns.
  • If an event is attributed to both retargeting and user acquisition campaigns, only the retargeting event is included in KPIs returned, meaning is_primary=true
  • Format: String
  • Example: "cohort_type": "user_acquisition"
Yes

min_cohort_size

Minimum cohort size is used to reduce the number of records returned by excluding cohorts having few users. This means that the users KPI has a value equal or greater to that specified. 

  • Format: Integer
  • Minimum value allowed: 1. Don't send 0 (Zero)
  • Default: 1 
  • Example: "min_cohort_size": 50
No

from 

Lower bound of the LTV attribution date range. The earliest date supported is 720 days before the current date. 

  • Format: String yyyy-mm-dd
  • Example: "from": "2020-01-02"
Yes

to

Higher bound of the LTV attribution date range

  • Number of the days in the range: 1-31 days
  • For a single day: from and to values are identical. 
  • Format: yyyy-mm-dd
  • Example: "from": "2020-01-01", "to": 2020-01-31 is 31 days.
Yes

granularity

Hourly granularity for the previous 72 hours by setting  "granularity": "hour" and setting the from and to range to include the time of day.

  • Format: yyyy-mm-dd hh:mm:ss
  • Example:
"granularity": "hour", "from": "2021-12-01 14:00:00", "to": "2021-12-03 11:00:00",
No

partial_data

To avoid data distortion and misinterpretation Cohort returns data of complete days. However, the data of partial days can be useful. 

The number of complete cohort days for a query is calculated as the difference between today's date and the to date.

  • [Default] If false, complete days return.
  • If true, up to 180 cohort days return, including days having incomplete data. 
  • Format: Boolean
  • Platform UI version: false

Example: On May 10, the number of complete cohort days for users converting during April 1-30, is 10. 

  • If false [default], cohort days 0-9, return. This is the number of days (10) between the last conversion date and today. 
  • If true, cohort days 1-40 return. Days 11-40 contain partial data and do not return. For example, since April 20, only 20 days have elapsed, and so on. 
 No

filters

Filter the data and period days returned. Select filters from the filter dimensions list.

  • Format: Strings in a nested JSON
  • Example limit to specific Geos: "filters": {"geo": "US"} includes only users attributed to the United States. 
  • Example period (cohort) days: The period filter sets the days for which measures are returned. The possible values are: 0-180.
  • Default: If no period filter is set the days 0-30, 60, 90, and 180 return. Example filter with period
 No

Use groupings to include additional columns and make your reports less granular.

Grouping parameters

Parameter

Values Mandatory 

groupings

  • Select 1-7 groupings from the grouping dimensions list.
  • Format: Strings in an array
  • Example: "groupings": ["af_ad", "c", "af_c_id", "af_prt"]
Yes

Selecting and formatting KPIs

  • The table lists the KPIs available and their associated functions. When you call a KPI, all its functions return.
  • The following KPIs always return: users, ecpi, and cost 
  • Select one additional KPI per call.
Available KPIs and associated functions
    Functions
Default/ Optional  KPI (Dimensions name)  Count cvr (conversion rate) Rate Sum Unique users
Number Percentage Percentage Number Number
Always users - - - -
Always ecpi - - - -
Always cost - - - -
Optional "event_name" - ✓ (3)
Optional revenue - - -
Optional ROAS - - - -
Optional roi - - - -
Optional sessions - - ✓(1)
Optional uninstalls (2) - - -

(1) Unique sessions returns when aggregation_type=on_day

(2) Not available when cohort_type=unified 

(3) Sum means the total revenue generated by the event. In the report, this is denoted by sum_event_name"

Parameter

Values Mandatory parameter

kpis

Select one KPI from the KPIs available. In the future, we plan to allow the selection of multiple KPIs.

  • For each KPI requested, all functions are returned. 
  • Format: Strings in an array 
  • Example A: "kpis": ["sessions"]
  • Example B: "kpis": ["event_name"]
Yes

KPI format parameters set the format of the KPIs returned. 

Presentation of KPI functions

Parameter

Values Mandatory 

preferred_currency

KPI revenue currency

  • If true, revenue is returned using the app-specific currency set in the platform. 
  • [Default] If false, results return in USD.
  • Format: Boolean 
  • Platform UI version: true

 No

preferred_timezone

Time zone of data ranges

  • If true, times are expressed using the app-specific time zone set in the platform.
  • [Default] If false, times are expressed using UTC time zone.
  • Format: Boolean 
  • Platform UI version: true

 No

aggregation_type

  • cumulative
  • on_day

"aggregation_type": "cumulative"

Format: String

Yes

per_user

Divide the KPI function by the number of app users. Applies only to relevant KPIs.

  • If true, KPI values are divided by the number of users in the cohort.
  • If false, KPI values are not divided by the number of users.
  • Format: Boolean 
  • Example if true: total revenue is $1000, the number of app users is 500, the value returned is $2. 
 No

List of group by and filter by dimensions

Available grouping and filter dimensions

Dimension name 

Dimension API value

Groupings

Filters

Ad

af_ad

Ad ID

af_ad_id

Campaign

c

Campaign ID

af_c_id

Channel

af_channel

Media Source

pid

Sub Param 1

af_sub1

Keywords

af_keywords

Agency

af_prt

Conversion Type (1) 

cohort_type

Site ID

site_id

Revenue Type (2)

revenue_type

Attributed Touch Type (3)

attributed_touch_type

Adset

af_adset

Adset ID

af_adset_id

 

Country

geo

Date (install/re-attribution/re-engagement date in the context of the cohort_type selected) 

date

Period

period 

Detailed explanation

 

x

Notes: 

Dimension options:

(1) Conversion Type:  user_acquisitionretargetingunified

(2) Revenue Type: regular, ad_monetization

(3) Attributed Touch Type: click, impression, TV, pre-installed

Curl example

This example contains a complete API call.


curl -L -X POST 'https://hq1.appsflyer.com/api/cohorts/v1/data/app/<insert your app_id here>?format=<insert results format here>' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <cohort_api_token_placeholder. Note the token has more than 700 characters.>' \
-H 'Accept: application/json' \
--data-raw '{
    "cohort_type": "user_acquisition",
    "min_cohort_size": 1,
    "preferred_timezone": false,
    "from": "2020-01-01",
    "to": "2020-01-31",
    "filters": {
        "period": [
            0,
            1,
            2,
            10,
            30,
            60
        ],
        "geo": [
            "US",
            "CN"
        ],
        "pid": [
            "Facebook Ads",
            "gooleadwords_int"
        ]
    },
    "preferred_currency": true,
    "aggregation_type": "on_day",
    "per_user": false,    
    "groupings": [
        "pid",
        "date"
    ],
    "kpis": [
        "sessions"
    ]
}'
Example files returned: CSVJSON

Python example

import http.client
import mimetypes
conn = http.client.HTTPSConnection("hq1.appsflyer.com")
payload = "{\r\n    \"cohort_type\": \"user_acquisition\",\r\n    \"min_cohort_size\": 1,\r\n    \"preferred_timezone\": false,\r\n    \"from\": \"2020-05-01\",\r\n    \"to\": \"2020-05-10\",\r\n    \"preferred_currency\": true,\r\n    \"aggregation_type\": \"cumulative\",\r\n    \"per_user\": false,   \r\n     \"groupings\": [\r\n               \"pid\",\r\n         \"date\"\r\n        ],\r\n    \"kpis\": [\r\n        \"roas\"\r\n    ]\r\n}"
headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer [Enter token here]',
  'Accept': 'application/json',
  'Content-Type': 'application/json'
}
conn.request("POST", "/api/cohorts/v1/data/app/[My App ID here]?format=csv", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
   

Use case examples

Example 1: Retention

Media source retention (sessions)  of users who installed the app during January on day 7, 14, and 28 

{
  "per_user": false,
  "groupings": [
    "pid"
  ],
  "filters": {
    "period": [
      7, 14, 28
    ]
  },
  "partial_data": false,
  "aggregation_type": "on_day",
  "min_cohort_size": 1,
  "cohort_type": "user_acquisition",
  "from": "2021-01-01",
  "to": "2021-01-30",
  "kpis": [
    "sessions"
  ]
}

Example 2: Campaign purchases

Cohort day 3 post-install revenue per campaign

{  
  "per_user": false,
  "groupings": [
    "c"
  ],
  "filters": {
    "period": [
      3
    ],
    "c":[
        "example_campaign_name"
    ]
  },
  "partial_data": false,
  "aggregation_type": "cumulative",
  "min_cohort_size": 1,
  "cohort_type": "user_acquisition",
  "from": "2021-01-01",
  "to": "2021-01-30",
  "kpis": [
    "Checkout Start"
  ]
}

Example 3: Yesterdays activity
What activity did users who converted (installed, re-engaged, re-attributed)  during a given conversion period perform yesterday? 

Use data available via Cohort for Data Locker. The conversion period is limited to the previous 360 days. 

 

Additional information

Response codes and troubleshooting

Response codes

Response code 

Message

Remark 

200 OK

Valid data returned

200 OK
  • No data is returned
    • The query was valid, but no data was found matching the query. 
    • Check that the date range does not include future dates.
    • No token at all was sent in the call. 
401 Unauthorized
  • The authorization token is malformed check that you are using the correct token it should be more than 700 characters long
404 Not found
  • Eliminate any network, firewall, etc. related problems. 
  • Ensure that you are using the most recently issued token. Get the current token from the dashboard. 
  • Ensure that the App specified in the path is authorized to use Cohort API. Meaning it is part of the subscription plan. The AppsFlyer account admin can check this in My Plan. 
 422 Unprocessable entity

Common reasons for this error code are:

  • Ensure that the request is contained in a JSON and not sent as query parameters. 
  • Ensure that the JSON is formatted in accordance with this document.
  • Illegal date

CSV file name structure

The name allocated to a CSV file that returns is generated from the API query. The structure is as detailed in the table that follows.

Example CSV file name

cohort_aggregation_type_per_user_kpi_report_app_id_from_to_timezone_currency_hash.csv
CSV file name structure depends on the API query
Variable Possible values
aggregation_type
  • on_day
  • cumulative
per_user
  • per_user 
  • false: Null 
kpi Example: sessions
app_id The app id requested
from from date: format yyyy-mm-dd
to to date: format yyyy-mm-dd
timezone Time zone default UTC
currency Currency code default USD 
hash

Alphanumeric hash string length=5

Using period filters

Period refers to the day post-attribution, where period 0 is the attribution day. For example, a user installs the app on January 1. This is the attribution day. A purchase made on period 0 means it was made on January 1. A purchase made on period 3 means it was made on January 4. Similarly, a user who installs on January 11, this is period 0. A purchase made on January 14 would be period 3.

If your report date range is January 1 to January 11 users who attributed (installed) during this period are included in the report. No other data is included. 

  • The value of the period can be one or more of the following 0-180. For example, 0, 1, 2, 30, 180. 
  • If no period is specified, the default values of 0, 1, 2, and so on to 30, 60, 90, and 180 return.  

 Example period filter

  • This example contains the JSON query parameters, raw data, and resulting CSV file.
  • The query filters period of 0, 1, and 2 and the KPI selected is revenue.
  • As a result, the data returned contains:
    • The measures of users, cost, and ecpi which always return 
    • Revenue measures consisting of sum and count for each period meaning periods 0, 1, and 2. 

Query

{
    "cohort_type": "user_acquisition",
    "min_cohort_size": 1,
    "preferred_timezone": false,
    "from": "2019-12-01",
    "to": "2020-01-01",
    "filters": {
        "period": [
            0,
            1,
            2
        ]
    },
    "aggregation_type": "on_day",
    "per_user": false,
    "groupings": [
        "pid"
    ],
    "kpis": [
        "revenue"
    ]
}

Raw data

mceclip1.png

Results

mceclip0.png

User interface mapping to API parameters

The figures that follow map the Cohort analytics user interface to the API parameters. The two solutions - API and user interface are similar but not identical. 

The API version has the following additional options:

  • Currency selection
  • Timezone selection
  • Filtering by period
CohortMapping.jpg Cohortmapping2.jpg

Difference between aggregation types

CohortRevnueCumulative.jpg

Traits and limitations

Trait
Trait Remarks 
Ad network access 

No. Campaign management partners can use the API if the advertiser grants permission. 

Agency access No
Agency transparency Not supported
App-specific time zone Yes
App-specific currency  Yes
Size limitations None
Rate limitation

API call-rate limit: 60 calls per minute per account 

Organic data Available
Non-organic data Available
Cost data limitation
  • AppsFlyer does not report cost data for keywords that contain uppercase letters in the cohort report or cohort API
  • You can't combine some groupings combinations with cost. For example, Facebook can have either geo or channel groupings but not both. The exact combination of groupings is ad network dependant.
Data freshness

Data freshness depends on partial_data as follows: 

Historical data Earliest conversion data (install or retarget) supported: January 1, 2019
Team member access The authorization token is available to the account admin in the dashboard
Was this article helpful?