> ## Content Index
> Fetch the complete content index at: https://blog.sudowl.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Zoho Books API: "Too Many Requests" and the Token Cache That Fixed It
- URL: https://blog.sudowl.com/zoho-books-api-too-many-requests-token-cache/
- Published: 2026-11-16T21:00:00.000Z
- Updated: 2026-11-18T12:34:02.000Z
- Description: Zoho Books API in the EU data center with a Self Client and a Python helper. Why token refreshes get blocked, how a 1 h cache fixes it, what's UI only.
- Author: Lukas
- Tags: business-ai, AI

I moved my invoicing for Sudowl into Zoho Books this week. Clicking through the web UI for every invoice is fine once. It's not fine when I want my scripts, and my AI assistant, to read invoices, fix the org profile and send an invoice without me opening a browser.

So I set up API access. That part took 20 minutes. Then Zoho locked me out of my own token endpoint after a handful of calls, and that's what this post is mostly about.

**TL;DR:** Use a Self Client in the Zoho API console of your data center (EU = `.eu` hosts), trade the grant code for a refresh token once, and store it in a file. Don't fetch a new access token on every call. Zoho blocks token refreshes after a few in a row. Cache the access token in a local file for its 1 hour lifetime. Logo upload and the org email are UI only. Invoice templates can contain placeholders that only the UI can change, so look at the PDF before you send.

## The helper

Usage first, explanation after. One small Python file, standard library only:

```bash
python zb.py GET invoices per_page=5
python zb.py POST invoices body.json

```

Or from another script:

```python
import zb
inv = zb.call("GET", "invoices", {"per_page": 5})

```

Every call adds the `organization_id` parameter, puts the access token into the `Authorization: Zoho-oauthtoken ...` header and returns JSON. If Zoho answers with a PDF, it returns the raw bytes. That's all it does.

## Step 1: Self Client in the right data center

Zoho runs separate data centers. If your Books account lives in the EU, everything has to happen on the EU hosts: the API console, `accounts.zoho.eu` for tokens, and the EU API domain for the actual calls. Mix them and you get auth errors that look like a wrong password.

For a single person automating their own account, the Self Client is the easy path. No redirect URL, no web app:

1. Open the API console on the `.eu` domain and create a Self Client.
2. Generate a grant code with the scope you need. I used `ZohoBooks.fullaccess.all` because I want to read and write. If you only read, take a smaller scope.
3. Trade the grant code for a refresh token right away. The grant code only lives a few minutes.

```bash
curl -s https://accounts.zoho.eu/oauth/v2/token \
  -d grant_type=authorization_code \
  -d client_id=1000.EXAMPLECLIENTID \
  -d client_secret=examplesecret \
  -d code=1000.examplegrantcode

```

The answer has a `refresh_token`, an `access_token` and an `api_domain`. The refresh token is the one that matters. It doesn't expire on its own, so treat it like a password. Mine sits in a small key=value file in my home folder, next to the client ID, client secret, org ID and the accounts and API domains. It never goes into a repo and never into a chat.

## Gotcha: Zoho blocks token refreshes

My first version of the helper did the obvious thing. Every call: refresh token in, fresh access token out, then the real request.

That works for a few calls. Then the token endpoint stops handing out tokens and answers with a "too many requests" error instead. In my case it happened after somewhere around 5 to 10 refreshes in a short time. I was testing, so I was firing calls fast. After a short wait it worked again.

The access token is valid for one hour. There's no reason to fetch a new one every few seconds. So the fix is to keep it.

## The fix: cache the access token in a file

Here's the token function, cleaned up. The cache file holds the token and its expiry time. A new token is only fetched when the cached one is missing or has less than a minute left:

```python
import json, os, time, urllib.parse, urllib.request

CACHE = os.path.expanduser("~/.zoho/.access.json")

def token(cfg):
    try:
        c = json.load(open(CACHE))
        if c["exp"] > time.time() + 60:      # still good for at least a minute
            return c["tok"]
    except Exception:
        pass                                 # no cache, broken cache: just refresh

    data = urllib.parse.urlencode({
        "grant_type": "refresh_token",
        "refresh_token": cfg["refresh_token"],
        "client_id": cfg["client_id"],
        "client_secret": cfg["client_secret"],
    }).encode()
    r = json.load(urllib.request.urlopen(cfg["accounts"] + "/oauth/v2/token", data, timeout=20))

    json.dump({"tok": r["access_token"],
               "exp": time.time() + int(r.get("expires_in", 3600))}, open(CACHE, "w"))
    return r["access_token"]

```

Three things I like about this:

- **The 60 second margin.** A token that expires in 5 seconds can die while the request is on the way. One minute of slack avoids that.
- **Failure means refresh.** If the file is missing or half written, the `except` falls through and it simply asks for a new token. No special cases.
- **Many scripts, one cache.** Every script that imports the helper shares the same file. Ten scripts in an hour cost one refresh, not ten.

The cache file is a live credential for up to an hour. Keep it out of synced folders and backups you share. If you're on Linux, a `chmod 600` on it doesn't hurt.

This is the same lesson as with any external API: count how often your code hits the expensive endpoint, not only how often it hits the one you care about. I wrote about a similar thing with an agent that burned money in the background in [API costs from background loops](/ai-agent-api-costs-background-loops/).

## What works over the API

Once the token problem was gone, most things were straightforward. What I actually did on day one:

- **Org profile.** Name, address, tax ID and website, set over the API from the data in my imprint. Before that I saved the old profile as JSON to a file, so I can see what it was.
- **Date format.** `date_format` can be set over the API. I switched it to `dd.MM.yyyy`, which is what people in Germany expect on an invoice.
- **Sending an invoice.** `POST invoices/{invoice_id}/email` with a JSON body:

```json
{
  "to_mail_ids": ["customer@example.com"],
  "subject": "Invoice INV-00001",
  "body": "Hi, attached is the invoice. Thanks!",
  "send_from_org_email_id": "billing@example.com"
}

```

The sender has to be an email address that is verified in the org. Which leads to the parts that don't work.

## Gotcha: some things are UI only

I lost time trying these over the API before giving up:

| What                             | API                                     | What I did                                    |
| -------------------------------- | --------------------------------------- | --------------------------------------------- |
| Upload the org logo              | 404, no such endpoint that I could find | Uploaded in the UI under organization profile |
| Change the org email             | Not possible, needs verification        | Has to be done and verified in the UI         |
| Text inside the invoice template | Not editable                            | UI template editor                            |
| date\_format                     | Works                                   | API                                           |
| Send invoice by mail             | Works                                   | POST invoices/{id}/email                      |

The org email one is annoying. Until the new address is verified in the UI, invoices go out from the old sender. That's fine, but tell your customer, or the first invoice from you lands in spam and nobody notices.

## Gotcha: check the PDF before you send

This one I have to admit. The template I picked has a bank block with a payment reference line. In that line there's a placeholder in square brackets, something like `[Your invoice number]`. It does not get filled in. It's literal text in the template, and you can only change it in the template editor in the UI.

The first invoice I sent over the API went out with that placeholder in it. Nothing broke, the customer could still pay, the invoice number is printed at the top anyway. But it looks sloppy and it was avoidable.

So now there's one step before every send: pull the PDF and look at it.

```python
pdf = zb.call("GET", "invoices/INVOICE_ID", {"accept": "pdf"})
open("check.pdf", "wb").write(pdf)

```

The helper returns raw bytes when the response is a PDF, that's exactly for this. Open it, read the bank block and the footer, then send. Ten seconds. If your automation sends invoices on its own, put a human check in front of the first one per template, the same way I don't let an AI parse bank statements unchecked in [my receipt sorter](/ai-receipt-matching-deterministic-parsing/).

## Why a script and not just the UI

Fair question for a one person business. For me the API is the base for later. My assistant can look up open invoices without me logging in, and the org profile and date format were two calls instead of a tour through settings pages. If you ever let a script create or send invoices on a schedule, make it check what already exists before it creates something, and read [the idempotency post](/idempotency-cron-automation-duplicate-uploads/) first. An invoice sent twice is worse than a file uploaded twice.

## What I'd do next time

Pick the template and fix its texts in the UI first, before the first API call. Verify the sender email first too. Build the token cache from line one, not after the lockout. Save the org profile as JSON before you change anything. And never send the first invoice of a new template without opening the PDF.

---

### Related posts

- [“I Barely Use It” — Where $100 of AI API Credit Actually Went](https://blog.sudowl.com/ai-agent-api-costs-background-loops/)
- [My AI Receipt Sorter Shifted Amounts by 2,000 Euros, So I Took the Numbers Away From It](https://blog.sudowl.com/ai-receipt-matching-deterministic-parsing/)
- [My AI Agent Invented a CLI Flag, and I Called the Error "Cosmetic"](https://blog.sudowl.com/ai-agent-hallucinated-cli-flags/)