---
updatedAt: 2025-05-29T21:41:16.000Z
agentTools:
  projectIndex: https://developers.apptweak.com/llms.txt
---

# App Metrics Extract

```python Python
"""
Recipe : App Metrics Extract

The way this recipe works:
  1. You provide the list of apps for which you would like to have the metrics and rankings
  2. Output a csv breakdown of the data.
"""

### ------------------ Your job ------------------ ###

# Fill the different parameters between the double quotes

# Set your API token (mandatory if you want to run the recipe :D)
API_KEY = ""

# Set the device (device options : "iphone", "ipad" or "android")
# Default : "iphone"
DEVICE = ""

# Give the list of app ids here separated by a comma
# Warning: do not mix Android and iOS ids as that
#          will cause the request to fail.
# Default for ios (iphone/ipad) : "1436140272,1199780189,1440301673"
# Default for android : "com.tier.app,com.limebike,com.ridedott.rider"
#         ("TIER Electric scooters", "Lime - RideGreen" and "Dott - Unlock your city")
APPS = ""

# Give here the list of metrics you want separated by a comma
# Available metrics : "downloads", "app-power","revenues", "ratings"
# Default : "downloads,app-power,ratings"
METRICS = ""

# Give the list of countries code here separated by a comma
# You can find the list of all the country codes supported
# here : https://developers.apptweak.com/reference/country-codes
# Default : "de,fr,it,gb"
COUNTRIES = ""

# Give the start date to get the downloads
# Default : One week ago on ISO 8601 format
#             (Eg 2022-01-21)
START_DATE = ""

# Give the end_date to get the downloads
# Default : Today on ISO 8601 format
#             (Eg 2022-01-28)
END_DATE = ""

# ONLY FOR GOOGLE CLOUD INTEGRATION
FOR_GOOGLE_CLOUD = False # If running on google cloud set this to True
GOOGLE_CLOUD_PROJECT_NAME = ""

# For more information about the endpoint parameters and options visit:
# https://developers.apptweak.com/reference/app-keyword-ranking-history

### ---- End of your job, just run and enjoy ! ---- ###

### -------------- ENTER MAGIC AREA --------------- ###
# Keep scrolling only if you are already an experienced wizard !

DEBUG_MODE = False

import warnings

if not DEBUG_MODE:
  warnings.filterwarnings("ignore")

import os
import numpy as np
from cgi import print_exception
from typing import Dict
from datetime import datetime
from dateutil import relativedelta
import requests
import pandas as pd
import traceback
# ------ Exceptions creation -------

class ParameterValidationError(Exception):
  BASE_MESSAGE = "Parameter validation error"
  def __init__(self, parameter: str, value: str, message: str):
    self.parameter = parameter
    self.value = value
    self.message = f"{self.BASE_MESSAGE} :\n{self.parameter} : {self.value}\n{message}"
    super().__init__(self.message)

class ApiParameterValidationError(ParameterValidationError):
  def __init__(self, api_value: str):
    super().__init__("API", api_value, "Missing API token")

class DeviceParameterValidationError(ParameterValidationError):
  def __init__(self, device_value: str, allowed_devices: str):
    super().__init__("Device", device_value, f"Device not in allowed devices list {allowed_devices}")

class AppsFormatParameterValidationError(ParameterValidationError):
  def __init__(self, device: str, value: str, message: str):
    self.device = device
    super().__init__(f"Apps format for {self.device}", value, message)

class AppsFormatAndroidParameterValidationError(AppsFormatParameterValidationError):
  def __init__(self, value: str, wrong_app: str, wrong_character: str, idx_wrong_character: str):
    super().__init__("android", value, f"Android can't contain numbers (found app \"{wrong_app}\" with \"{wrong_character}\" at index {idx_wrong_character})")

class AppsFormatIosParameterValidationError(AppsFormatParameterValidationError):
  def __init__(self, value: str, wrong_app: str, wrong_character: str, idx_wrong_character: str):
    super().__init__("ios", value, f"iOS can only contain numbers (found for app \"{wrong_app}\" with \"{wrong_character}\" at index {idx_wrong_character})")

class StartDateParameterValidationError(ParameterValidationError):
  def __init__(self, start_date: str):
    super().__init__("start_date", start_date, "Format of start date not following YYYY-MM-DD")

class EndDateParameterValidationError(ParameterValidationError):
  def __init__(self, end_date: str):
    super().__init__("end_date", end_date, "Format of end date not following YYYY-MM-DD")

class EndDateBeforeStartDateParameterValidationError(ParameterValidationError):
  def __init__(self, start_date: str, end_date: str):
    super().__init__("end_date < start_date", f"Start date : {start_date}\n End date : {end_date}", "Start date needs to be before end date")

class GoogleCloudParameterValidationError(ParameterValidationError):
  def __init__(self):
    super().__init__("env_var", "google cloud project name", "Google cloud project name is empty!")

class ApiRuntimeError(Exception):
  BASE_MESSAGE = "Error calling PublicAPI"
  def __init__(self, reason: str):
    self.reason = reason
    self.message = f"{self.BASE_MESSAGE} :\n{self.reason}"
    super().__init__(self.message)

class MetricsParameterValidationError(ParameterValidationError):
  def __init__(self, metrics: str, allowed_metrics: str):
    super().__init__("metrics", metrics, f"Metric not in allowed metrics list {allowed_metrics}")

class NotEnoughCreditsError(ApiRuntimeError):
  def __init__(self):
    super().__init__("Account with the associated API Token has ran out of credits")

class WrongAPIToken(ApiRuntimeError):
  def __init__(self):
    super().__init__("The API token provided is not correct")

# If a param validation fails on the API side.
# An example could be wrong country/language combination
class RuntimeParameterValidationError(ApiRuntimeError):
  def __init__(self, reason: str, parameter: str):
    super().__init__(f"Parameter {parameter} validation failed: {reason}")

# 500s will be caught here
class InternalError(ApiRuntimeError):
  def __init__(self):
    super().__init__(f"Something went terribly wrong in the internals of the API")

# ------ End exceptions ------

# ----- Utils -------

class Utils:
  @staticmethod
  def batch(iterable, batch_size = 1):
    length = len(iterable)
    for i in range(0, length, batch_size):
      yield iterable[i: min(i + batch_size, length)]

  @staticmethod
  def unique(array):
    return list(set(array))

# ---- End utils ------

class AppMetricsExtract:
  def __init__(self) -> None:
    self.API_KEY = {"x-apptweak-key": API_KEY}
    self.APP_METRICS_HISTORY_ENDPOINT = "https://public-api.apptweak.com/api/public/store/apps/metrics/history.json"
    self.APP_CATEGORY_RANKINGS_HISTORY_ENDPOINT = "https://public-api.apptweak.com/api/public/store/apps/category-rankings/history.json"

    self.DEVICE = DEVICE

    self.APPS = Utils.unique(APPS.split(","))
    self.APPS_STRING = ",".join(self.APPS)

    self.METRICS = Utils.unique(METRICS.split(","))
    self.METRICS_STRING = ",".join(self.METRICS)

    self.COUNTRIES = Utils.unique(COUNTRIES.split(","))
    self.COUNTRIES_STRING = ",".join(self.COUNTRIES)

    self.START_DATE = START_DATE
    self.END_DATE = END_DATE

    self.GOOGLE_CLOUD_PROJECT_NAME = GOOGLE_CLOUD_PROJECT_NAME

    self.credit_cost = 0
    self.data = pd.DataFrame()

    self.print_config()

  # Function that prints the current configuration
  def print_config(self) -> None:
    print()
    print("#----- Configuration of the recipe ----#")
    print(f"API_KEY : **************** (FILTERED)")
    print(f"DEVICE : {self.DEVICE}")
    print(f"APPS : {self.APPS_STRING}")
    print(f"METRICS : {self.METRICS_STRING}")
    print(f"COUNTRIES : {self.COUNTRIES_STRING}")
    print(f"START_DATE : {self.START_DATE}")
    print(f"END_DATE : {self.END_DATE}")
    print("#---------- End configuration ---------#")
    print()

  # Function to get data from the API
  def get_url(_self, url: str, at_key: Dict) -> Dict:
    response = requests.get(url, headers=at_key)

    # API error checking
    if response.status_code == 500:
      raise InternalError()
    elif response.status_code == 422:
      parameter = response.json()["error"]["parameter"]
      reason = response.json()["error"]["reason"]
      raise RuntimeParameterValidationError(reason, parameter)
    elif response.status_code == 403:
      raise NotEnoughCreditsError()
    elif response.status_code == 401:
      raise WrongAPIToken()

    resp_dict = response.json()
    return resp_dict

  # The name of the CSV is app_metrics_extract_report_XXXXXX
  # where XXXX is the current timestamp
  def export_to_csv(self):
    if self.data.empty:
      return

    """"Writes the data to a csv"""
    current_time = datetime.now().strftime("%Y-%m-%d-%H.%M.%S")
    self.data.reset_index(drop=True, inplace=True)
    self.data.index.name = "index"
    output_filename = f"app_metrics_extract_report_{current_time}.csv"
    self.data.to_csv(output_filename)
    return output_filename

  # The name of the CSV is app_metrics_extract_report_XXXXXX
  # where XXXX is the current timestamp
  def export_to_big_query(self):
    if self.data.empty:
      return

    """"Writes the data to big query"""
    dataset_name = 'app_metrics'
    table_name = "apptweak_app_metrics_data"

    # Work around int64 not being able to be saved
    blankIndex=[''] * len(self.data)
    self.data.index = blankIndex
    for metric in self.METRICS:
      self.data[metric] = self.data[metric].replace({None: np.nan})
    self.data.to_gbq(destination_table=f"{dataset_name}.{table_name}", project_id=self.GOOGLE_CLOUD_PROJECT_NAME, if_exists='replace')
    return f"{dataset_name}.{table_name}"

  # Gets app metrics for the specific apps by country
  def get_app_metrics(self, apps: str, country: str):
    query = f"?apps={apps}&metrics={self.METRICS_STRING}&country={country}&device={self.DEVICE}&start_date={self.START_DATE}&end_date={self.END_DATE}"
    url = self.APP_METRICS_HISTORY_ENDPOINT + query

    resp_dict = self.get_url(url, self.API_KEY)

    self.credit_cost += resp_dict["metadata"]["request"]["cost"]
    print(f"App Metrics Extract - The current credit cost is: {self.credit_cost}")

    return resp_dict

  # Gets app category rankings for the specific apps by country
  def get_app_category_rankings(self, apps: str, country: str):
    query = f"?apps={apps}&country={country}&device={self.DEVICE}&start_date={self.START_DATE}&end_date={self.END_DATE}"
    url = self.APP_CATEGORY_RANKINGS_HISTORY_ENDPOINT + query

    resp_dict = self.get_url(url, self.API_KEY)

    self.credit_cost += resp_dict["metadata"]["request"]["cost"]
    print(f"App Metrics Extract - The current credit cost is: {self.credit_cost}")

    return resp_dict

  def fetch_data(self):
    start_date = datetime.strptime(self.START_DATE, "%Y-%m-%d")
    end_date = datetime.strptime(self.END_DATE, "%Y-%m-%d")
    date_range = [(start_date + relativedelta.relativedelta(days=i)).strftime("%Y-%m-%d") for i in range((end_date - start_date).days + 1)]

    for country in self.COUNTRIES:
      for apps in Utils.batch(self.APPS, 5):
        print (f" ------ Starting fetch for {country} - {apps} ------- ")
        try :
          apps_metrics = (
            self.get_app_metrics(",".join(apps), country)
                .get("result")
          )
          apps_category_rankings = (
            self.get_app_category_rankings(",".join(apps), country)
                .get("result")
          )
          for app in apps:
            app_metrics = apps_metrics.get(app)
            app_category_rankings = apps_category_rankings.get(app).get("rankings")
            for date in date_range:
              metrics_data = []
              for metric in self.METRICS:
                try:
                  datapoint = next(elem for elem in app_metrics.get(metric) if elem.get("date") == date)
                  if metric == "daily-ratings" or metric == "ratings":
                    breakdown = datapoint.get("breakdown")
                    if breakdown == None:
                      if metric == "daily-ratings" or metric == "ratings":
                        metrics_data += [0 for _ in range(7)]
                      else:
                        metrics_data.append(0)
                      continue
                    del breakdown["avg"]
                    breakdown_values = list(breakdown.values())
                    metrics_data += breakdown_values + [datapoint.get("value")]
                  else:
                    metrics_data.append(datapoint.get("value"))
                except StopIteration as e:
                  if metric == "daily-ratings" or metric == "ratings":
                    metrics_data += [0 for _ in range(7)]
                  else:
                    metrics_data.append(0)
              try:
                rank = next(e for e in next(elem for elem in app_category_rankings if elem.get("date") == date).get("value") if e.get("category") == "0" or e.get("category") == "ALL").get("rank")
                if rank == None:
                  rank = 0
              except StopIteration as e:
                rank = 0
              yield(country, app, date, *metrics_data, rank)
        except ApiRuntimeError as e:
          print(f"An error occurred while getting the data from the api")
          print(f"Error: {e.reason}")
          raise e
        except Exception as e:
          print(f"No data for apps {apps}")
          raise e
        except:
          print(f"No data for {country} - {apps}")
          continue

  def get_metrics_columns(self):
    metrics_columns = []
    for metric in self.METRICS:
      if metric == "ratings" or metric == "daily-ratings":
        metrics_columns += [f"{metric}-{str(i)}" for i in range(1, 6)] + [f"{metric}-total", f"{metric}-value"]
      else:
        metrics_columns.append(metric)
    return metrics_columns

  def fetch_and_parse_data(self):
    metrics_columns = self.get_metrics_columns()
    for _i, data in enumerate(self.fetch_data()):
      row_data = pd.DataFrame([list(data)], columns=["country", "app", "date"] + metrics_columns + ["rank-all-categories"])
      self.data = pd.concat([self.data, row_data], ignore_index=True)

def fill_default_parameters():
  global API_KEY, DEVICE, APPS, METRICS, COUNTRIES, START_DATE, END_DATE, GOOGLE_CLOUD_PROJECT_NAME
  if API_KEY == "":
    API_KEY = os.environ.get('APPTWEAK-API-KEY', "")

  # DEVICE
  if DEVICE == "":
    DEVICE = "iphone"

  # APPS
  if APPS == "":
    if DEVICE == "android":
      APPS = "com.tier.app,com.limebike,com.ridedott.rider"
    else:
      APPS = "1436140272,1199780189,1440301673"

  # METRICS
  if METRICS == "":
    METRICS = "downloads,app-power,ratings"

  # COUNTRIES
  if COUNTRIES == "":
    COUNTRIES = "de,fr,it,gb"

  # START_DATE
  if START_DATE == "":
    START_DATE = (datetime.now() - relativedelta.relativedelta(days=8)).strftime("%Y-%m-%d")

  # END_DATE
  if END_DATE == "":
    END_DATE = (datetime.now() - relativedelta.relativedelta(days=1)).strftime("%Y-%m-%d")

  if GOOGLE_CLOUD_PROJECT_NAME == "":
    # Default name in the guide
    GOOGLE_CLOUD_PROJECT_NAME = os.environ.get('GOOGLE-CLOUD-PROJECT-ID', "")

#  --- Parameters validation ---

def parameters_validation():
  global API_KEY, DEVICE, APPS, TERMS, COUNTRIES, START_DATE, END_DATE
  # API_KEY
  if API_KEY == "":
    raise ApiParameterValidationError(API_KEY)

  # DEVICE
  ALLOWED_DEVICES = ["iphone", "ipad", "android"]
  ALLOWED_DEVICES_STRING = ",".join(ALLOWED_DEVICES)
  if DEVICE not in ALLOWED_DEVICES:
    raise DeviceParameterValidationError(DEVICE, ALLOWED_DEVICES_STRING)

  # APPS
  apps_list = APPS.split(",")
  if DEVICE == "android":
    for app in apps_list:
      for c in app:
        if c.isdigit() and c != ",":
          raise AppsFormatAndroidParameterValidationError(APPS, app, c)
  else:
    for app in apps_list:
      for c in app:
        if not c.isdigit() and c != ",":
          raise AppsFormatIosParameterValidationError(APPS, app, c)

  # START_DATE
  try:
    datetime.strptime(START_DATE, '%Y-%m-%d')
  except:
    raise StartDateParameterValidationError(START_DATE)

  # END_DATE
  try:
    datetime.strptime(END_DATE, '%Y-%m-%d')
  except:
    raise EndDateParameterValidationError(END_DATE)

  # START_DATE < END_DATE
  START_DATE_DATE = datetime.strptime(START_DATE, "%Y-%m-%d")
  END_DATE_DATE = datetime.strptime(END_DATE, "%Y-%m-%d")
  if END_DATE_DATE < START_DATE_DATE:
    raise EndDateBeforeStartDateParameterValidationError(START_DATE, END_DATE)

  # METRICS
  ALLOWED_METRICS = ["downloads", "revenues", "ratings", "daily-ratings", "app-power"]
  ALLOWED_METRICS_STRING = ",".join(ALLOWED_METRICS)
  METRICS_LIST = METRICS.split(",")
  for metric in METRICS_LIST:
    if metric not in ALLOWED_METRICS:
      raise MetricsParameterValidationError(METRICS, ALLOWED_METRICS_STRING)

  # GOOGLE PROJECT ID
  if FOR_GOOGLE_CLOUD and GOOGLE_CLOUD_PROJECT_NAME == "":
    raise GoogleCloudParameterValidationError()

def print_need_help():
  print()
  print("######################################")
  print("Any problem? Contact us : squad_api@apptweak.com")
  print("--------------------------------------")

def print_exception(e: Exception):
  print("For more experienced wizards, here is the error:")
  print()
  message_attr = getattr(e, "message", None)
  if callable(message_attr) and e.message != "":
    print(e.message)
  else:
    print(repr(e))
  print(traceback.format_exc())
  print("######################################")

def print_successful_execution(output_file_name):
  print()
  print("######################################")
  print()
  print("SUCCESSFUL EXECUTION :)")
  print()
  if output_file_name == None:
    print("No data with the requested parameters so no file was generated")
  else:
    print(f"Generated file is named {output_file_name}")
  print()
  print("######################################")

if FOR_GOOGLE_CLOUD:
  import functions_framework
  @functions_framework.cloud_event
  def consume_event(_cloud_event):
    try:
      fill_default_parameters()
      parameters_validation()
      recipe_parser = AppMetricsExtract()
      recipe_parser.fetch_and_parse_data()
      output_file = recipe_parser.export_to_big_query()
      print_successful_execution(output_file)
    except ApiRuntimeError as e:
      if DEBUG_MODE:
        raise e
      recipe_parser.export_to_big_query()
      print_need_help()
    except Exception as e:
      if DEBUG_MODE:
        raise e
      print_need_help()
      print_exception(e)
else:
  if __name__ == "__main__":
    try:
      fill_default_parameters()
      parameters_validation()
      recipe_parser = AppMetricsExtract()
      recipe_parser.fetch_and_parse_data()
      output_file = recipe_parser.export_to_csv()
      print_successful_execution(output_file)
    except ApiRuntimeError as e:
      if DEBUG_MODE:
        raise e
      recipe_parser.export_to_csv()
      print_need_help()
    except Exception as e:
      if DEBUG_MODE:
        raise e
      print_need_help()
      print_exception(e)
```

```json Response Example
{"success":true}
```

# Copy this recipe

<!-- python@1-523 -->

Copy this code sample by clicking on the clipboard icon on the right and paste it in your preferred code editor.

➡️ <a href="https://help.apptweak.com/en/articles/6077217-create-powerful-reporting-dashboards-with-the-app-metrics-extract-recipe" target="_blank">full tutorial</a> ⬅️

# API Token

<!-- python@14 -->

Replace "" with your personal API token.

# Define query parameters

<!-- python@16-47 -->

- Select for which device you would like data. You can choose from iphone, ipad or android. Only one device can be used.

- List the app ids you're looking data for.

- List the metrics you would like data for.

List the country codes for the countries you would like data for.

# Date range

<!-- python@39-47 -->

By default, the date range is for the last 7 days. You can change this range here by modifying the start and end dates.

# Results written in Pandas & CSV

<!-- python@231-244 -->

The API responses are parsed and stored in a Pandas DataFrame first to easily create a csv file. Make sure to have installed the Pandas library.