Exporting reservations via the REST API
How to authenticate against the ZEMTU REST API and export reservation data — including filtering, pagination, and a ready-to-use export script.
Written By Zemtu
Last updated 5 days ago
Introduction
This article is aimed at developers who want to make use of the ZEMTU REST API. It explains authentication, pagination, filtering, and ordering — using the export of reservation data as a complete, working example. The same pattern applies to all other endpoints (vehicles, users, invoices, etc.).
For large or regular reservation exports (for example a full year), use the API. The Excel export in the administration can time out. See Exporting large amounts of reservations.
General info
Base URL: We use
https://carsharing.zemtu.comin this documentation. Always replacecarsharingwith your subdomain:https://YOUR_ORGANIZATION.zemtu.comSerialization format: JSON is used for data exchange.
Versioning:
/api/v2/— new API versions are offered under a distinct version number to allow backward-incompatible API evolution.Methods: HTTP GET is used for fetching data, POST for creating, PUT/PATCH for updating and DELETE for deleting data.
Documentation: The auto-generated, interactive API documentation with all available endpoints, fields, and filters can be accessed at
https://YOUR_ORGANIZATION.zemtu.com/docs
Authentication
TokenAuthentication: for clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal Token, with whitespace separating the two strings:
Authorization: Token 9944b19199c62bgf9418td846dd0e4bzdfc6de9bThere are several possibilities to obtain the token:
Read token from admin interface (only for users with org admin role):
https://YOUR_ORGANIZATION.zemtu.com/admin/authtoken/token/Get direct access to the token, e.g. via secure email from your organization administrator.
Obtain the token with username & password by posting the credentials to
/api-token-auth/:
curl --data "username=USERNAME&password=PASSWORD" https://YOUR_ORGANIZATION.zemtu.com/api-token-auth/The JSON response looks like {"token": "9844b19129c62bhf9418td746cd0e4bzdfc6de9b"} — the token is then used for all API communication.
Setup recommendation
Best practice is to create a dedicated machine user at https://YOUR_ORGANIZATION.zemtu.com/admin/main/customuser/ and get a token for it via https://YOUR_ORGANIZATION.zemtu.com/admin/authtoken/token/?user=PRIMARY_KEY_OF_THE_USER.
The rule of thumb for permissions: the API user sees the same objects via the API as in the backend administration. To export all reservations of an organization, the machine user needs to be assigned to the organization with a suitable role, e.g. "Accountant" or "OrgAdmin".
Pagination
All list endpoints return a paginated envelope:
{"count": 1234, "next": "https://...&page=2", "previous": null, "results": [ ... ]}/api/v2/reservation/— default page size: 100, maximum: 500/api/v2/reservationaccounting/and/api/v2/reservationreporting/— default page size: 50, maximum: 250A custom page size can be set with
?page_size=250; a specific page with&page=2. The simplest export strategy is to follow thenextURL until it isnull.
Endpoints for exporting reservations
Hint: the trailing / is important for detail endpoints, e.g. /api/v2/reservation/{ID}/.
Filtering
The reservation and reservation accounting endpoints support these filters:
Hint: gte stands for "greater than or equal to", lte for "less than or equal to". Datetimes are given in ISO 8601 format, e.g. 2026-01-01T00:00:00Z.
/api/v2/reservationreporting/ additionally offers start__gte/__lte (reservation start) and billed_end__gte/__lte (the end relevant for billing).
Filtering examples
All reservations starting in January 2026:
https://YOUR_ORGANIZATION.zemtu.com/api/v2/reservationaccounting/?reservation_start__gte=2026-01-01T00:00:00Z&reservation_start__lt=2026-02-01T00:00:00ZClosed or deleted reservations:
?state__in=closed,deletedReservations of vehicle 201:
?vehicle=201Reservations owned by user 1550:
?owner=1550Reservations changed since the last export run:
?modified__gte=2026-10-01T00:00:00Z
Ordering
Results can be sorted with the ordering parameter, e.g. ?ordering=-reservation_start for descending order by reservation start. Available ordering fields are created, reservation_start, reservation_end, and vehicle (reservation API); reservation_start (accounting and reporting APIs).
Result structure (reservation accounting)
Example result
"note": "",
"reservation_start": "2014-09-04T05:30:00Z",
"start_real": null,
"reservation_end": "2014-09-05T12:30:00Z",
"end_real": null,
"note_billing": null,
"purpose": 0,
"owner": {
"id": 2275,
"external_user_id": ""
},
"vehicle": {
"id": 201,
"type": "ZEMTU Renault Twizy",
"address1": "Färbergasse 17b",
"city": "Dornbirn",
"zip": "6850"
},
"created": "2014-09-02T18:02:48.740223Z",
"modified": "2014-09-02T18:03:00.274824Z",
"distance": null,
"lift_offer": false,
"state": "deleted",
"versions": [
{
"lift_offer": false,
"state": "deleted",
"modified": "2014-09-02T18:03:00.274Z",
"note": "",
"reservation_start": "2014-09-04T05:30:00Z",
"purpose": 0,
"reservation_end": "2014-09-05T12:30:00Z"
},
{
"lift_offer": false,
"state": "opened",
"modified": "2014-09-02T18:02:56.804Z",
"note": "",
"reservation_start": "2014-09-04T05:30:00Z",
"purpose": 0,
"reservation_end": "2014-09-05T12:30:00Z"
},
{
"lift_offer": false,
"state": "opened",
"modified": "2014-09-02T18:02:48.740Z",
"note": "",
"reservation_start": "2014-09-04T05:30:00Z",
"purpose": 0,
"reservation_end": "2014-09-05T09:30:00Z"
}
],
"odometer_start": null,
"odometer_end": nullExample: exporting reservations
cURL
curl -H "Authorization: Token XXXX" \ "https://YOUR_ORGANIZATION.zemtu.com/api/v2/reservationaccounting/?format=json&page_size=250"Python 3 — export all reservations of a month to CSV
The script reads every page of reservations for one month and writes them to a CSV file. It needs Python 3.11 or later, with nothing extra to install. Put your token in the environment variable ZEMTU_API_TOKEN and run:
python3 export_reservations_month.py --organization YOUR_ORGANIZATION --month 2026-01Month boundaries are in UTC. The file reservations-2026-01.csv opens directly in Excel.
#!/usr/bin/env python3
"""Export all reservations that start in one month to a CSV file.
Uses the ZEMTU REST API endpoint /api/v2/reservationaccounting/ and follows
the pagination links until every page has been read. Standard library only.
Usage:
export ZEMTU_API_TOKEN="your-token"
python3 export_reservations_month.py --organization YOUR_ORGANIZATION --month 2026-01
Month boundaries are interpreted in UTC.
"""
from __future__ import annotations
import argparse
import csv
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import TYPE_CHECKING, Final, TypedDict, cast
if TYPE_CHECKING:
from collections.abc import Iterator
TOKEN_ENV_VAR: Final = "ZEMTU_API_TOKEN" # noqa: S105 - name of the variable, not a secret
API_PATH: Final = "/api/v2/reservationaccounting/"
PAGE_SIZE: Final = 250 # maximum page size of this endpoint
REQUEST_TIMEOUT_SECONDS: Final = 60
ALLOWED_URL_SCHEMES: Final = ("https", "http")
CSV_COLUMNS: Final = (
"id",
"state",
"reservation_start",
"reservation_end",
"start_real",
"end_real",
"start_booked",
"end_booked",
"distance",
"vehicle_id",
"owner_id",
"created",
"modified",
)
class Vehicle(TypedDict):
"""Vehicle as embedded in a reservation (only the id is exported)."""
id: int
class Owner(TypedDict):
"""User who made the reservation (only the id is exported)."""
id: int
class Reservation(TypedDict, total=False):
"""The subset of the API response fields that this script exports."""
id: int
state: str
reservation_start: str
reservation_end: str
start_real: str | None
end_real: str | None
start_booked: str
end_booked: str
distance: float | None
vehicle: Vehicle | None
owner: Owner | None
created: str
modified: str
class Page(TypedDict):
"""One page of the paginated API response."""
count: int
next: str | None
previous: str | None
results: list[Reservation]
@dataclass(frozen=True)
class ExportSettings:
"""Everything one export run needs."""
base_url: str
token: str
period_start: datetime
period_end: datetime
output_path: Path
class ExportError(Exception):
"""Raised when the export cannot be completed."""
def parse_month(value: str) -> tuple[datetime, datetime]:
"""Return the UTC start of the given month (YYYY-MM) and the start of the next month."""
try:
start = datetime.strptime(value, "%Y-%m").replace(tzinfo=UTC)
except ValueError as error:
raise argparse.ArgumentTypeError(f"invalid month {value!r}, expected YYYY-MM") from error
# Day 28 + 4 days always lands in the next month; then go to its first day.
next_month_start = (start.replace(day=28) + timedelta(days=4)).replace(day=1)
return start, next_month_start
def format_utc(moment: datetime) -> str:
"""Format a datetime as an ISO 8601 UTC timestamp, e.g. 2026-01-01T00:00:00Z."""
return moment.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
def parse_settings(argv: list[str] | None = None) -> ExportSettings:
"""Read the command line arguments and the API token from the environment."""
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--organization", required=True, help="your ZEMTU subdomain, e.g. carsharing")
parser.add_argument("--month", required=True, type=parse_month, help="month to export, e.g. 2026-01")
parser.add_argument("--output", type=Path, help="CSV file to write (default: reservations-YYYY-MM.csv)")
parser.add_argument("--base-url", help="override the API base URL (default: https://ORGANIZATION.zemtu.com)")
arguments = parser.parse_args(argv)
token = os.environ.get(TOKEN_ENV_VAR, "").strip()
if not token:
parser.error(f"set the API token in the environment variable {TOKEN_ENV_VAR}")
base_url = cast("str | None", arguments.base_url) or f"https://{arguments.organization}.zemtu.com"
if urllib.parse.urlsplit(base_url).scheme not in ALLOWED_URL_SCHEMES:
parser.error("--base-url must start with https:// (or http:// for local testing)")
period_start, period_end = cast("tuple[datetime, datetime]", arguments.month)
output_path = cast("Path | None", arguments.output) or Path(f"reservations-{period_start:%Y-%m}.csv")
return ExportSettings(
base_url=base_url.rstrip("/"),
token=token,
period_start=period_start,
period_end=period_end,
output_path=output_path,
)
def build_first_page_url(settings: ExportSettings) -> str:
"""Build the URL of the first page, filtered to reservations starting in the period."""
query = urllib.parse.urlencode(
{
"reservation_start__gte": format_utc(settings.period_start),
"reservation_start__lt": format_utc(settings.period_end),
"ordering": "reservation_start",
"page_size": PAGE_SIZE,
}
)
return f"{settings.base_url}{API_PATH}?{query}"
def fetch_page(url: str, token: str) -> Page:
"""Fetch one page of results. Any HTTP error status raises ExportError."""
request = urllib.request.Request( # noqa: S310 - see ALLOWED_URL_SCHEMES
url,
headers={"Authorization": f"Token {token}", "Accept": "application/json"},
)
try:
# The scheme is restricted to http(s) in parse_settings and `next` links come from the same API.
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response: # noqa: S310
payload: object = json.load(response)
except urllib.error.HTTPError as error: # non-2xx status
detail = error.read().decode("utf-8", errors="replace")[:500]
raise ExportError(f"HTTP {error.code} for {url}: {detail}") from error
except urllib.error.URLError as error:
raise ExportError(f"could not reach {url}: {error.reason}") from error
except (TimeoutError, json.JSONDecodeError) as error:
raise ExportError(f"invalid or no response from {url}: {error}") from error
if not isinstance(payload, dict) or not isinstance(payload.get("results"), list):
raise ExportError(f"unexpected response format from {url}")
return cast("Page", payload)
def iter_reservations(settings: ExportSettings) -> Iterator[Reservation]:
"""Yield every reservation of the period, following the `next` link page by page."""
next_url: str | None = build_first_page_url(settings)
while next_url:
page = fetch_page(next_url, settings.token)
yield from page["results"]
next_url = page["next"]
def to_csv_row(reservation: Reservation) -> dict[str, object]:
"""Flatten one reservation into the CSV columns."""
vehicle = reservation.get("vehicle")
owner = reservation.get("owner")
row: dict[str, object] = {column: reservation.get(column) for column in CSV_COLUMNS}
row["vehicle_id"] = vehicle["id"] if vehicle else None
row["owner_id"] = owner["id"] if owner else None
return row
def write_csv(reservations: Iterator[Reservation], output_path: Path) -> int:
"""Write the reservations to a CSV file (UTF-8 with BOM for Excel) and return the row count.
The data is written to a temporary file first, so a failed export never leaves a half-written CSV behind.
"""
partial_path = output_path.with_name(f"{output_path.name}.partial")
row_count = 0
try:
with partial_path.open("w", newline="", encoding="utf-8-sig") as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=CSV_COLUMNS)
writer.writeheader()
for reservation in reservations:
writer.writerow(to_csv_row(reservation))
row_count += 1
except BaseException:
partial_path.unlink(missing_ok=True)
raise
partial_path.replace(output_path)
return row_count
def main(argv: list[str] | None = None) -> int:
"""Run the export and return the process exit code."""
settings = parse_settings(argv)
try:
row_count = write_csv(iter_reservations(settings), settings.output_path)
except ExportError as error:
print(f"Export failed: {error}", file=sys.stderr)
return 1
print(f"{row_count} reservations written to {settings.output_path}")
return 0
if __name__ == "__main__":
sys.exit(main())
Usage hints
After a reservation is finished,
end_realis the Precise end,end_bookedis the Snapped end andreservation_endis the Date end shown in the calendar. Useend_bookedandend_realfor clearing.reservation_endis for display only. Before the reservation is finished,end_bookedequalsreservation_end. See Reservation end times: Precise end, Snapped end and Date end.When
end_real>end_bookedthe reservation was overdrawn — extra fees might apply.The field
versionscontains the whole history of a reservation. Loop over it to detect whether it was deleted or changed in a time span where extra fees might apply.Deleted reservations stay in the result set — use
state=deletedorstate__in=...to handle them explicitly.For recurring exports, filter on
modified__gtewith the timestamp of the last run instead of re-fetching everything.
Reservation states
Further reading
Interactive API documentation (all endpoints, fields and filters):
https://YOUR_ORGANIZATION.zemtu.com/docsTokenAuthentication: https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
What Precise end, Snapped end and Date end mean: Reservation end times: Precise end, Snapped end and Date end
Choosing an export method: Exporting large amounts of reservations