Code Samples
These samples show how to call the API from Bash, Python and C#. We don’t have official client libraries yet. The API is simple, so the Python and cURL examples should translate to whatever language you use. If you get stuck, ask us.
Each example uses either Personal Access Tokens or OAuth 2.0 to authenticate.
Bash + cURL (Personal Access Token)
Section titled “Bash + cURL (Personal Access Token)”This example makes a request from the command line. You probably won’t use cURL in production. But if you hit a problem, try to reproduce it with cURL and the -vv flag. You’ll see exactly what your request and response look like. cURL is also easy to read, even if you don’t use it often.
#!/bin/bashexport TOKEN='pat_1234' # Your personal access token goes here.export BASE='https://api.appfigures.com/v2/'
# get productscurl -H"Authorization: Bearer $TOKEN" "${BASE}products/mine?pretty=true"
#get total sales by productcurl -H"Authorization: Bearer $TOKEN" "${BASE}reports/sales/products?pretty=true"Python (Personal Access Token)
Section titled “Python (Personal Access Token)”This example uses the requests package from pip. make_request does the work. The rest of the script calls the API and works with the results.
""" Script that demonstrates how to access the Appfigures API from python. It relies on requests"""import requests
# Fill these constants inPERSONAL_ACCESS_TOKEN = "pat_1224" # Your personal access token goes hereUSERNAME = "you@example.com" # The email address on your Appfigures accountBASE_URI = "https://api.appfigures.com/v2/"
# Helper function for auth and app_key# first / in uri is optionaldef make_request(uri, **querystring_params): headers = {"Authorization": f"Bearer {PERSONAL_ACCESS_TOKEN}"} return requests.get(BASE_URI + uri.lstrip("/"), params=querystring_params, headers=headers)
# Get the root resource to show we are in businessroot_response = make_request("/")assert 200 == root_response.status_codeassert USERNAME == root_response.json()["user"]["email"]
# Get a list of productsproduct_response = make_request("/products/mine")assert 200 == product_response.status_codeassert 0 < len(product_response.json())for (id, product) in product_response.json().items(): print(product["name"], product["id"])
# Get sales for all apps over the last 30 days, grouped by monthproducts = product_response.json().values()inapps = [p for p in products if p["type"] == u"app"]inapp_ids = [str(product["id"]) for product in inapps]inapp_names = [inapp["name"] for inapp in inapps]route = "/reports/sales?start_date=-30&group_by=dates,products"inapp_sales_response = make_request(route, granularity="monthly", products=";".join(inapp_ids))print(inapp_sales_response.json())assert 200 == inapp_sales_response.status_code
# Make a little table of downloadsdata = inapp_sales_response.json()months = sorted(data.keys())print(",".join(["date\\product_name"] + inapp_names))for month in months: values = data[month] downloads = [] for inapp_id in inapp_ids: if inapp_id in values: downloads.append(values[inapp_id]["downloads"]) else: downloads.append("0") print(",".join([month] + list(map(str, downloads))))Python (OAuth 2.0)
Section titled “Python (OAuth 2.0)”This example uses the requests-oauthlib package to get an access token and start making requests.
""" Demonstrates using the requests-oauthlib library to interact with the Appfigures API"""from requests_oauthlib import OAuth2Session
base_url = "https://api.appfigures.com/v2"client_key = "your_client_key"client_secret = "your_client_secret"
authorize_url = base_url + "/oauth2/authorize"access_token_url = base_url + "/oauth2/access_token"
scopes = ["account:read", "products:read", "public:read"]
def _get_session(access_token=None): """If access_token and secret are given, create and return a session.
If they are not given, go through the authorization process interactively and return the new session """ session = OAuth2Session(client_id=client_key, scope=scopes, redirect_uri="oob") if access_token: session.token = {"access_token": access_token, "token_type": "bearer"} return session
authorization_url, state = session.authorization_url(authorize_url) print("Please go here and authorize: %s" % authorization_url) code = input("Paste the code you were given here:") token = session.fetch_token( access_token_url, client_secret=client_secret, code=code, auth=(client_key, client_secret), ) return session
if __name__ == "__main__":
# run the user through the authorization process s = _get_session() print("Token: %s" % (s.token))
# get a list of products from the account resp = s.get(base_url + "/products/mine") print([product["name"] for (id, product) in resp.json().items()])
# get the list of only apple products from the account resp = s.get(base_url + "/products/mine", params=dict(store="apple")) print([product["name"] for (id, product) in resp.json().items()])
# now try to get a report, which requires a different scope resp = s.get(base_url + "/reports/sales/products") print("Status code(%s) should be 403 because of scope" % resp.status_code)C# (Personal Access Token)
Section titled “C# (Personal Access Token)”Here’s a C# snippet that calls the API.
using System;using System.IO;using System.Net;using Newtonsoft.Json;using Newtonsoft.Json.Linq;
namespace ApiClient{ class Program { static void Main(string[] args) { Console.WriteLine(" --- Products --- "); AppfiguresApi client = new AppfiguresApi("PERSONAL_ACCESS_TOKEN");
var products = client.MakeRequest("products/mine"); foreach(var product in products){ Console.WriteLine(product.Value["name"]); }
Console.WriteLine("\n--- Sales Over Past 7 Days ---"); var sevenDaySales = client.MakeRequest("/reports/sales?group_by=dates&start_date=-7"); foreach (var date in sevenDaySales) { var sales = date.Value; Console.WriteLine(String.Format("{0}: {1,-4}(${2:C})", date.Key, sales["downloads"], sales["revenue"])); } } }
class AppfiguresApi { private static readonly Uri BaseUrl = new Uri("https://api.appfigures.com/v2/"); public readonly String AccessToken;
public AppfiguresApi(String accessToken) { this.AccessToken = accessToken; }
public JObject MakeRequest(String path) { Uri fullUri = new Uri(BaseUrl, path); WebRequest request = WebRequest.Create(fullUri); request.PreAuthenticate = true; request.Headers.Add("Authorization", $"Bearer {this.AccessToken}"); WebResponse response = request.GetResponse(); using (StreamReader responseReader = new StreamReader(response.GetResponseStream())) { return JObject.ReadFrom(new JsonTextReader(responseReader)) as JObject; } } }}