Book a Meeting

Zoho Books tutorial · Python and REST

Zoho Books API with Python: connect, authenticate and post GST invoices

Short answer: Zoho does not ship an official Python SDK for Books, and you do not need one. The Zoho Books API is plain REST with JSON, so the requests library is enough. For an Indian organisation you call https://www.zohoapis.in/books/v3/, get tokens from accounts.zoho.in, send organization_id with every call and pass an Authorization: Zoho-oauthtoken header. The rest of this guide walks through tokens, a first call, a GST invoice, paging, limits and where the code should live.

We reply within 1 business hour · No obligation

300+
Zoho projects delivered
2021
Writing Zoho integrations since
3 offices
Bangalore, Coimbatore, Kochi
ZohoAdvancedPartner

Also Zoho Creator Registered, Zoho Catalyst, AWS and Shopify Partner

What do you need before Python can talk to Zoho Books?

Four things: the right data centre, your organisation ID, an OAuth client registered in Zoho's API console, and a short list of scopes. Get these right first and most "invalid token" errors never happen.

  • Data centre. A Books account created in India lives on Zoho's India data centre. API calls go to zohoapis.in and token calls go to accounts.zoho.in. Pointing an Indian account at the .com hosts is the first-day mistake we see most.
  • Organisation ID. One login can own several Books organisations, for example one per GSTIN or one per company. Every request names the organisation it acts on. You can read the ID under Manage Organisations in Books, or call the /organizations endpoint once.
  • An OAuth client. For a backend job with no web page, register a Self Client at api-console.zoho.in. For an app where many Books users sign in, register a server-based client with a redirect URL instead.
  • Scopes. Zoho Books scopes follow the pattern ZohoBooks.<module>.<operation>, such as ZohoBooks.invoices.CREATE or ZohoBooks.contacts.READ. Ask for the modules your script actually touches, not fullaccess by habit.

Use Python 3.10 or later and the requests package. Community wrappers on PyPI are not Zoho products, so check their coverage first. Zoho's Zoho Books API introduction is the reference we keep open while writing these jobs.

How does OAuth work for a Python script on the India data centre?

You trade a short-lived grant code for a refresh token once, store that refresh token as a secret, and let the script swap it for a fresh access token whenever it needs one. Zoho states that each access token works for an hour, while the refresh token lasts until someone revokes it.

  1. Create the Self ClientIn the API console choose Self Client. Zoho shows a client ID and client secret. Treat the secret like a bank password.
  2. Generate a grant codeOn the Generate Code tab enter your scopes, comma separated, pick a time window and add a description such as "nightly order sync". Copy the code at once; it expires within minutes.
  3. Exchange it for tokensPOST the code, client ID, client secret and grant_type=authorization_code to https://accounts.zoho.in/oauth/v2/token. Keep the refresh_token from the reply.
  4. Store the secrets outside the codeEnvironment variables on a server, or a secrets manager in the cloud. Never a Git repository, a shared sheet or a front-end bundle.
  5. Refresh on demandEach run asks for a new access token with grant_type=refresh_token and caches it for slightly under the hour.
# zbooks.py : token handling for an Indian Zoho Books organisation
import os
import time
import requests

ACCOUNTS = "https://accounts.zoho.in"
API_BASE = "https://www.zohoapis.in/books/v3"

_token = None
_token_expiry = 0.0

def access_token():
    """Return a cached access token, refreshing it a few minutes early."""
    global _token, _token_expiry
    if _token and time.time() < _token_expiry:
        return _token
    resp = requests.post(
        f"{ACCOUNTS}/oauth/v2/token",
        params={
            "refresh_token": os.environ["ZB_REFRESH_TOKEN"],
            "client_id": os.environ["ZB_CLIENT_ID"],
            "client_secret": os.environ["ZB_CLIENT_SECRET"],
            "grant_type": "refresh_token",
        },
        timeout=30,
    )
    resp.raise_for_status()
    body = resp.json()
    if "access_token" not in body:
        raise RuntimeError(f"Token refresh refused: {body.get('error')}")
    _token = body["access_token"]
    _token_expiry = time.time() + 55 * 60
    return _token

A reply that says invalid_client or invalid_code nearly always means the token call went to the wrong accounts host, or the grant code expired before the exchange. Zoho's OAuth page for the Books API lists the full parameter set.

What does a first working API call look like?

A GET to the contacts endpoint with your organisation ID in the query string and the token in the header. If the JSON reply carries "code": 0, authentication, data centre and scopes are all correct.

ORG_ID = os.environ["ZB_ORG_ID"]

def books(method, path, params=None, payload=None):
    """One Zoho Books call with the org ID and auth header added."""
    query = {"organization_id": ORG_ID, **(params or {})}
    resp = requests.request(
        method,
        f"{API_BASE}/{path.lstrip('/')}",
        params=query,
        json=payload,
        headers={"Authorization": f"Zoho-oauthtoken {access_token()}"},
        timeout=60,
    )
    data = resp.json()
    if resp.status_code >= 400 or data.get("code") != 0:
        raise BooksError(resp.status_code, data.get("code"), data.get("message"))
    return data

class BooksError(Exception):
    def __init__(self, http_status, code, message):
        super().__init__(f"HTTP {http_status}, Books code {code}: {message}")
        self.http_status = http_status
        self.code = code

customers = books("GET", "contacts", params={"contact_type": "customer"})
for c in customers["contacts"][:5]:
    print(c["contact_name"], c.get("gst_no", "no GSTIN"))

The helper checks both the HTTP status and Zoho's own code field. Log the message in full: it is written for people and is the fastest clue when a call is refused.

How do you create a GST-ready invoice through the API?

Send a JSON body with the customer ID, the GST treatment, the place of supply and line items that carry an HSN or SAC code and a tax ID from your own Books organisation. Books then works out CGST and SGST, or IGST, the same way it does for an invoice typed on screen.

These India-only fields are the ones our integrations set most often; confirm each against Zoho's API reference before going live.

FieldWhereWhat to send
gst_treatmentContact and invoiceRegistered business, unregistered business, consumer, overseas or SEZ, using the value names in Zoho's reference
gst_noContact and invoiceThe buyer's 15-character GSTIN, validated before the call
place_of_supplyInvoiceTwo-letter state code such as KA, MH or TN; this decides intra-state or inter-state tax
hsn_or_sacLine itemHSN for goods, SAC for services, taken from your item master
tax_idLine itemThe ID of a GST rate already set up in Books, read once from the taxes endpoint
invoice = {
    "customer_id": "460000000012345",          # Sample ID
    "reference_number": "WEB-ORD-10482",       # your own order number
    "date": "2026-11-23",
    "gst_treatment": "business_gst",
    "gst_no": "29ABCDE1234F1Z5",               # Sample GSTIN
    "place_of_supply": "KA",
    "line_items": [
        {
            "item_id": "460000000067890",      # Sample ID
            "quantity": 12,
            "rate": 850,
            "hsn_or_sac": "84819090",
            "tax_id": "460000000011111",       # 18% GST group, Sample
        }
    ],
}

created = books("POST", "invoices", payload=invoice)
print(created["invoice"]["invoice_number"], created["invoice"]["total"])

Two habits save hours later. First, put your source system's order number in reference_number and search on it before posting, so a retried job never raises the same invoice twice. Second, create invoices as drafts while you test, then switch to sending them only after your accountant has checked a week of output. If e-invoicing applies to you, see how Books handles the IRN step in our Zoho Books e-invoicing guide.

How do you read every record without missing a page?

List endpoints return one page at a time. Ask for a page with page and per_page, then keep going while the page_context block in the reply says has_more_page is true.

def all_records(path, key, **filters):
    """Yield every record from a Books list endpoint, page by page."""
    page = 1
    while True:
        data = books("GET", path, params={"page": page, "per_page": 200, **filters})
        yield from data.get(key, [])
        if not data.get("page_context", {}).get("has_more_page"):
            break
        page += 1

unpaid = list(all_records("invoices", "invoices", status="unpaid"))
print(len(unpaid), "unpaid invoices")

For a nightly sync, filter by date rather than pulling the whole ledger, so each run spends only a small share of the daily call budget.

Tap each reply

What are the Zoho Books API limits, and how should Python react?

Zoho publishes a cap of 100 requests per minute for each organisation, a daily cap that rises with your Books plan, and a limit on calls running at the same moment. Go past any of them and Books answers with HTTP 429, so the script should slow down and retry, not crash.

Daily API calls per organisation, as Zoho's API introduction listed them in November 2026
Books planCalls per dayCalls at once
Free1,0005
Standard2,00010 (soft limit)
Professional5,00010 (soft limit)
Premium, Elite, Ultimate10,00010 (soft limit)
def books_retry(method, path, attempts=5, **kw):
    """Retry per-minute and concurrency limits; give up on the daily cap."""
    global _token
    for n in range(attempts):
        try:
            return books(method, path, **kw)
        except BooksError as err:
            if err.code == 45:
                raise                      # daily cap: wait for tomorrow
            if err.http_status == 401 and n == 0:
                _token = None              # force one token refresh
                continue
            if err.http_status != 429:
                raise
            time.sleep(min(60, 2 ** n * 5))
    raise RuntimeError(f"Gave up on {method} {path} after {attempts} tries")

Limits and codes summarised from Zoho's Books API introduction. Zoho can revise them, so read the live page before you size a job.

Sort your use case

Should this run as a Python script, Deluge, Catalyst or Zoho Flow?

Python on your own server suits jobs that start in a system you already run, such as an order database or a data warehouse. When the trigger is an event inside Zoho, a Deluge function in Books, a Zoho Catalyst function or a Zoho Flow often does the same work with less to maintain.

  • Keep or skip eight situations
  • Each points to the runtime we would try first

How do you keep keys and accounting data safe in a Python integration?

Give the client the narrowest scopes, keep every secret on the server, log request IDs rather than ledger data, and make each write safe to repeat. Accounting data carries customer GSTINs, bank details and prices, so it deserves the same care as payroll.

  • Read-only where possible. A warehouse pull needs READ scopes only. Write scopes belong to the job that truly writes.
  • A named Books user. Create the token while signed in as a dedicated integration user with a limited role, so the audit trail in Books shows clearly what the script changed.
  • No secrets in browsers. If a web form or mobile app must reach Books, it calls your server or a Catalyst function, which holds the keys. Never put a client secret or refresh token in front-end code.
  • Repeat-safe writes. Search by your reference number before creating, and record the Books ID you get back, so a crash halfway through a run can be resumed cleanly.

Deluge is the other half of many of these builds: a small function in Books often handles the inside-Zoho step while Python handles the outside. Our Deluge scripting services cover that side, and Zoho Catalyst is where we host callback endpoints when there is no server of your own.

What should you check before the integration goes live?

Run the job against a test organisation or in draft mode, compare a week of its output with what your accounts team would have entered by hand, and agree who watches the error log. Then switch on real posting.

  • Tax mapping signed off. Your CA or accounts head confirms the GST treatment, place of supply and tax rate logic on sample invoices for in-state, out-of-state and export buyers.
  • Payments and reconciliation. If payments also flow in, decide which system records them, so they are not entered twice. Our Razorpay and Zoho Books payment sync guide shows one way to settle that, and the bank reconciliation walkthrough covers the matching that follows.
  • A daily summary. Count of records created, skipped and failed, mailed or posted to a Cliq channel, so silence never hides a stopped job.
  • Handover. A short runbook on tokens, limits and restarts. We train accounts and IT staff in English, Hindi, Marathi, Tamil, Kannada or Malayalam, using your own records.

Some jobs do not need the API at all. Invoices that repeat every month, for instance, are often simpler with the built-in features shown in our recurring invoices tutorial, and a monthly board pack can usually be built from the management reports Zoho Books already includes before anyone writes a script.

Want a second pair of eyes on your Books API design?We review scopes, data centre, GST payloads and limits, then tell you whether Python, Deluge or Catalyst should carry the job.

Book my free Zoho fit assessment

When the integration is part of a bigger connected setup, our Zoho API integration services team scopes and builds it, priced as a fixed amount in a signed scope. Still choosing an edition? Start with the Zoho Books product overview.

Written by

Who is behind this Zoho Books API guide?

The Zoho developers at Elite Tech Corp, a Zoho Advanced Partner with 300+ Zoho projects since 2021. The client quotes below are about our Zoho work across several industries, not about this API tutorial.

The team at Elite Tech Corporation is highly knowledgeable and extremely supportive. They took the time to understand each of our business use cases in detail and approached every requirement with a strong implementation mindset.
KVP EnterprisesFounder and CEO · manufacturing automation
What stood out most was their structured approach, clarity in communication, and commitment to aligning technology with practical, on-ground operations rather than offering generic solutions.
MegawinFounder and CEO · multiple Zoho applications
Your understanding of our requirements and customization of Zoho Books have positively impacted our operations. The successful implementation of APIs and workflows has streamlined processes.
F Care GroupFounder and CEO · Zoho Books, APIs, workflows

FAQ

Zoho Books API and Python: questions developers send us

Stuck on a refused token or an odd GST error? Paste the Books message into the form. We reply within 1 business hour.

Book my free Zoho fit assessment
Is there an official Zoho Books SDK for Python?

Zoho does not offer an official Python SDK for Zoho Books. The Books API is REST with JSON, so the requests library handles it well. Community packages exist on PyPI, but they are maintained by third parties, so check their Books coverage before relying on one.

Which API URL should an Indian Zoho Books account use?

Accounts created on Zoho's India data centre call https://www.zohoapis.in/books/v3/ for data and https://accounts.zoho.in for OAuth tokens. Using the .com hosts with an Indian account leads to token or organisation errors.

How long does a Zoho Books access token last?

Zoho states that an access token is valid for one hour. The refresh token has no expiry until the user or an admin revokes it, so a script can request a new access token whenever the old one runs out.

Where do I find my Zoho Books organization_id?

Open Manage Organisations in Zoho Books, or call the organizations endpoint once with a valid token. Every API request must carry the organization_id of the Books organisation it should act on.

How many API calls can I make to Zoho Books in a day?

Zoho's API introduction lists 1,000 calls a day on the Free plan, 2,000 on Standard, 5,000 on Professional and 10,000 on Premium, Elite and Ultimate, plus a limit of 100 calls a minute per organisation. Check the live page, because Zoho can change these.

Can Python create GST invoices with HSN codes in Zoho Books?

Yes. Send the customer ID, GST treatment, GSTIN, place of supply and line items with hsn_or_sac and a tax_id that already exists in your Books organisation. Books then calculates CGST and SGST or IGST from those values. Have your accountant check sample output first.

What does HTTP 429 with code 44 or 45 mean in the Zoho Books API?

Both mean a limit was reached. Code 44 is the per-minute limit, so wait and retry. Code 45 means the daily limit for your plan is used up, so stop the job and resume after the daily window resets.

Should my Python script use a Self Client or a server-based OAuth client?

Use a Self Client for a backend job that acts on your own Books organisation and has no web page. Use a server-based client with a redirect URL when many different Books users will sign in and grant your app access.

Zoho Books API work

Have a Python job that needs to read or write Zoho Books?

Tell us which system holds the data today, what should land in Books and how often. We reply within 1 business hour with the runtime and scopes we would use.

  • We pick the right data centre, scopes and runtime
  • GST fields mapped with your accountant before the first live invoice
  • Custom code scoped as a fixed price agreed in a signed scope

Tell us about your business

Three short steps. Fields marked * are required.

Your need
Your company
How we reach you

Privacy notice. We collect the details in this form (name, business email, phone, company, city and your requirement) only to reply to your enquiry and arrange the assessment. They are stored in Zoho CRM, the system we use to manage enquiries, and are never sold or used for advertising. The updates box is optional and you can withdraw it at any time. To see, correct or delete your details, or to withdraw consent, call +91 89259 24785 or message us on WhatsApp. Read our privacy policy.