← Back to blog

How to Check API Quota and Handle 429 Errors (curl + Python)

September 26, 2026 · Eric · 7 min read

The fastest way to make an agent look broken is to let it discover quotas by hitting them. A batch job that runs 40 image operations, blows through the free pool at operation 11, and then keeps retrying a 429 in a tight loop does not look clever — it looks like a bug that also costs money.

Agent Media Tools exposes its own limits as data. There is a free, unmetered endpoint that tells you exactly how much quota you have left, a standard set of RateLimit-* headers on every response, distinct machine-readable error codes on every refusal, and a small group of status endpoints you can poll without spending anything. This post shows how to read all four, with the exact response bodies, and ends with a Python client that backs off the right way.

The limiters you can actually hit

Four separate things can refuse a request, and they need different reactions:

LimiterScopeAllowance
Anonymous daily poolPer IP address10 metered calls / day
Free account poolPer logged-in user25 calls / day
Paid account poolPer subscribed user1,000 calls / day
Free agent keyPer mt_ API key25 calls / day by default
Pro agent keyPer mt_ API key1,000 calls / day
Burst windowPer IP, anonymous traffic only60 requests / 60 seconds
Credit-priced toolsPer tool, per identitySmall per-tool daily free allowance, then credits

The 25/day and 1,000/day figures are the published plan allowances on the pricing page. The anonymous allowance is reported live by the API itself, so you never have to guess it — which brings us to the first call your client should make.

Step 1: preflight with GET /api/usage

/api/usage is free, needs no API key, and is deliberately excluded from the metered pool, so asking "how much do I have left?" never costs you anything. It answers for whichever identity you present: an Authorization: Bearer mt_... header reports the agent key, a session cookie reports the account, and no credentials reports the calling IP.

curl -s https://agentmediatools.com/api/usage
{
  "success": true,
  "identity": "anonymous",
  "plan": "anonymous",
  "used_today": 5,
  "daily_limit": 10,
  "remaining": 5,
  "percent_used": 50,
  "suggested_action": "ok",
  "upgrade_cta": "Create free account — 25/day",
  "pricing_url": "https://agentmediatools.com/pricing",
  "register_url": "https://agentmediatools.com/app?register=1",
  "reset": "Resets at midnight UTC"
}

Three fields do the real work. remaining is what your scheduler should branch on before starting a batch. suggested_action moves through ok → consider_upgrade → register (anonymous) or upgrade_pro / buy_credits (keyed), which means an agent can explain its own situation instead of surfacing a bare 429. And reset tells you the boundary: the daily pools roll over at midnight UTC.

Two behaviours worth knowing, both easy to verify yourself: calling /api/usage repeatedly leaves used_today unchanged, while one successful tool call moves it by exactly one. The counter is charged when a response comes back with a status below 400 — so a call that returns 200 with {"success": false, "error": "text required"} still costs a unit, whereas genuine 4xx and 5xx responses do not. Validate inputs before you ship them, and the free pool lasts a lot longer.

Step 2: read the burst headers on every response

Alongside the daily pool, anonymous traffic passes through a per-IP burst limiter. Its state is published in standard headers on each response, so you can see it coming instead of discovering it:

curl -si "https://agentmediatools.com/api/uuid?count=1" | head -20
HTTP/1.1 200 OK
RateLimit-Policy: 60;w=60
RateLimit-Limit: 60
RateLimit-Remaining: 59
RateLimit-Reset: 60

Treat these as a per-minute signal and the daily pool as a per-day signal; RateLimit-Reset is the number of seconds until the burst window refills, which is exactly what a polite retry needs. Two details matter for agents: the burst limiter is skipped for any request that carries credentials (a session cookie, or an Authorization / X-API-Key header), and a handful of routes — health, public stats, the tools catalog, docs, changelogs — are exempt from both limiters because they are not tool work.

Step 3: branch on the 429 body, not the status code

Every daily-limit refusal is a 429 with a code field that says which pool ran dry, plus the numbers behind the decision. Anonymous callers see this:

{
  "success": false,
  "code": "ANON_DAILY_LIMIT",
  "error": "Free daily limit reached (10/day). Sign up free for 25/day—no card required: ...",
  "suggested_action": "register",
  "upgrade_cta": "Create free account — 25/day",
  "limit": 10,
  "used": 10
}

Agent keys get the same shape under a different code — AGENT_FREE_DAILY_LIMIT or AGENT_PAID_DAILY_LIMIT — and logged-in users get FREE_USER_DAILY_LIMIT or PAID_DAILY_LIMIT. That single field is the difference between two completely different retry strategies:

Step 4: credit-priced tools fail with 402, not 429

Some tools skip the shared pool entirely because each call has real upstream cost — transcription, image generation, background removal, vision captioning, hosted browser sessions, PDF-to-markdown, and the larger media routes. Those run on a small per-tool daily free allowance and then spend flexible credits. That means their refusal is a 402 and the numbers live in a billing object:

{
  "success": false,
  "error": "Free daily limit for transcribe reached (1/day). Log in, create an API key, and buy credits to continue.",
  "billing": {
    "tool": "transcribe",
    "free_daily_limit": 1,
    "credit_cost": 2,
    "buy_credits": "https://agentmediatools.com/pricing"
  }
}

The real body also lists the available credit packs and a one-line agent checkout hint, so a client can surface an exact next step. When credits run out instead, the same 402 carries credits_available next to credit_cost, so a client can say "this job needs 2 credits and you have 0" without guesswork. And if your key has a spend policy — a kill switch, a daily credit budget, or an approval threshold — refusals come back as 403 with a billing.code describing the policy that stopped it. Those knobs are covered in Cap AI Agent API Costs.

Tip

Free daily allowances are per tool, per identity, and they stack the same way for everyone: screenshot gets 5, html-to-pdf and pdf-to-markdown get 3 and 5, structured-scrape gets 3, transcribe gets 1, and describe-image gets none because every vision call is upstream spend. Pro plans raise the allowances rather than removing them, and unused monthly credits roll up to a cap. Check the current numbers on the pricing page before you hard-code anything.

Step 5: a quota-aware Python client

Here is the whole pattern in one file. It preflights the quota, sends the request, then classifies every failure: burst waits seconds, daily pools stop the job, credit shortfalls and policy blocks fail loudly, and transient 5xx responses back off exponentially.

import time
import requests

BASE = "https://agentmediatools.com"
KEY = None  # "mt_..." for agent keys, or a session cookie for account view

def auth_headers():
    return {"Authorization": f"Bearer {KEY}"} if KEY else {}

def quota():
    """Free preflight — never counted against the daily pool."""
    r = requests.get(f"{BASE}/api/usage", headers=auth_headers(), timeout=30)
    r.raise_for_status()
    return r.json()

def call(path, payload, attempts=4):
    for attempt in range(attempts):
        r = requests.post(f"{BASE}{path}", json=payload,
                          headers=auth_headers(), timeout=120)

        if r.status_code == 429:
            body = r.json()
            code = body.get("code")
            if code is None:                      # burst window: seconds, not hours
                time.sleep(int(r.headers.get("RateLimit-Reset", 5)) + 1)
                continue
            # Any named daily code means the pool is gone until midnight UTC.
            raise RuntimeError(f"daily pool exhausted: {code} — {body['error']}")

        if r.status_code == 402:
            b = r.json().get("billing", {})
            raise RuntimeError(
                f"needs credits: cost={b.get('credit_cost')} "
                f"free_limit={b.get('free_daily_limit')} "
                f"balance={b.get('credits_available')}"
            )

        if r.status_code == 403:
            raise RuntimeError(f"blocked by key policy: {r.json()}")

        if r.status_code >= 500:
            time.sleep(2 ** attempt)
            continue

        return r.json()

    raise RuntimeError(f"gave up on {path} after {attempts} attempts")

print(quota())
print(call("/api/slugify", {"text": "Quota aware client"}))

The preflight matters most for scheduled work. An agent that checks remaining before a nightly batch can resize the batch to fit, or skip tonight and report why — which is a much better failure mode than a half-finished pipeline with eight unexplained errors in a log.

Status endpoints you can poll for free

Probing a tool endpoint just to see whether the service is up is wasteful; every one of these is exempt from the daily pool and the burst limiter.

EndpointWhat it tells you
GET /api/health{"ok": true}, cheap enough for a 30-second liveness probe
GET /api/status/uptimePer-region status, 30-day uptime percentage, and the previous outage window
GET /api/stats/liveToday's processed operations, tool operations, human vs agent requests, top paths, and the stats day boundary
GET /api/stats/activityA human-readable feed of recent tool activity plus the day's top tools
GET /api/tools/statsCatalog totals by tier and category, so a client can discover how much surface exists before choosing a path

/api/status/uptime deserves one caveat: when the upstream uptime history is not available it returns 503 with {"available": false}. That is "I don't know", not "the API is down" — your alerting should keep those two cases apart, otherwise a monitoring blip pages a human at 3am for nothing.

Honest limitations

Wrap up

Preflight with /api/usage, watch the RateLimit-* headers, branch on the 429 code (and on 402 for credit-priced tools), and poll the free status endpoints when something looks wrong. That is about forty lines of client code that turn quota exhaustion from a mystery into a scheduled, explainable event — and your agent stops being the thing your on-call rotation complains about.

Try it in the Toolbox

Run the same tools in the browser, or call them from your agent with an API key.

Open toolbox