Batch Sending
Send multiple invoices efficiently using GoRoute's bulk operations API at
/api/v1/batches.
Batching is a two-step operation: you create a batch, then process it. Creating
a batch stores the invoices and returns immediately; processing sends them. A small batch
(up to 100 invoices) is sent within the process request. A bigger one, or any batch you
ask for with Prefer: respond-async, is queued for GoRoute's bulk workers and the request
returns 202 Accepted at once; you poll the batch, read its results file, or subscribe to
webhooks to learn when it finishes.
Queued processing, the results file, the receipt and the larger batch limits run on
GoRoute's test service. They reach production in a later release. To see whether the
service you use has them, call GET /api/v1/batches/{any-id}/results with no API key:
404: your service does not have them yet. Each section below says how a batch behaves until then.401: your service has them, and this page applies as written.
Create a Batchโ
import requests
BASE_URL = "https://app.goroute.ai/peppol-api"
HEADERS = {
"X-API-Key": "your_api_key",
"Content-Type": "application/json"
}
def create_batch(invoices: list[dict], name: str = None) -> dict:
"""Create a batch of invoices for bulk processing."""
response = requests.post(
f"{BASE_URL}/api/v1/batches",
headers=HEADERS,
json={
"name": name,
"invoices": invoices,
"batch_type": "send"
}
)
response.raise_for_status()
return response.json()
# Example: create a batch of 3 invoices
batch = create_batch(
[
{"number": "INV-001", "...": "invoice fields"},
{"number": "INV-002", "...": "invoice fields"},
{"number": "INV-003", "...": "invoice fields"},
],
name="January invoices"
)
print(f"Batch {batch['id']} created with {batch['progress']['total']} invoices")
Each entry in invoices is an invoice object using the same fields as a single-invoice
send. The number field is used as the batch item's invoice number; if it is omitted,
items are numbered Item-1, Item-2, and so on.
Batch Typesโ
batch_type | Behaviour |
|---|---|
send | Validate and send all invoices |
validate | Validate only โ a dry run, nothing is sent |
schedule | Validate now, send at scheduled_at |
For schedule, pass scheduled_at as an ISO 8601 timestamp.
Batch Responseโ
POST /api/v1/batches returns 201 with the batch:
{
"id": "3f2a1b4c-5d6e-4f70-8a91-2b3c4d5e6f70",
"org_id": "9a8b7c6d-5e4f-4a3b-2c1d-0e9f8a7b6c5d",
"name": "January invoices",
"description": null,
"batch_type": "send",
"status": "pending",
"progress": {
"total": 3,
"pending": 3,
"processing": 0,
"success": 0,
"failed": 0,
"skipped": 0,
"percent": 0.0
},
"scheduled_at": null,
"created_at": "2026-08-03T09:15:00",
"started_at": null,
"completed_at": null,
"error_message": null
}
Create a Batch from CSVโ
Upload a CSV file instead of a JSON array:
def create_batch_from_csv(path: str, name: str = None) -> dict:
"""Create a batch by uploading a CSV file."""
with open(path, "rb") as handle:
response = requests.post(
f"{BASE_URL}/api/v1/batches/csv",
headers={"X-API-Key": "your_api_key"},
files={"file": handle},
params={"name": name, "batch_type": "send"}
)
response.raise_for_status()
return response.json()
Validate a Batchโ
Validate every invoice in a batch without sending anything:
response = requests.post(
f"{BASE_URL}/api/v1/batches/{batch_id}/validate",
headers={"X-API-Key": "your_api_key"}
)
batch = response.json()
print(f"Status: {batch['status']}")
Validating moves the batch to validating and then to ready once it has finished.
Process a Batchโ
Send the invoices:
response = requests.post(
f"{BASE_URL}/api/v1/batches/{batch_id}/process",
headers={"X-API-Key": "your_api_key"},
params={"skip_invalid": True}
)
batch = response.json()
skip_invalid defaults to true, which sends the valid invoices and skips the invalid
ones. Set it to false to require that every invoice is valid.
The batch must be ready (validated) or partial.
In the request, or queuedโ
| Batch | Answer |
|---|---|
Up to 100 invoices, no Prefer header | 200: the invoices are sent before the answer, which is the batch in its final status |
More than 100 invoices, or Prefer: respond-async | 202 Accepted at once: the batch with status queued, and job_id, status_url, results_url, receipt_url and a Location header |
response = requests.post(
f"{BASE_URL}/api/v1/batches/{batch_id}/process",
headers={"X-API-Key": "your_api_key", "Prefer": "respond-async"},
)
assert response.status_code == 202
queued = response.json() # {"status": "queued", "job_id": "...", "results_url": "...", ...}
Where the check at the top of this page answers 404, /process sends every invoice
before it answers, whatever the size of the batch, and returns the batch in its final
status. There is no Prefer: respond-async and no 202.
A queued batch moves queued โ processing โ its final status. Asking again while it
is queued or being sent returns 202 with the same job_id; nothing is queued twice. A
queued batch survives a restart or a deploy of the platform: it resumes where it stopped
and no invoice is sent twice. An invoice whose send was cut off with its outcome unknown
(for an invoice a tax authority issues, such as Nigeria's NRS) is not sent again: it stays
processing with error.code INTERRUPTED, so check your transactions before sending it
by hand. POST /batches/{id}/cancel stops a queued or running batch before its next
invoice.
Track Batch Progressโ
def get_batch(batch_id: str) -> dict:
"""Get the current state of a batch."""
response = requests.get(
f"{BASE_URL}/api/v1/batches/{batch_id}",
headers={"X-API-Key": "your_api_key"}
)
response.raise_for_status()
return response.json()
batch = get_batch(batch_id)
progress = batch["progress"]
print(f"Batch {batch['id']} โ {batch['status']}")
print(f" Succeeded: {progress['success']}")
print(f" Failed: {progress['failed']}")
print(f" Skipped: {progress['skipped']}")
print(f" Pending: {progress['pending']}")
print(f" Complete: {progress['percent']}%")
Batch Statusesโ
| Status | Meaning |
|---|---|
pending | Created, waiting to start |
queued | Waiting for a bulk worker (a queued /process) |
validating | Validating invoices |
ready | Validated, ready to send |
processing | Sending invoices |
completed | All invoices processed |
partial | Some invoices failed |
failed | Batch failed entirely |
cancelled | Cancelled by a user |
Polling for Completionโ
import time
TERMINAL = {"completed", "partial", "failed", "cancelled"}
def wait_for_batch(batch_id: str, timeout: int = 300) -> dict:
"""Poll a batch until it reaches a terminal status."""
start = time.time()
while time.time() - start < timeout:
batch = get_batch(batch_id)
if batch["status"] in TERMINAL:
return batch
time.sleep(5)
raise TimeoutError("Batch did not complete in time")
Inspect Individual Itemsโ
To see per-invoice outcomes, list the batch items:
def list_batch_items(batch_id: str, page: int = 1, page_size: int = 50) -> dict:
response = requests.get(
f"{BASE_URL}/api/v1/batches/{batch_id}/items",
headers={"X-API-Key": "your_api_key"},
params={"page": page, "page_size": page_size}
)
response.raise_for_status()
return response.json()
for item in list_batch_items(batch_id)["items"]:
if item["status"] == "success":
print(f"โ
{item['invoice_number']}: {item['transaction_id']}")
elif item["error"]:
print(f"โ {item['invoice_number']}: {item['error']['message']}")
Each item carries sequence, status, invoice_number, validation,
transaction_id, error and timestamps. Item statuses are pending, validating,
valid, invalid, processing, success, failed and skipped.
Results Fileโ
On the test service only until a later release: see the check at the top of this page. Until then, read per-invoice outcomes from the batch items.
GET /api/v1/batches/{batch_id}/results streams one row per invoice, in sequence
order, readable at any time (a batch still being sent shows each invoice's status so far):
| Column | Value |
|---|---|
sequence | Position in the batch, from 1 |
invoice_number | The invoice's number |
status | The item status |
transaction_id | The transaction created for it, once sent |
document_uuid | The issued document's UUID (BTOM-002 for an Omani invoice; the IRN of a Nigerian one), when it has one |
qr | The Oman QR TLV (base64) when the issued document carries one; empty otherwise |
error_code, error_message | Why it failed, was skipped or is unknown |
?format=csv (the default) answers text/csv with a header row; ?format=ndjson
answers one JSON object per line.
response = requests.get(
f"{BASE_URL}/api/v1/batches/{batch_id}/results",
headers={"X-API-Key": "your_api_key"},
params={"format": "ndjson"},
stream=True,
)
for line in response.iter_lines():
row = json.loads(line)
print(row["sequence"], row["status"], row["transaction_id"])
Receiptโ
On the test service only until a later release: see the check at the top of this page.
GET /api/v1/batches/{batch_id}/receipt returns the batch's receipt:
counts: the number of invoices in each item status, andtotal;control_totals: the invoice count, and the taxable amount (totals.net_amount) and VAT (totals.tax_amount) summed from the invoices as submitted, where present, per currency (by_currency) and, for a single-currency batch, overall;created_at,started_at,completed_at;request_sha256: a SHA-256 of the batch's invoices as stored, so you can prove which invoices the batch held. It is computed over the UTF-8 JSON array of the invoices in sequence order, keys sorted, with no whitespace (json.dumps(invoices, sort_keys=True, separators=(",", ":"), ensure_ascii=False)in Python).
Retry Failed Itemsโ
Reset the failed items in a batch so they can be processed again:
response = requests.post(
f"{BASE_URL}/api/v1/batches/{batch_id}/retry",
headers={"X-API-Key": "your_api_key"}
)
print(response.json()["message"]) # e.g. "Reset 2 failed items for retry"
Cancel a Batchโ
Cancel a batch that is still pending or ready:
requests.post(
f"{BASE_URL}/api/v1/batches/{batch_id}/cancel",
headers={"X-API-Key": "your_api_key"}
)
List Batchesโ
response = requests.get(
f"{BASE_URL}/api/v1/batches",
headers={"X-API-Key": "your_api_key"},
params={"page": 1, "page_size": 20, "status": "completed"}
)
listing = response.json()
print(f"{listing['total']} batches across {listing['total_pages']} pages")
Batch Limitsโ
| Limit | Value |
|---|---|
| Invoices per batch (new limit, with queued batches) | 1 minimum, 5,000 maximum |
| Invoices per batch, until queued batches reach your service | 1 minimum, 1,000 maximum; a larger batch is refused with 422 |
Request body of POST /batches (new limit, with queued batches) | 20 MB maximum (413 BATCH_BODY_TOO_LARGE past it) |
Sent within the /process request (with queued batches) | up to 100 invoices; more are queued (202) |
| Batch items per page | 100 maximum |
The check at the top of this page tells you which limits your service applies.
Requests are subject to your plan's standard API rate limits.
Chunking Larger Volumesโ
For more than 5,000 invoices, split the work across several batches. Until queued batches reach your service (the check at the top of this page), chunk at 1,000:
# 1000 until your service has queued batches; 5000 once it does.
CHUNK_SIZE = 1000
def create_batches_in_chunks(invoices: list[dict], chunk_size: int = CHUNK_SIZE) -> list[dict]:
"""Split a large invoice list into batches of at most chunk_size invoices."""
batches = []
for i in range(0, len(invoices), chunk_size):
chunk = invoices[i:i + chunk_size]
batches.append(create_batch(chunk, name=f"Chunk {i // chunk_size + 1}"))
return batches
Webhooks for Batch Eventsโ
Rather than polling, subscribe to the batch outcome events. Three are sent when a batch finishes (in the request or queued):
| Event | When |
|---|---|
batch.completed | Every invoice the run went through was sent |
batch.partial | Some invoices were sent, some failed or were skipped |
batch.failed | No invoice was sent; or the platform ended the batch, with reason_code SCHEDULE_EXPIRED (a scheduled batch first picked up over 24 hours late) or BATCH_INTERRUPTED (a send that stopped and was released for you to finish with /process) |
Each event's data carries batch_id, batch_name, batch_type, status, total,
success, failed, skipped, started_at, completed_at, results_url and
receipt_url (and reason_code and message when the platform ended the batch). Read
the results file for per-invoice detail.
batch.created, batch.validated, batch.started and batch.cancelled are catalogued
but not sent yet: GET /api/v1/events/catalog marks them planned.
Where the check at the top of this page answers 404, no event is sent when a batch
finishes. The only batch event sent is batch.failed, with reason_code
SCHEDULE_EXPIRED or BATCH_INTERRUPTED, when the platform ends a scheduled batch. To learn
when a batch has finished, poll it, as in Polling for Completion.
Complete Exampleโ
import requests
import time
from typing import Optional
BASE_URL = "https://app.goroute.ai/peppol-api"
TERMINAL = {"completed", "partial", "failed", "cancelled"}
# 1000 until your service has queued batches; 5000 once it does.
CHUNK_SIZE = 1000
class BatchSender:
def __init__(self, api_key: str):
self.api_key = api_key
self.headers = {
"X-API-Key": api_key,
"Content-Type": "application/json"
}
def create(self, invoices: list[dict], name: Optional[str] = None) -> dict:
response = requests.post(
f"{BASE_URL}/api/v1/batches",
headers=self.headers,
json={"name": name, "invoices": invoices, "batch_type": "send"}
)
response.raise_for_status()
return response.json()
def process(self, batch_id: str, skip_invalid: bool = True) -> dict:
response = requests.post(
f"{BASE_URL}/api/v1/batches/{batch_id}/process",
headers={"X-API-Key": self.api_key},
params={"skip_invalid": skip_invalid}
)
response.raise_for_status()
return response.json()
def get(self, batch_id: str) -> dict:
response = requests.get(
f"{BASE_URL}/api/v1/batches/{batch_id}",
headers={"X-API-Key": self.api_key}
)
response.raise_for_status()
return response.json()
def items(self, batch_id: str) -> list[dict]:
response = requests.get(
f"{BASE_URL}/api/v1/batches/{batch_id}/items",
headers={"X-API-Key": self.api_key},
params={"page": 1, "page_size": 100}
)
response.raise_for_status()
return response.json()["items"]
def wait(self, batch_id: str, timeout: int = 300) -> dict:
start = time.time()
while time.time() - start < timeout:
batch = self.get(batch_id)
if batch["status"] in TERMINAL:
return batch
print(f" Waiting... {batch['progress']['percent']}% complete")
time.sleep(5)
raise TimeoutError("Batch did not complete in time")
def send_all(self, invoices: list[dict], chunk_size: int = CHUNK_SIZE) -> list[dict]:
"""Create, process and await a batch for every chunk of invoices."""
results = []
for i in range(0, len(invoices), chunk_size):
chunk = invoices[i:i + chunk_size]
print(f"Batch {i // chunk_size + 1}: {len(chunk)} invoices")
batch = self.create(chunk, name=f"Chunk {i // chunk_size + 1}")
self.process(batch["id"])
results.append(self.wait(batch["id"]))
return results
# Usage
sender = BatchSender("your_api_key")
batches = sender.send_all(load_invoices())
for batch in batches:
progress = batch["progress"]
print(f"Batch {batch['id']}: {batch['status']}")
print(f" {progress['success']} succeeded, {progress['failed']} failed")
for item in sender.items(batch["id"]):
if item["error"]:
print(f" โ {item['invoice_number']}: {item['error']['message']}")