Skip to main content
API

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.com in this documentation. Always replace carsharing with your subdomain: https://YOUR_ORGANIZATION.zemtu.com

  • Serialization 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 9944b19199c62bgf9418td846dd0e4bzdfc6de9b

There 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: 250

  • A custom page size can be set with ?page_size=250; a specific page with &page=2. The simplest export strategy is to follow the next URL until it is null.

Endpoints for exporting reservations

Endpoint

Description

Access

/api/v2/reservation/

Complete reservation objects as shown in the UI. Returns reservations the user is allowed to view.

Read & Write

/api/v2/reservationaccounting/

Reservation data for accounting: real start/end, booked end, distance, odometer, version history, fees. Best suited for exports for billing and statistics.

Read-only

/api/v2/reservationreporting/

The user's own reservations including a trip report (distance, overdrawn time, trip segments).

Read-only

/api/v2/vehicle/

Vehicle master data (id, type, location).

Read-only

/api/v2/user/

User data. Users with the "User" role can only retrieve themselves; org admins can retrieve all users of the organization.

Read-only

Hint: the trailing / is important for detail endpoints, e.g. /api/v2/reservation/{ID}/.

Filtering

The reservation and reservation accounting endpoints support these filters:

Filter

Description

created__gte, created__lte

Creation date range of the reservation

modified__gte, modified__lte

Last change to the reservation (also considers workflow transitions triggered by the OBU)

reservation_start__gte/__gt/__lte/__lt

Reservation start range

reservation_end__gte/__gt/__lte/__lt

Reservation end range

state

Exact workflow state: opened, protected, closed, deleted

state__in

Several states, e.g. state__in=closed,deleted

vehicle

Vehicle id

vehicle__in

Several vehicle ids, e.g. vehicle__in=201,202

owner

User id of the reservation owner

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:00Z

  • Closed or deleted reservations: ?state__in=closed,deleted

  • Reservations of vehicle 201: ?vehicle=201

  • Reservations owned by user 1550: ?owner=1550

  • Reservations 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)

Field

Type

Description

id

integer

Unique identifier of the reservation

created, modified

datetime

Creation / last change of the reservation

reservation_start, reservation_end

datetime

Start/end displayed in the UI (snapped to the booking slot)

start_booked, end_booked

datetime

Booked start/end relevant for billing

start_real, end_real

datetime

Real start (e.g. early access) / actual return time

start_first_tripsegment, end_last_tripsegment

datetime

Start of first / end of last recorded trip segment

purpose

integer

0 personal, 10 business

note, note_billing

text

Reservation note / billing note

lift_offer

boolean

Offering a lift?

state

text

Workflow state (see below)

owner

object

id, external_user_id, additional_data of the reservation owner

vehicle

object

id, type, label, brand, model, address1, city, zip, timezone

distance

float

Distance driven in km

odometer_start, odometer_end

float

Odometer readings at start/end

fees_data

object

Calculated fee data for the reservation

tags

list

Tags assigned to the reservation

versions

list

All versions of the reservation in descending order, including the current version — the complete history (fields: lift_offer, modified, note, reservation_start, reservation_end, purpose, state)

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": null

Example: 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-01

Month 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_real is the Precise end, end_booked is the Snapped end and reservation_end is the Date end shown in the calendar. Use end_booked and end_real for clearing. reservation_end is for display only. Before the reservation is finished, end_booked equals reservation_end. See Reservation end times: Precise end, Snapped end and Date end.

  • When end_real > end_booked the reservation was overdrawn — extra fees might apply.

  • The field versions contains 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=deleted or state__in=... to handle them explicitly.

  • For recurring exports, filter on modified__gte with the timestamp of the last run instead of re-fetching everything.

Reservation states

State

Description

opened

Initial state when a new reservation is created. It is allowed to modify and delete the reservation. Allowed transitions: → protected, → deleted

protected

Reservation has been started — triggered when the OBU confirmed the start. No more changes to the reservation start allowed. Allowed transitions: → closed

closed

Reservation has ended — triggered when the OBU sends the final trip data. No more changes to start and end allowed.

deleted

Reservation has been deleted.

Further reading

Was this helpful?

Still need help? Share an idea