Skip to main content

Frappy API Billing

API Quota and Billing System for Flask - compatible with the Frappy framework.

Usage

from frappyapibilling import ApiBilling, QuotaDuration, QuotaDefinition
from frappymongoapibilling import UsageStore
from datetime import datetime
from flask import Flask, jsonify, make_response

# init the usage store and the api billing handler instance
store = UsageStore(mongo_url="mongodb://localhost:27015", mongo_db="myDbName", collection_name="apiUsage")
api_billing = ApiBilling(usage_store=store)

# define the quotas for any existing client and feed them into the ApiBilling instance
client_id = "client1"
quotas = [
    QuotaDefinition(duration_type=QuotaDuration.DAY, credit_limit=500, start_date=datetime(2022, 1, 1)),
    QuotaDefinition(duration_type=QuotaDuration.MONTH, credit_limit=10000, start_date=datetime(2022, 1, 1)),
]
api_billing.update_client_quotas(client_id=client_id, quota_definitions=quotas)

app = Flask(__name__)

@app.route("/api/fetch-data", methods=["GET"])
def fetch_data_api_handler():
    # run authentication of the user
    authenticated_client = "client1" # replace with your auth mechanism
    api_billing.track_client_usage(client_id=authenticated_client)  # will abort if insufficient credits and deduct 1 credit
    # run your method
    result = ...
    return jsonify(result)


@app.route("/api/fetch-expensive-data", methods=["GET"])
def fetch_expensive_data_api_handler():
    # run authentication of the user
    authenticated_client = "client1" # replace with your auth mechanism
    credits_used = 5.0  # this can also be determined dynamically by the request
    api_billing.track_client_usage(client_id=authenticated_client, credits_used=credits_used)  
    # run your method
    result = ...
    # return a response with X-RateLimit-[Remaining|Reset] headers
    return api_billing.create_response_with_header(client_id=authenticated_client, response_body=jsonify(result))

Quota Definitions

It is up to you, where and how you store quota definitions. The API Billing module does not store the quota definitions anywhere.

When your API starts up you need to fetch any pre-existing clients and their respective quota limits and create the quota definitions. The module will fetch existing usage and update the current renew interval with already used up credits.

Likewise, while the API is running, if a new client registers, you can feed the quota definitions into the ApiBilling instance using the update_client_quotas(client_id, quota_definitions: List[QuotdaDefinition]) method.

Error Handling

The track_client_usage method will first check if sufficient credits are available. If not there are 2 possible behaviours:

  • by default a 429 will be returned to the caller with an error message and RateLimit headers
  • if the parameter use_abort=False is passed into the track_client_usage a QuotaException will be thrown and you have to handle the error.

A QuotaException has 2 fields storing quota_remaining (a number) and quota_renew (datetime) for the "shortest quota" - i.e. the quota definition with the fewest remaining credits.

You can also pass the QuotaException instance into the create_response_with_header method of ApiBilling as the optional exception parameter, which can reduce required computation to determining the next renew and remaining credits.

Please note, all datetime objects are relative to the server's timezone.

Metadata

Release files for frappyapibilling 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for frappyapibilling 0.1.0
File Size Uploaded
frappyapibilling-0.1.0.tar.gz 7.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for frappyapibilling 0.1.0
File Interpreter ABI Platform
frappyapibilling-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 18.7 kB

Release files / frappyapibilling-0.1.0.tar.gz

Download URL frappyapibilling-0.1.0.tar.gz
Size 7.0 kB
Tags Source
SHA-256 checksum
How to use checksums
f749b4c2ee2cfec91282a9ec5ad3a89db6bd96c76ca9c9ce0e0733caf1e194fc
BLAKE2b-256 checksum
How to use checksums
610820ecfef4e2f6863a2fdbac0d69431e1eff8afe3074efd471a0f2003df434
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/51.1.0 requests-toolbelt/0.9.1 tqdm/4.58.0 CPython/3.8.11

Release files / frappyapibilling-0.1.0-py3-none-any.whl

Download URL frappyapibilling-0.1.0-py3-none-any.whl
Size 11.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
45e485513ea83f4f189a2c37b4c7648701219c7df7408d14055f2640b098f0df
BLAKE2b-256 checksum
How to use checksums
c4ee022bee7ff1cf55bffe00f579bf25fb8d95ec54542bfa248cfc5492101ae2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/51.1.0 requests-toolbelt/0.9.1 tqdm/4.58.0 CPython/3.8.11

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page