Technical
Odoo External API: XML-RPC vs JSON-RPC vs JSON-2 in Python
A practical guide to calling Odoo from outside: how XML-RPC, JSON-RPC and the newer JSON-2 API differ, how to authenticate with API keys, and how to batch calls and handle errors and throttling in Python.
Kalvyai Engineering · · Updated · 7 min read

On this page
Most Odoo integrations start the same way. A script, a web shop or another system needs to read or write Odoo records without a person clicking through the UI. Odoo gives you three ways to do that from outside: XML-RPC, JSON-RPC, and the newer JSON-2 API added in Odoo 19.
This post covers how the three differ, how to authenticate with API keys, how to batch calls so you don't flood the server, and how to handle errors and throttling. All examples are in Python.
The three APIs at a glance
| XML-RPC | JSON-RPC | JSON-2 |
|---|---|---|---|
Endpoint | | | |
Payload | XML | JSON-RPC 2.0 envelope | Plain JSON of named arguments |
Auth | db + uid + password or API key on every call | Same as XML-RPC | |
Errors | | HTTP 200 with an | HTTP error status plus JSON body |
Available | All supported versions | All supported versions | Odoo 19 and later |
Odoo 19 marks the /xmlrpc, /xmlrpc/2 and /jsonrpc endpoints as deprecated, with removal planned for a later version (Odoo 22, fall 2028, and Odoo Online 21.1, winter 2027). If you are on Odoo 19 or will upgrade soon, build new integrations on JSON-2. If you are on Odoo 18 or earlier, XML-RPC or JSON-RPC is what you have, and you should plan the switch as part of your upgrade.
One more thing to check early: on Odoo Online, external API access depends on your subscription plan. Odoo's documentation states it is only available on the Custom plan (it is not available on the One App Free or Standard plans). Odoo.sh and on-premise installs do not have that restriction.
Step 1: Create a dedicated user and an API key
Don't run integrations under a real person's login. Give each integration its own user so you can control its access rights, see its changes in the chatter, and revoke it without locking anyone out.
- Create an internal user for the integration, for example
shop-sync@yourcompany.com, and give it only the access groups it needs. - Log in as that user (or have an admin do it).
- Open the user menu, then My Profile / Preferences, then the Account Security tab (in Odoo 19 the documented path is Preferences ‣ Account Security ‣ New API Key).
- Click New API Key, confirm the password, give the key a description such as
shopify-sync-prod, and copy the key. Odoo shows it only once. - Store the key in a secrets manager or environment variable, never in the repository.
In XML-RPC and JSON-RPC, the API key goes where the password would. In JSON-2, it goes in the Authorization header and there is no separate login step.
export ODOO_URL="https://yourcompany.odoo.com"
export ODOO_DB="yourcompany"
export ODOO_USER="shop-sync@yourcompany.com"
export ODOO_API_KEY="paste-the-key-here"Step 2: Make your first call
XML-RPC
XML-RPC ships with Python's standard library, which is why so many older scripts use it. You authenticate once to get the user id (uid), then pass db, uid and key on every execute_kw call.
import os
import xmlrpc.client
url = os.environ["ODOO_URL"]
db = os.environ["ODOO_DB"]
user = os.environ["ODOO_USER"]
key = os.environ["ODOO_API_KEY"]
common = xmlrpc.client.ServerProxy(f"{url}/xmlrpc/2/common")
uid = common.authenticate(db, user, key, {})
if not uid:
raise RuntimeError("Authentication failed")
models = xmlrpc.client.ServerProxy(f"{url}/xmlrpc/2/object", allow_none=True)
partners = models.execute_kw(
db, uid, key,
"res.partner", "search_read",
[[["is_company", "=", True]]],
{"fields": ["name", "email"], "limit": 10},
)
print(partners)Things that trip people up:
- Positional arguments go in a list, keyword arguments in a dict. A domain is a list inside that list, which is why you see three levels of brackets.
- Empty fields come back as
False, notNone. - Many2one fields come back as
[id, display_name]. - XML-RPC cannot marshal integers larger than 32 bits, so very large numbers need to be sent as strings or floats.
JSON-RPC
JSON-RPC calls the same services as XML-RPC, wrapped in a JSON-RPC 2.0 envelope. It is easier to use from JavaScript and avoids XML quirks, but the shape of the call is identical.
import os
import requests
url = os.environ["ODOO_URL"]
db = os.environ["ODOO_DB"]
user = os.environ["ODOO_USER"]
key = os.environ["ODOO_API_KEY"]
def jsonrpc(service, method, *args):
payload = {
"jsonrpc": "2.0",
"method": "call",
"params": {"service": service, "method": method, "args": args},
"id": 1,
}
resp = requests.post(f"{url}/jsonrpc", json=payload, timeout=60)
resp.raise_for_status()
body = resp.json()
if "error" in body:
data = body["error"].get("data", {})
raise RuntimeError(f"{data.get('name')}: {data.get('message')}")
return body["result"]
uid = jsonrpc("common", "authenticate", db, user, key, {})
partners = jsonrpc(
"object", "execute_kw", db, uid, key,
"res.partner", "search_read",
[[["is_company", "=", True]]],
{"fields": ["name", "email"], "limit": 10},
)Note that Odoo returns most application errors with HTTP status 200 and an error key in the body. If you only check the status code, you will miss them.
JSON-2 (Odoo 19+)
JSON-2 drops the envelope and the login step. The model and method are in the URL, the API key is a bearer token, and the body is a JSON object of named arguments that match the Python method's signature.
import os
import requests
url = os.environ["ODOO_URL"]
session = requests.Session()
session.headers.update({
"Authorization": f"bearer {os.environ['ODOO_API_KEY']}",
"X-Odoo-Database": os.environ["ODOO_DB"],
"Content-Type": "application/json; charset=utf-8",
"User-Agent": "shop-sync/1.0",
})
resp = session.post(
f"{url}/json/2/res.partner/search_read",
json={
"domain": [["is_company", "=", True]],
"fields": ["name", "email"],
"limit": 10,
"context": {"lang": "en_US"},
},
timeout=60,
)
resp.raise_for_status()
print(resp.json())The X-Odoo-Database header is only needed when the server hosts several databases and cannot pick one from the domain name. For methods that act on existing records, pass ids:
session.post(
f"{url}/json/2/res.partner/write",
json={"ids": [42], "vals": {"phone": "+91 98765 43210"}},
timeout=60,
).raise_for_status()One design point matters here: each JSON-2 request runs in its own database transaction. If your logical operation needs several writes that must succeed or fail together (create an order, add lines, confirm it), three separate calls can leave half-finished data when the second one fails. The cleaner fix is a small custom method in an Odoo module that does the whole operation server-side, which you then call with one request.
Step 3: Batch your calls
The most common performance problem we see in Odoo integrations is one HTTP call per record. Every call has network latency plus authentication and transaction overhead. A sync that does 10,000 single-record calls is slow and puts real load on the server.
Create many records in one call
create accepts a list of value dicts and returns a list of ids.
new_ids = session.post(
f"{url}/json/2/res.partner/create",
json={"vals_list": [
{"name": "Acme Traders", "is_company": True},
{"name": "Blue Hill Retail", "is_company": True},
]},
timeout=120,
).json()Write the same values to many records
write applies one set of values to every id you pass. Group your updates by identical values where you can.
Read only what you need, page by id
Always pass fields. Reading every field on a model like product.product pulls computed fields you don't use and can be very slow. For large tables, page by id rather than offset, because offsets get slower as they grow and can skip or repeat rows if data changes during the run.
def iter_records(model, domain, fields, page_size=500):
last_id = 0
while True:
rows = session.post(
f"{url}/json/2/{model}/search_read",
json={
"domain": domain + [["id", ">", last_id]],
"fields": fields,
"order": "id asc",
"limit": page_size,
},
timeout=120,
).json()
if not rows:
return
yield from rows
last_id = rows[-1]["id"]
for product in iter_records("product.product", [["active", "=", True]], ["default_code", "qty_available"]):
...The page size of 500 here is a starting point, not a rule. Measure on your own data: models with heavy computed fields need smaller pages.
For incremental syncs, filter on write_date greater than the last successful run time instead of re-reading everything.
Step 4: Handle errors properly
Split errors into two groups, because they need opposite treatment.
Do not retry: access errors, validation errors, missing records, wrong field names, bad arguments. Retrying these gives the same result. Log them with the payload and send them to a person or a review queue.
Retry with backoff: connection resets, timeouts, and gateway or overload responses such as 502, 503, 504 and 429.
With JSON-2, failures come back as non-2xx HTTP statuses with a JSON body describing the error, including its name and message (the docs specify a 4xx/5xx status with a JSON error object containing name, message, arguments, context and debug). A small wrapper keeps this consistent:
class OdooError(Exception):
def __init__(self, status, name, message):
super().__init__(f"{status} {name}: {message}")
self.status = status
self.name = name
self.message = message
def raise_for_odoo(resp):
if resp.ok:
return
try:
err = resp.json()
except ValueError:
err = {"name": None, "message": resp.text[:500]}
raise OdooError(resp.status_code, err.get("name"), err.get("message"))With XML-RPC, catch xmlrpc.client.Fault and read faultString, which usually contains the server traceback. With JSON-RPC, check the error object as shown earlier. In both cases the exception name (for example odoo.exceptions.AccessError or odoo.exceptions.ValidationError) is the most reliable way to decide whether to retry.
Step 5: Respect rate limits and server load
Odoo's documentation does not publish a fixed request-per-second limit for the external API check your hosting plan's terms for any limits that apply to you. In practice, throttling comes from several places: the hosting platform, a reverse proxy or load balancer in front of Odoo, or simply worker exhaustion when too many long requests arrive at once.
The defensive approach is the same regardless of the source:
- Keep concurrency low. A handful of parallel workers is usually plenty; more just queues requests on the Odoo side.
- Retry only the retryable cases, with exponential backoff and jitter.
- Honour a
Retry-Afterheader if the response includes one. - Cap total attempts and surface the failure instead of looping forever.
import random
import time
import requests
RETRYABLE = {429, 502, 503, 504}
def post_with_retry(session, url, payload, max_attempts=5, timeout=120):
for attempt in range(1, max_attempts + 1):
try:
resp = session.post(url, json=payload, timeout=timeout)
except (requests.ConnectionError, requests.Timeout):
if attempt == max_attempts:
raise
delay = min(60, 2 ** attempt)
else:
if resp.status_code not in RETRYABLE or attempt == max_attempts:
raise_for_odoo(resp)
return resp.json()
retry_after = resp.headers.get("Retry-After", "")
delay = int(retry_after) if retry_after.isdigit() else min(60, 2 ** attempt)
time.sleep(delay + random.uniform(0, 1))Make retries safe
A timeout does not mean the call failed. Odoo may have created the record and the response was lost on the way back. If you blindly retry a create, you get duplicates.
Two ways to avoid this:
- Store an external reference on the record (for example the Shopify order id in a dedicated field or as an external ID) and search for it before creating.
- Wrap create-or-update logic in a server-side method that checks the reference itself, so a retried call is a no-op.
Reads and write calls with the same values are naturally safe to repeat. Creates, confirmations and anything that posts accounting entries are not.
Which one should you use?
- New integration on Odoo 19 or later: JSON-2. Simpler payloads, proper HTTP errors, header-based auth, and it is the path Odoo is keeping.
- Odoo 18 or earlier: JSON-RPC if you are in a JavaScript or
requests-based stack, XML-RPC if you want zero dependencies. Keep the call logic in one module so moving to JSON-2 later is a contained change. - Existing XML-RPC or JSON-RPC integration you are upgrading to Odoo 19: it keeps working while deprecated, but put the migration on the upgrade plan rather than waiting for removal.
Whatever you pick, the habits matter more than the protocol: one user and key per integration, batched calls, explicit fields, retries only where safe, and logs that tell you which record failed and why.
How Kalvyai can help
We build and maintain Odoo integrations for teams connecting shops, accounting tools and internal systems, including moving older XML-RPC scripts to JSON-2. You can see what we do at kalvyai.com/odoo, and our ready-made apps are at store.kalvyai.com.
If your problem is a store sync, the Shopify Odoo Connector connects Shopify and Odoo without writing the API layer yourself. If you already run several store syncs and need to see what is failing, ConnectIQ gives you unified sync telemetry, queue tracking and AI error diagnostics inside Odoo.
For a custom integration or a review of an existing one, get in touch.
Last updated 20 Nov 2026
- Odoo
- External API
- JSON-2
- XML-RPC
- Python
- Integrations
Kalvyai Engineering · Engineering team
The engineers who build, connect and fix business systems at Kalvyai: Odoo, ERPNext, Shopify and AI agents that work inside them with approvals, budgets and an audit trail.



Comments
No comments yet. Questions and corrections are welcome.
Rate this post or leave a comment