Code Samples

Sometimes it’s best to just see it done. For that, we have some code samples for you to peruse. Though we are working diligently on full libraries for interfacing with our API, they aren’t quite ready yet. Until then, these examples should get you started (and never be afraid to ask if not), the interface is simple enough that whatever language you are using should run closely to what’s happening here in python and cURL.

Each example either uses Personal Access Tokens or OAuth 2.0 to authenticate.

Bash + cURL (Personal Access Token)

This is a simple example of making a request from the command line. You probably won’t be using cURL, but if you run into issues we’ve found it’s best to try to recreate them with cURL with the -vv flag.
You get a lot of of insight into what your request and response look like this way. Another good thing about cURL is that it’s easy to see what it’s doing even if you’re not familiar with the tool.

#!/bin/bash
export TOKEN='pat_1234' # Your personal access token goes here.
export BASE='https://api.appfigures.com/v2/'

# get products
curl -H"Authorization: Bearer $TOKEN" "${BASE}products/mine?pretty=true"

#get total sales by product
curl-H"Authorization: Bearer $TOKEN" "${BASE}reports/sales/products?pretty=true"

Python (Personal Access Token)

The below example uses the requests package, available from pip. make_request is the crux, the rest is just exercising the API by getting and manipulating resources.

""" Script that demonstrates how to access the Appfigures API from python. It relies on requests
"""
import requests

# Fill these constants in
PERSONAL_ACCESS_TOKEN = "pat_1224" # Your personal access token goes here
BASE_URI = "https://api.appfigures.com/v2/"

# Helper function for auth and app_key
# first / in uri is optional
def 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 business
root_response = make_request("/")
assert 200 == root_response.status_code
assert USERNAME == root_response.json()["user"]["email"]

# Get a list of products
product_response = make_request("/products/mine")
assert 200 == product_response.status_code
assert 0 < len(product_response.json())
for (id, product) in product_response.json().items():
  print(product["name"], product["id"])

# Get data for all inapps for a year by month
products = 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 revenue
data = 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] + map(str, downloads)))

Python (OAuth 2.0)

There's a decent python package for OAuth 2.0 called requests-oauthlib.
This example shows how to use it 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)

Here's snippet of C# code that talks to 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}");
            Console.Write(request.Headers["Authorization"]);
            WebResponse response = request.GetResponse();
            using (StreamReader responseReader = new StreamReader(response.GetResponseStream())) {
                return JObject.ReadFrom(new JsonTextReader(responseReader)) as JObject;
            }
        }
    }
}