Introduction
Analytics metrics help partners and advertisers understand the performance of the content they promote on X. This includes information such as impressions, clicks, video views, and spend. In addition, partners and advertisers are able to get detailed metrics for various segments of the audiences they reach. The Ads API supports two ways of retrieving detailed campaign performance metrics: synchronously and asynchronously. With synchronous analytics calls, the requested metrics are returned in the response. With the asynchronous analytics endpoints, the requested metrics are available in a downloadable results file after the associated “job” has finished processing. The synchronous endpoint supports short time ranges and is ideal for real-time campaign optimizations. The asynchronous endpoints support much longer time ranges and are, thus, intended for fetching much more data, ideal for generating reporting or historical backfills.Details
Synchronous vs. Asynchronous
The differences between the synchronous and asynchronous analytics endpoints are summarized in the following table. This information is intended to help developers choose which set of endpoints to use.* This refers to the maximum number of jobs that may be in a processing state at any given time.** Once the job has successfully finished processing, a URL is returned. This is where the compressed (gzip) results file can be downloaded from.Outside of this, the endpoints offer the same functionality.
Use cases
There are three major analytics use cases.- Real-time optimization: using performance metrics to update active campaigns
- Synchronization: regularly-scheduled background syncs
- New account on-boarding: backfilling historical data
Request Options
Analytics requests are scoped to ads accounts and, thus, require the account ID in the resource path. Request options, listed below, are specified as query parameters. The following types of values are required.- Entities: the entity type as well as up to 20 entity IDs you’d like to request analytics for
- Time range: the start and end times, expressed in ISO 8601
- Note: must be expressed in whole hours
- Metric groups: one or more sets of related metrics (see Metrics and Segmentation for a list of metrics within each metric group)
- Granularity: specifies the level of aggregation in which the metrics should be returned
- Placement: determines whether metrics are pulled for ads that served on or off of X
- Note: only a single placement value can be specified per request
start_time and end_time request parameters to specify a time range. These values must be aligned with the specified granularity in the following way.
TOTAL: specify any time range (within the endpoint’s limits)DAY: both the start time and end time values must be aligned with midnight in the account’s time zoneHOUR: specify any time range (within the endpoint’s limits)
start_time=2019-01-01T00:00:00Z and end_time=2019-01-02T00:00:00Z will return a single day’s worth of analytics metrics (not two) as this time range covers only a 24 hour period.
Segmentation
Available only through our asynchronous analytics endpoints, segmentation allows partners and advertisers to retrieve metrics broken out particular targeting values. To request segmented metrics, use the segmentation_type request parameter. For more details on segmentation options, see Metrics and Segmentation.
FAQs
Why don’t the Ads API numbers match what’s shown in the X Ads UI?- Make sure you’ve requested data for both placements:
ALL_ON_TWITTERandPUBLISHER_NETWORK,SPOTLIGHT, andTREND. - Remember that end times in the Ads API are exclusive; they are inclusive in the Ads UI
- As soon as reporting metrics are available, you are able to retrieve them. They are available in near real-time. These early results are estimates, though, and, as a result, are expected to change. Metrics are finalized after 24 hours, with the exception of spend data.
- Spend metrics are generally final within 3 days of the event. However, we process billing data for up to 14 days from the date of the event (for spam filtering, for example).
- Use the Active Entities endpoint
null?
- It’s likely that the campaign did not serve during the requested time period
- Use the Active Entities endpoint to determine which entities to fetch analytics for and for what time period
null values while the UI shows 0s?
- The UI chooses to display these values as 0s, but the values are equivalent
- We support the following placement values in analytics:
ALL_ON_TWITTERandPUBLISHER_NETWORK,SPOTLIGHT, andTREND(i.e., the X Audience Platform)
- Yes. The entity’s status does not impact the availability of analytics metrics.
- Segmented data is not expected to roll-up 100% to the non-segmented data, due to how this information is derived.
- We do not support multi-segmentation.
Best Practices
Some best practices when collecting analytics data from the Ads API.Rate Limiting and Retries
- On queries that are rate limited (those that return an
HTTP 429status code), you must inspect thex-rate-limit-resetheader and retry only at or after the time indicated. - On queries that result in an HTTP 503 Service Unavailable status code, you must inspect the
retry-afterheader and retry only after the time indicated. - Applications that do not respect the times indicated for retries could have their access to the Ads API revoked or throttled without notice.
Analytics Metrics In a Nutshell
- All analytics metrics are locked and will not change after 24 hours, with the exception of
billed_charge_local_micro. - The
billed_charge_local_micrometric is an estimate for up to 3 days after the data is returned. - After 24 hours, this metric can decrease due to credits for overspend (ads served after the given
end_time) and for billable events that are determined to be junk. This metric changes minimally after 24 hours. - Please see Analytics for more information.
Fetching Real-time, Non-segmented Data
- Always provide both a
start_timeand anend_time. - Do not pull data for any entities older than 7 days.
- Do request data (ideally) with
HOURgranularity, as you can always aggregate and roll metrics up to getDAYandTOTALgranularity. - Do request data (ideally) at the
line_itemsandpromoted_tweetslevel, as you can always aggregate and roll these metrics up to get totals across the entire ads entity hierarchy (i.e. for the campaign, funding instrument or account levels). - Save and store the values of analytics metrics on your side (locally).
- Do not repeatedly query for data that is older than 30 days. This data will not change and should be stored locally.
- All non-segmented data is real-time and data should be available within seconds of an event occurring.
- Group conversion metrics and non-conversion metrics into separate requests.
Fetching Segmented Data
- Refer to guidelines provided for “Fetching Real-time, Non-segmented Data” above. Additional advice provided below.
- For most segmented data types, it is possible for data to not be complete for up to 1 hour at times. Data segmented by
INTERESTScan be delayed for up to 12 hours. - Segmented data is not expected to roll-up 100% to the non-segmented data, due to how this information is derived.
Fetching Historical Data
- When backfilling data (i.e. adding a new advertiser account), you may need make several requests in smaller
start_timeandend_timechunks. - Limit your fetches to 30-day date windows.
- Throttle these requests and distribute over time so as not to exhaust your rate limits for these fetches.
Sample
You can find a sample script demonstrating some of these best practices (fetch_stats) on our ads-platform-tools github repository.
Metrics by Objective
Which metrics are applicable for an entity depends on the campaign objective. Use this guide to determine the relevant metric groups to fetch for each objective type, as well as how additional derived metrics can be calculated.ENGAGEMENTS
Relevant metric groups:ENGAGEMENT and BILLING. MEDIA is also applicable if media is used in creatives.
WEBSITE_CLICKS and WEBSITE_CONVERSIONS
Relevant metric groups:ENGAGEMENT, BILLING, and WEB_CONVERSION. MEDIA is also applicable if media is used in creatives.
APP_INSTALLS and APP_ENGAGEMENTS
Relevant metric groups:ENGAGEMENT, BILLING, MOBILE_CONVERSION, and LIFE_TIME_VALUE_MOBILE_CONVERSION. MEDIA and VIDEO are also applicable if media or video app card is used in creatives.
FOLLOWERS
Relevant metric groups:ENGAGEMENT and BILLING. MEDIA is also applicable if media is used in creatives.
LEAD_GENERATION
Relevant metric groups:ENGAGEMENT and BILLING. MEDIA is also applicable if media is used in creatives.
VIDEO_VIEWS
Relevant metric groups:ENGAGEMENT, BILLING, and VIDEO.
VIDEO_VIEWS_PREROLL
Relevant metric groups:ENGAGEMENT, BILLING, and VIDEO.
Metrics and Segmentation
This document is an overview of the metrics available from our Analytics for each entity type, as well as the available segmentation for each metrics.
*Some metrics in the
ENGAGEMENT metrics family are not available at the account and funding instrument level. See the ENGAGEMENT section for details.
Available Metrics by Metrics Group
ENGAGEMENT
BILLING
VIDEO
Notice about video metrics definition changes:
The video_total_views metric within the VIDEO metrics group will report on any views which are at least 50% in-view for 2 seconds, as per the MRC standard.
Our original video view definition of 100% in view for at least 3 seconds will continue to be available as a new video_3s100pct_views metric in the VIDEO metrics group. To continue to bid and be charged based on the original view definition, use the newly available VIEW_3S_100PCT bid_unit.
MEDIA
WEB_CONVERSION
MOBILE_CONVERSION
Mobile conversion stats are available only to advertiser accounts enabled for MACT.
LIFE_TIME_VALUE_MOBILE_CONVERSION
Lifetime mobile conversion stats are available only to advertiser accounts enabled for MACT.
Segmentation
Segmentation reporting allows the retrieval of metrics broken out by the values of a given targeting type. Segmentation is only available through asynchronous analytics queries due to their significant added complexity. Segmentation not supported forMEDIA_CREATIVE or ORGANIC_TWEET entities.
Some segmentation types require additional parameters to be passed in. These are documented below.
When segmenting by CITIES or POSTAL_CODES, the API will only returned targeted locations. Region and metro segmentation will return both targeted and non-targeted locations.
Derived Metrics
Campaign metrics depend on their campaign objective. Use this guide to determine how to calculcate derived metrics for use based on the objectives in place. Anymetric without curly brackets is one that is returned by the Ads API analytics endpoints. Any name surrounded by {curley brackets} indicates a derived metric for that category.
ENGAGEMENTS
WEBSITE_CLICKS
APP_INSTALLS and APP_ENGAGEMENTS
FOLLOWERS
LEAD_GENERATION
VIDEO_VIEWS
QUALIFIED_IMPRESSIONS
CUSTOM
Forplacement_type of PROMOTED_ACCOUNT see the FOLLOWERS objective above. For all other placements with this objective, see ENGAGEMENTS for the corresponding derived metrics.
Guides
Active Entities
Introduction
The Active Entities endpoint is designed to be used in conjunction with our synchronous and asynchronous analytics endpoints as it provides information about which campaigns to request analytics for. It does this by returning details about ads entities and when their metrics changed. Using this endpoint will greatly simplify your code and analytics fetching logic. This guide includes information and context about the endpoint and its data source. It also provides usage guidelines and a series of example requests, demonstrating how to use Active Entities in conjunction with our analytics endpoints. The Summary section provides a high-level description of the recommended approach.Data
Whenever an ads entity metric changes, we record information about that change. These change events are stored in hourly buckets and include details about the entity as well as the time that the change applies to. The latter is necessary because change events do not always correspond to when they were recorded. Billing adjustments are a common reason for this, but there are others, too.Endpoint
Request
Active Entities requests are scoped under ads accounts and have three required query parameters:entity, start_time, and end_time.
twurl -H ads-api.x.com "/11/stats/accounts/18ce54d4x5t/active_entities?entity=PROMOTED_TWEET&start_time=2019-03-05T00:00:00Z&end_time=2019-03-06T00:00:00Z"
The following entity values are supported: CAMPAIGN, FUNDING_INSTRUMENT, LINE_ITEM, MEDIA_CREATIVE, PROMOTED_ACCOUNT, and PROMOTED_TWEET. This reflects the entity types that our analytics endpoints support.
The start_time and end_time values must be expressed in ISO 8601 and specify which hourly buckets to query. These must be expressed in whole hours.
This endpoint also supports three optional parameters that can be used to filter results: funding_instrument_ids, campaign_ids, and line_item_ids. These work at all levels of the ads hierarchy and with any specified entity type.
Response
The Active Entities response for the request above is shown below.data array includes an object for every entity that should be included in a subsequent analytics request. You should not request analytics for IDs outside of this set.
Each object includes four fields: entity_id, activity_start_time, activity_end_time, and placements. The activity start and end times represent the time range that the associated entity’s change events apply to and, thus, determine the dates that should be specified in subsequent analytics requests. The placements array can include the following values: ALL_ON_TWITTER, PUBLISHER_NETWORK, SPOTLIGHT, and TREND. It indicates which placements should be requested for the given entity ID.
Usage
The Active Entities endpoint should dictate how analytics requests are made. The following usage guidelines are written to support analytics synchronization, enabling partners to keep their data stores in sync with Twitter. In other words, it describes how to perform regularly-scheduled background syncs. There are two decisions a developer must make.- How often to request active entities information and, thus, how often to pull analytics.
- How to use the activity start and end times to determine the analytics request’s
start_timeandend_timevalues.
Summary
Use the Active Entities endpoint in the following way to dictate how analytics requests are made. Follow this after you’ve decided how often to request active entities information and, thus, how often to pull analytics.- Make the Active Entities request.
- Split the response by placement. One group for
ALL_ON_TWITTER, one forPUBLISHER_NETWORK, one forSPOTLIGHT, and one forTREND. - For each placement group, do the following.
- Extract the entity IDs.
- Determine the analytics
start_timeandend_timevalues.- Find the minimum
activity_start_time. Round this value down. - Find the maximum
activity_end_time. Round this value up.
- Find the minimum
- Make the analytics request(s).
- Group entity IDs into batches of 20.
- Use the
start_timeandend_timevalues from #3b. - Specify the appropriate
placementvalue.
- Write to your data store.
Frequency
The answer to the first question determines the time range that should be used in Active Entities requests. For example, if requesting active entities information every hour, the time range should be an hour. If requesting active entities information once a day, the time range should be a day. In other words, time ranges should be selected such that the current request’sstart_time is equal to the previous request’s end_time.
Note: A time window should only be requested once. Requesting a time window more than once will lead to unnecessary analytics requests. (Exception below.)
Given the way that change events are stored, all four Active Entities requests above query the same hourly bucket, which is necessary for this use case. However, after the current hour, this hourly bucket should no longer be queried.
Activity Times
We recommend the following approach to working with activity start and end times. Across all objects in the Active Entities response, find the minimumactivity_start_time and the maximum activity_end_time. Modify these values by rounding the minimum activity start time down and rounding the maximum activity end time up. Specifically, set the timestamps to zero for both and add one day to the end time, as illustrated in the following table. These are the start and end times that should be specified in subsequent analytics requests.
Note: It’s important to include the timestamps with hours, minutes, and seconds set to zero. Otherwise, if only the date is passed in, we will assume you’re requesting analytics starting and ending at midnight in the ads account’s timezone, which may not be desirable. For example, if the minimum activity start time is 2019-02-28T01:30:07Z and the timestamp is omitted for an ads account with an offset of -08:00:00, the analytics request will miss changes that happened between 01:30 and 08:00.
Alternatively, if you would prefer to request analytics for just the returned activity time window without expanding to full days, you can. Using this approach, the derived start and end times would be 2019-03-04T20:00:00Z and 2019-03-05T15:00:00Z, respectively. (Note that ranges like these are not accepted if you specify
DAY granularity in the analytics request.)
Example
This section demonstrates how to use Active Entities in conjunction with the synchronous analytics endpoint. (The responses have been slightly modified for readability.) In this example, the Active Entities endpoint is called at the top of each hour, with each request looking at the previous hour. The response determines how the synchronous analytics endpoint is used. The first Active Entities request is made at 03:00:00. The response indicates that line item dvcz7’s metrics changed and that those change events apply to the window between 02:02:55 and 02:28:12.start_time and end_time values are set to 2019-02-11T00:00:00Z and 2019-02-12T00:00:00Z, respectively. We see that the third element in each of the metrics arrays below are non-zero, as we expected based on the active entities information.
Asynchronous Guide
API Reference
Asynchronous Analytics
Introduction
The asynchronous analytics endpoints allow partners and advertisers to request metrics by submitting create requests that the server processes asynchronously. (We refer to these as asynchronous analytics “jobs.”) With this approach, the client’s connection does not need to remain open until the request has been fulfilled. These endpoints, like their synchronous counterpart, allow partners and advertisers to request detailed statistics on campaign performance. They support requesting data for accounts, funding instruments, campaigns, line items, promoted Tweets, and media creatives. The difference between these and the synchronous endpoint is that the asynchronous analytics endpoints support longer date ranges, up to 90 days, as well as segmentation. Additional details on the differences between the two can be found on our Analytics Overview page. Unlike our synchronous endpoints, rate limiting is based on the number of concurrent jobs for a given account. In other words, it’s based on the number of jobs that can be in a processing state at a given time. We count this at the ads account level.Usage
Retrieving campaign metrics using the asynchronous analytics endpoints is a multi-step process. It involves creating a job, checking whether the job has finished processing, and, finally, downloading the data. The data file must be decompressed. The four specific steps are outlined below.- Create the job using the POST stats/jobs/accounts/:account_id endpoint.
- Make requests at regular intervals to the GET stats/jobs/accounts/:account_id endpoint to determine whether the job has finished processing.
- Once the job has finished processing, download the data file.
- Unzip the data file.
segmentation_type request parameter when creating the job.
Example
This section demonstrates how to use the asynchronous analytics endpoints. Start by creating a job using the POST stats/jobs/accounts/:account_id endpoint. The example below requests engagement metrics—such as impressions, likes, clicks, etc.—for a specific line item over a week’s time. (Note that the requested time range goes up to, but does not include March 20th since the timestamp is set to midnight.)id and id_str response attributes.
Next, you’ll want to check whether the job you’ve created using the id_str from the previous response, has finished processing as indicated by "status": "SUCCESS" in the response. This means the data is ready to download. The url field contains the download link.
job_ids parameter to check on the status of multiple jobs at a time by specifying up to 200 job IDs.
Next, download the data file using the listed url value.
Reach and Average Frequency
GET stats/accounts/:account_id/reach/campaigns
Retrieve reach and average frequency analytics for specified campaigns.Resource URL
https://ads-api.x.com/stats/accounts/:account_id/reach/campaigns
Parameters
Example Request
GET https://ads-api.x.com/12/stats/accounts/18ce54d4x5t/reach/campaigns?campaign_ids=8fgzf&start_time=2017-05-19&end_time=2017-05-26
Example Response
GET stats/accounts/:account_id/reach/funding_instruments
Retrieve reach and average frequency analytics for specified funding instruments.Resource URL
https://ads-api.x.com/stats/accounts/:account_id/reach/funding_instruments
Parameters
Example Request
Example Response
Synchronous Analytics
GET stats/accounts/:account_id
Retrieve synchronous analytics for the current account. A maximum time range (end_time - start_time) of 7 days is allowed.
Resource URL
https://ads-api.x.com/12/stats/accounts/:account_id
Parameters
Example Request
Example Response
Active Entities
GET stats/accounts/:account_id/active_entities
Retrieve details about which entities’ analytics metrics have changed in a given time period. This endpoint should be used in conjunction with our analytics endpoints. The results of this endpoint indicate which ads entities to request analytics for. See our Active Entities Guide for usage guidelines. Change events are available in hourly buckets.- The
start_timeandend_timevalues specify which hourly buckets to query. - The returned
dataarray will include an object for every entity that should be included in subsequent analytics requests. - IMPORTANT: The dates that should be specified in subsequent analytics requests should be determined based on the
activity_start_timeandactivity_end_timevalues.- These values represent the time ranges that the stored change events apply to. This is returned per entity.
end_time - start_time) of 90 days is allowed.
Resource URL
https://ads-api.x.com/12/stats/accounts/:account_id/active_entities
Parameters
Example Request
GET https://ads-api.x.com/12/stats/accounts/18ce54d4x5t/active_entities?entity=PROMOTED_TWEET&start_time=2019-02-28&end_time=2019-03-01