Documentation Index
Fetch the complete documentation index at: https://samsara-showcase.mintlify.app/llms.txt
Use this file to discover all available pages before exploring further.
This recipe creates a routes.csv file that summarizes routes scheduled in the last 24 hours.
import csv
import datetime
import os
import requests
token = os.environ["SAMSARA_API_TOKEN"]
with open("routes.csv", "w", newline="") as csv_file:
fieldnames = [
"Assigned To",
"Route",
"Scheduled Start",
"Route Timeliness",
"Current Status",
"Current Destination",
]
csv_dict_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
csv_dict_writer.writeheader()
pagination = {"hasNextPage": True, "endCursor": ""}
now = datetime.datetime.now(datetime.timezone.utc)
start_time = (now - datetime.timedelta(days=1)).isoformat().replace("+00:00", "Z")
end_time = now.isoformat().replace("+00:00", "Z")
while pagination["hasNextPage"]:
response = requests.request(
"GET",
"https://api.samsara.com/fleet/routes",
params={
"startTime": start_time,
"endTime": end_time,
"after": pagination["endCursor"],
},
headers={"Authorization": "Bearer " + token},
).json()
pagination = response["pagination"]
for route in response["data"]:
row = {}
if "driver" in route:
row["Assigned To"] = route["driver"]["name"] + " (Driver)"
elif "vehicle" in route:
row["Assigned To"] = route["vehicle"]["name"] + " (Vehicle)"
else:
row["Assigned To"] = "Unassigned"
row["Route"] = route["name"]
row["Scheduled Start"] = route["scheduledRouteStartTime"]
if "actualRouteStartTime" not in route:
scheduled_end = datetime.datetime.fromisoformat(route["scheduledRouteEndTime"].replace("Z", "+00:00"))
row["Route Timeliness"] = "Skipped" if scheduled_end < now else "Scheduled"
elif "actualRouteEndTime" in route:
row["Route Timeliness"] = "Completed"
else:
for stop in route["stops"]:
if stop["state"] == "en route":
row["Current Destination"] = "TO " + stop["name"]
row["Current Status"] = "ETA " + stop["eta"]
eta = datetime.datetime.fromisoformat(stop["eta"].replace("Z", "+00:00"))
scheduled_arrival = datetime.datetime.fromisoformat(stop["scheduledArrivalTime"].replace("Z", "+00:00"))
row["Route Timeliness"] = "On time" if eta <= scheduled_arrival else str(eta - scheduled_arrival) + " late"
elif stop["state"] == "arrived":
row["Current Destination"] = "AT " + stop["name"]
row["Current Status"] = "ARR " + stop["actualArrivalTime"]
actual_arrival = datetime.datetime.fromisoformat(stop["actualArrivalTime"].replace("Z", "+00:00"))
scheduled_arrival = datetime.datetime.fromisoformat(stop["scheduledArrivalTime"].replace("Z", "+00:00"))
row["Route Timeliness"] = "On time" if actual_arrival <= scheduled_arrival else str(actual_arrival - scheduled_arrival) + " late"
csv_dict_writer.writerow(row)
How it works
Create the CSV file
The report includes the route assignment, route name, scheduled start, route timeliness, current status, and current destination.
Initialize pagination
The script starts with hasNextPage set to True and endCursor set to an empty string so it can request the first page.
Set the time range
The sample retrieves routes scheduled within the last 24 hours using RFC 3339 timestamps in UTC.
Call GET /fleet/routes
Provide startTime, endTime, and after query parameters while paging through results.
Parse the assignment
Routes can be assigned to a driver, assigned to a vehicle, or unassigned.
Determine route status
The script labels routes as Scheduled, Skipped, Completed, On time, or late based on route and stop timestamps.
Handle in-progress routes
For routes in progress, the current stop is the stop in the en route or arrived state.
Write each row
After the script processes a route, it writes the row to routes.csv.
See Routing for more details about routes and stop states.