For developers

API and MCP

Bring the fleet's data into your own systems, or let an AI agent answer questions about it. Same key, same data, two ways to reach it.

Overview

JSON-API

For systems

Regular HTTP requests that respond with JSON. For payroll systems, business systems, reports and your own scripts.

https://fordonskollen.com/api/v1

MCP

For AI agents

An MCP server that gives Claude and other AI assistants tools for reading the fleet. You ask in plain language.

https://fordonskollen.com/mcp

  • Read-only. A key cannot change or delete anything.
  • One key, one organisation. The key only sees the organisation it was created in.
  • Included in Bas+. Contact us and we will tell you more.

Get started

  1. Create a key

    Sign in as owner or administrator and open API in the side menu. Give the key a name that says what it is used for and copy it right away. It is shown only once.

    The key starts with fordonskollen_ and is valid for one year. You can revoke it at any time.

  2. Make a first request

    Send the key in the Authorization header with every request:

    curl "https://fordonskollen.com/api/v1/vehicles?page[limit]=2" \
      -H "Authorization: Bearer fordonskollen_DIN_NYCKEL" \
      -H "Accept: application/vnd.api+json"
  3. Read the response

    The response follows the JSON:API standard. The rows are in data, and each row has id, type and attributes:

    {
      "data": [
        {
          "id": "3e26ddcd-2858-4771-91a2-6da8f1f302d1",
          "type": "vehicle",
          "attributes": {
            "registration_number": "ABC123",
            "brand": "Volvo",
            "model": "V60",
            "status": "yellow",
            "inspection_date": "2026-12-01"
          }
        }
      ],
      "links": { "next": "…" }
    }

A machine-readable OpenAPI specification is available at https://fordonskollen.com/api/v1/open_api (requires a key).

Connect an AI agent

MCP (Model Context Protocol) is an open standard for giving AI assistants access to tools. Once the server is added, the assistant can fetch what it needs to answer on its own.

Claude Code

claude mcp add --transport http fordonskollen https://fordonskollen.com/mcp \
  --header "Authorization: Bearer fordonskollen_DIN_NYCKEL"

Other MCP clients

Most clients take a configuration in this format. The transport is HTTP and the key is sent as a header:

{
  "mcpServers": {
    "fordonskollen": {
      "type": "http",
      "url": "https://fordonskollen.com/mcp",
      "headers": {
        "Authorization": "Bearer fordonskollen_DIN_NYCKEL"
      }
    }
  }
}

The tools

Tools Returns
list_vehicles Vehicles – same fields as /api/v1/vehicles
list_trips Trips – same fields as /api/v1/trips
list_drivers Drivers – same fields as /api/v1/drivers
latest_vehicle_positions Latest position – same fields as /api/v1/positions
list_site_visits Visits (time on site) – same fields as /api/v1/site_visits
list_sites Sites – same fields as /api/v1/sites
list_geozones Geozones – same fields as /api/v1/geozones

Each tool can filter, sort, limit the number of rows and count or sum a field. The agent chooses on its own.

Questions to start with

  • Which vehicles are due for inspection in the next 30 days?
  • How many kilometres of business trips did we drive in October, per vehicle?
  • Which trips from last week are not classified yet?
  • Where are our vehicles right now?

What data you can get

The lists below are complete and come straight from the system: if a field is not here, it cannot be retrieved.

Marked fields are included without asking. Request the others with the fields parameter.

How trips are formed and why their times can differ from time on site: Trips and sites.

Vehicles

The vehicle register: what you have entered yourselves, plus registry data from the Swedish Transport Agency that is updated automatically. Sold vehicles remain and have a date in sold_at.

List
GET /api/v1/vehicles
One row
GET /api/v1/vehicles/:id
MCP tool
list_vehicles

Identity

Field Type Description
id uuid
registration_number string
brand string
model string
name string Your own name for the vehicle.
variant string
version string
year integer
vehicle_year integer
vehicle_type car | truck | light_truck | motorcycle | tractor | trailer | motorized_equipment | bus
color string
vin string
chassi string

Status and operation

Field Type Description
status red | yellow | green | grey The inspection traffic light: red = overdue, yellow = due soon, green = done, grey = information missing.
registry_status string Status in the road traffic registry, for example in traffic or off the road.
inspection_date date Latest date for the next inspection.
last_inspection_date date
next_service_date date
insurance_expiry date
insurance_number string
mileage integer Odometer reading in km, latest known.
location string Town or place you have entered for the vehicle.
sold_at date Date the vehicle was sold. Empty for vehicles in service.
group_id uuid The vehicle group the vehicle belongs to, if any.

Registration

Field Type Description
registered_date date
manufactured_date date
aquired_date date
number_of_owners integer
reused_registration boolean
pending_registration_action deregister | reregister A started deregistration or re-registration awaiting the Swedish Transport Agency.
pending_registration_action_started_at datetime
pending_registration_action_acknowledged_at datetime
pending_registration_action_acknowledged_by_id uuid
registration_action_discrepancy deregister | reregister
registration_action_discrepancy_at datetime
last_api_update datetime When the registry data was last fetched.

Tax

Field Type Description
yearly_tax integer Vehicle tax per year, in SEK.
malus_tax integer
tax_months integer[] Months when the vehicle tax is due, 1–12.

Engine and drivetrain

Field Type Description
fuel_type string
drive_fuel string
transmission string
power_hp integer
drive_power_kw decimal
drive_power_hp integer
cylinder_volume integer
top_speed integer
tank_volume decimal

Consumption and environment

Field Type Description
co2_emissions integer
drive_co2 integer
co2_city integer
co2_highway integer
co2_combined integer
consumption_city decimal
consumption_highway decimal
consumption_combined decimal
eco_class_eu string
emission_class string
drive_sound_stationary decimal
drive_sound_driving decimal

Dimensions, weight and tyres

Field Type Description
width integer
length integer
height integer
kerb_weight integer
gross_weight integer
trailer_weight integer
unbreaked_trailer_weight integer
tyre_dimension_front string
tyre_dimension_rear string
rim_dimension_front string
rim_dimension_rear string

Other

Field Type Description
forarsparning boolean

Trips

The driving log: one row per trip, created automatically when the vehicle starts and stops, with start and end location as address and GPS coordinate. For trips the driver has classified as private, address and coordinates are missing from the response altogether. Classification, purpose and driver exist only for vehicles with driver tracking turned on; other vehicles have a plain driving log and those fields are missing from the response.

List
GET /api/v1/trips
One row
GET /api/v1/trips/:id
MCP tool
list_trips
Field Type Description
id uuid
started_at datetime When the trip started (UTC).
ended_at datetime When the trip ended. Empty while the trip is in progress.
start_odometer_m integer The tracker's own odometer in metres. Basis for distance_m.
end_odometer_m integer The tracker's own odometer in metres. Basis for distance_m.
distance_m integer Distance driven in metres.
start_can_odometer_km integer The car's own odometer reading in km. Empty if the car does not report it.
end_can_odometer_km integer The car's own odometer reading in km. Empty if the car does not report it.
start_fuel_used_raw integer Raw value of the fuel counter. The scale depends on fuel_counter_model.
end_fuel_used_raw integer Raw value of the fuel counter. The scale depends on fuel_counter_model.
fuel_counter_model fmc003 | fmc650 | ftc961
purpose tjanst | privat The driver's classification: tjanst (business) or privat (private). Empty = not classified yet. Missing for vehicles without driver tracking.
syfte string The driver's free text about the errand, 200 characters at most.
start_lat number GPS coordinate (WGS84). Missing for private trips.
start_lng number GPS coordinate (WGS84). Missing for private trips.
end_lat number GPS coordinate (WGS84). Missing for private trips.
end_lng number GPS coordinate (WGS84). Missing for private trips.
start_address string Street address. Missing for private trips.
end_address string Street address. Missing for private trips.
start_geokodning_status vantande | klar | ingen_adress | misslyckad Whether the address lookup is done, pending or has no address.
end_geokodning_status vantande | klar | ingen_adress | misslyckad Whether the address lookup is done, pending or has no address.
geokodning_forsokt_at datetime
driver_assignment_status unverified | preliminary | confirmed | disputed How certain the driver assignment is: unverified, preliminary, confirmed or disputed.
driver_assignment_source automatic_ble | manual_session | manual_driver | manual_admin How the driver was linked to the trip: automatically or manually.
driver_assigned_at datetime
driver_queue_since datetime
vehicle_id uuid The vehicle that was driven. Same id as in Vehicles.
driver_id uuid The driver, if the trip has one. Same as user_id in Drivers.
driver_name string The driver's name.

Drivers

The organisation's drivers. Of the personal data, only the name is released. Email, phone and driving licence details cannot be retrieved.

List
GET /api/v1/drivers
One row
GET /api/v1/drivers/:id
MCP tool
list_drivers
Field Type Description
id uuid
all_vehicles boolean True if the driver sees all the organisation's vehicles in the app.
track servicebil | formansbil Tax track: servicebil (service vehicle) or formansbil (company car).
invited_at datetime When the driver was invited.
accepted_at datetime When the driver activated their account.
ended_at datetime When the driver was ended. Empty for active drivers.
user_id uuid Same as driver_id in Trips.
name string The driver's name.
status string invited = invited, active = has signed in, ended = ended.

Latest position

The latest position with a GPS fix for each vehicle with a tracker. Always one row per vehicle. If the tracker has no fix, for example in a garage or a tunnel, the vehicle stays at its latest position with a fix, and recorded_at shows how old it is. Position history and driven routes cannot be fetched. For a map that updates: send ?since= with meta.next_since from the previous response, and only vehicles that have moved since then are returned. No changes give an empty list. The same vehicle can occasionally appear twice in a row; then just replace its position. Every response has an ETag: send it in If-None-Match next time, and the server answers 304 with no body if nothing has changed. A 304 counts as a request.

List
GET /api/v1/positions
MCP tool
latest_vehicle_positions
Field Type Description
id uuid
imei string The tracker's serial number.
recorded_at datetime When the position was measured (UTC).
lat number Coordinate (WGS84).
lng number Coordinate (WGS84).
speed integer Speed in km/h.
altitude integer Altitude in metres.
angle integer Heading in degrees, 0 = north.
ignition boolean True if the ignition was on.
movement boolean True if the vehicle was moving. Empty if unknown.
odometer_m integer The tracker's own odometer in metres.
can_odometer_km integer The car's own odometer reading in km. Empty if the car does not report it.
fuel_used_raw integer Raw value of the fuel counter.
satellites integer Number of satellites the tracker saw. Empty for older positions.
gnss_fix boolean True if the tracker had a GPS fix. Empty for older positions. Positions without a fix are never returned here.
received_at datetime When Fordonskollen received the position (UTC). Later than recorded_at if the tracker was out of coverage. This is the time that ?since= compares against.
vehicle_id uuid The vehicle. Same id as in Vehicles.

Visits (time on site)

A vehicle's visit to a site, from arrival to departure, calculated from GPS. Time with the ignition on at the site, such as queueing and idling, is also part of a trip, so do not add visits and trips together. Visits connected to private trips have the times, but never the site, address or position. How visits are calculated is explained on the Trips and sites page.

List
GET /api/v1/site_visits
One row
GET /api/v1/site_visits/:id
MCP tool
list_site_visits
Field Type Description
id uuid
arrived_at datetime Arrival (UTC).
departed_at datetime Departure (UTC). Empty while the vehicle is still there.
lat number Where the vehicle stood (WGS84). Missing for visits connected to private trips.
lng number Where the vehicle stood (WGS84). Missing for visits connected to private trips.
duration_s integer Total time on site in seconds.
ignition_on_s integer Of which ignition on, in seconds. The same time is also part of a trip.
ignition_off_s integer Of which ignition off, in seconds.
idle_s integer Of which idling, in seconds: standing still with the ignition on for at least 60 seconds at a stretch.
quality ok | degraded ok, or degraded when GPS was poor during the visit and the times are less certain.
algorithm_version integer The version of the rule that calculated the visit.
vehicle_id uuid The vehicle. Same id as in Vehicles.
site_id uuid The site. Same id as in Sites. Missing for visits connected to private trips.
geozone_id uuid The geozone, for visits in a zone you drew. Same id as in Geozones.
arriving_trip_id uuid The trip that ended at the site, if there is one. Same id as in Trips.
departing_trip_id uuid The trip that started at the site, if there is one. Same id as in Trips.
address string The site's name and address. Search with ?address=, which ignores case. Missing for visits connected to private trips.

Sites

Places where the organisation's vehicles tend to stop, such as customers and warehouses. Fordonskollen learns them from the stops by itself. Use the id to filter visits to a site.

List
GET /api/v1/sites
One row
GET /api/v1/sites/:id
MCP tool
list_sites
Field Type Description
id uuid
lat number Centre point (WGS84): the median of the visits' positions.
lng number Centre point (WGS84): the median of the visits' positions.
address string Street address, looked up from the centre point.
name string Name you have given the site. Empty otherwise.

Geozones

Areas you have drawn yourselves in the app, as a circle or a polygon. Visits in a zone have the zone's id in geozone_id. The list shows the zones in effect now; an archived zone can still be fetched by its id. Zones are only created and changed in the app.

List
GET /api/v1/geozones
One row
GET /api/v1/geozones/:id
MCP tool
list_geozones
Field Type Description
id uuid
name string The zone's name.
kind circle | polygon The shape: circle or polygon.
center_lat number Centre point (WGS84). For a polygon, the centre of its bounding box.
center_lng number Centre point (WGS84). For a polygon, the centre of its bounding box.
radius_m integer The radius in metres for a circle. Empty for a polygon.
geometry object The polygon as GeoJSON, with coordinates in [lng, lat] order. Empty for a circle.
show_passages boolean True if short visits under 2 minutes are counted too, for example at a gate.
archived_at datetime When the zone was archived. Empty for an active zone.

Never released

The protection sits in the data layer and applies to every key. It cannot be switched off or bypassed with filters.

  • Where private trips went. Trips the driver has classified as private show time and distance, never address or coordinates. Business trips and trips not yet classified have start and end location.
  • Position history and routes. Only the latest position per vehicle can be retrieved.
  • The driver's contact details and driving licence. Of the personal data, only the name is released.
  • The driver's own settings. Choices about private driving and classification rules belong to the driver.
  • The vehicle's authorisation code and internal comment. The code for the Swedish Transport Agency and your free text stay in the app.
  • Documents, notes, fault reports and fault codes. Not available in the API in this version.

Filter, sort, paginate

You want Parameter
Only certain fields fields[vehicle]=registration_number,status
Exact value filter[purpose]=tjanst
Comparison filter[started_at][greater_than_or_equal]=2026-11-01T00:00:00Z
Has no value filter[sold_at][is_nil]=true
Sort, newest first sort=-started_at
Page size (200 at most) page[limit]=100
Skip rows page[offset]=100
Total count in the response page[count]=true

Comparisons: eq, not_eq, in, greater_than, greater_than_or_equal, less_than, less_than_or_equal, is_nil, contains

Vehicles, trips and drivers are paginated when you pass page[limit]. The response then has a link in links.next to the next page. Follow it until it is empty. Without page[limit], all rows come in one response.

# Tjänsteresor i november, nyast först, 100 per sida
curl -G "https://fordonskollen.com/api/v1/trips" \
  -H "Authorization: Bearer fordonskollen_DIN_NYCKEL" \
  -H "Accept: application/vnd.api+json" \
  --data-urlencode "filter[purpose]=tjanst" \
  --data-urlencode "filter[started_at][greater_than_or_equal]=2026-11-01T00:00:00Z" \
  --data-urlencode "filter[started_at][less_than]=2026-12-01T00:00:00Z" \
  --data-urlencode "sort=-started_at" \
  --data-urlencode "page[limit]=100"

Live map: positions in real time

A map that follows the vehicles does not need to ask over and over. Open a stream, and Fordonskollen sends every new position as soon as it arrives. These are the same updates Fordonskollen's own map receives.

  • First a snapshot. The snapshot event has the latest position of every vehicle. It comes again on every reconnect, so you never miss anything.
  • Then one event per movement. The position event has the same fields as /api/v1/positions. Replace the vehicle's marker with the new one. It only arrives when the vehicle has a new position with a GPS fix; in a garage or a tunnel the marker stays put.
  • A sign of life every 20 seconds. The line : ping keeps the connection open. It carries no data and can be ignored.
  • The stream is sometimes closed, on purpose. The closed event comes last and says why: max_lifetime after 30 minutes, or superseded when a fourth stream was opened with the same key. Then reconnect with the same key. In the browser you need a new stream ticket, see below.
# Från en server: samma nyckel som resten av API:t. -N stänger av buffring.
curl -N "https://fordonskollen.com/api/v1/positions/stream" \
  -H "Authorization: Bearer fordonskollen_DIN_NYCKEL"

event: snapshot
data: [{"vehicle_id":"3e26…","lat":57.70887,"lng":11.97456,"speed":0,…}]

event: position
data: {"vehicle_id":"3e26…","lat":57.70912,"lng":11.97501,"speed":34,…}

: ping

In the browser

Never put the API key in the browser. Let your own server exchange it for a stream ticket, and open the stream with the ticket. The ticket is valid for five minutes for connecting, so fetch a new one every time the stream is opened again, for example after closed. The key never needs to change. The stream may be opened from any website.

// 1. Er server byter nyckeln mot en biljett (gäller i 5 minuter):
//    POST https://fordonskollen.com/api/v1/positions/stream-tickets
//    Authorization: Bearer fordonskollen_DIN_NYCKEL
//    -> {"ticket": "…", "expires_at": "…"}

// 2. Webbläsaren öppnar strömmen med biljetten:
const stream = new EventSource(
  "https://fordonskollen.com/api/v1/positions/stream?ticket=" + encodeURIComponent(ticket)
);

stream.addEventListener("snapshot", (e) => JSON.parse(e.data).forEach(place));
stream.addEventListener("position", (e) => place(JSON.parse(e.data)));

// 3. Strömmen stängs efter 30 minuter (event: closed) eller bryts av
//    nätet. Hämta då en ny biljett och öppna igen. Nyckeln är densamma;
//    EventSource egen återanslutning duger inte, den återanvänder den
//    gamla biljetten.
stream.addEventListener("closed", () => { stream.close(); reconnect(); });
stream.onerror = () => { stream.close(); setTimeout(reconnect, 5000); };

The Live map example further down is a complete program that does exactly this.

When a stream is not possible

If your system cannot keep a connection open: query /api/v1/positions with ?since= and send meta.next_since from the previous response. Only vehicles that have moved since then are returned, and an empty response if nothing happened. A vehicle may occasionally appear twice. Just replace its position.

# Första gången: alla fordon. Spara meta.next_since ur svaret.
curl "https://fordonskollen.com/api/v1/positions" -H "Authorization: Bearer fordonskollen_DIN_NYCKEL"

# Därefter: bara fordon som rört sig sedan dess. Tom lista om inget hänt.
curl -G "https://fordonskollen.com/api/v1/positions" \
  -H "Authorization: Bearer fordonskollen_DIN_NYCKEL" \
  --data-urlencode "since=2026-11-23T09:15:00.000000Z"

Webhooks: requests when something happens

Can your system not keep a stream open, but you want to know when a trip starts or ends? Add a webhook under API in the app. Fordonskollen then calls your address with a POST for every event.

  • Events: trip.started and trip.ended. More events, such as alarms, will come later.
  • Only ids, no personal data. The request says what happened and to which trip and vehicle. Fetch the details with /api/v1/trips/{id}. The usual rules apply there, for example that private trips have no addresses.
  • Respond with 2xx within 10 seconds. Otherwise Fordonskollen tries again, waiting longer each time, up to 8 times. The same event has the same id on every attempt, so you can skip duplicates.
  • The address must start with https://. Redirects are not followed.
POST https://er-server.se/fordonskollen
Content-Type: application/json
Fordonskollen-Event: trip.ended
Fordonskollen-Delivery: 5b0c1e1a-…
Fordonskollen-Signature: t=1795431600,v1=3f9a…

{
  "id": "5b0c1e1a-…",
  "event": "trip.ended",
  "occurred_at": "2026-11-23T08:41:12.000000Z",
  "data": { "trip_id": "c71e…", "vehicle_id": "3e26…" }
}

Check the signature

Every webhook gets a secret that is shown once when it is created. The Fordonskollen-Signature header contains the time t and v1, an HMAC-SHA256 with the secret over t, a dot and the unmodified body. Compute the same value and compare. Reject requests older than a few minutes.

// Node.js: kontrollera signaturen innan ni litar på anropet.
import { createHmac, timingSafeEqual } from "node:crypto";

function verify(rawBody, header, secret) {
  const { t, v1 } = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return false; // äldre än 5 min
  const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
  return timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
}

Errors and limits

Code Means What to do
400 Unknown field or invalid filter. Check the field name against the lists above.
401 The key is missing, wrong, revoked or expired. Create a new key in the app.
403 API access is not included in the organisation's plan. Contact us about Bas+.
404 The row does not exist, or belongs to another organisation. Check the id.
429 Too many requests. Wait the number of seconds given in the Retry-After header.
  • 60 requests per minute per key. Applies to the JSON API and MCP combined.
  • At most 3 open streams per key. Opening a fourth closes the oldest. An open stream does not count against the per-minute limit. Opening it and fetching tickets does.
  • Ten wrong keys in a minute block the sender for a while. Requests with a correct key from the same address are also refused in the meantime.
  • Times are in UTC. Convert to local time in your own system.

Example projects

Four finished programs to download and build on. No packages to install. Set the key as an environment variable and run.

export FORDONSKOLLEN_API_KEY=fordonskollen_DIN_NYCKEL

Python

Driving log to CSV

Download

Fetches a month of trips and writes a CSV file for Excel or the payroll system. Shows time filters, sorting and pagination.

python3 korjournal_till_csv.py 2026-11
Show the code · korjournal_till_csv.py
#!/usr/bin/env python3
"""Körjournal till CSV - exempel för Fordonskollens JSON-API.

Hämtar en månads resor och skriver dem till en CSV-fil som går att öppna i
Excel. Behöver bara Python 3.8+, inga extra paket.

    export FORDONSKOLLEN_API_KEY=fordonskollen_...
    python3 korjournal_till_csv.py 2026-11

Privata resor kommer med tid och sträcka men utan plats: API:t lämnar
aldrig ut adress eller koordinater för dem.
"""
import csv
import json
import os
import sys
import urllib.parse
import urllib.request
from datetime import date

BASE_URL = os.environ.get("FORDONSKOLLEN_URL", "https://fordonskollen.com")
API_KEY = os.environ.get("FORDONSKOLLEN_API_KEY")


def get(path_and_query):
    request = urllib.request.Request(
        BASE_URL + path_and_query,
        headers={
            "Authorization": "Bearer " + API_KEY,
            "Accept": "application/vnd.api+json",
        },
    )
    with urllib.request.urlopen(request) as response:
        return json.load(response)


def all_pages(path, params):
    """Följer links.next tills allt är hämtat."""
    url = path + "?" + urllib.parse.urlencode(params)
    while url:
        body = get(url)
        yield from body["data"]
        next_link = (body.get("links") or {}).get("next")
        # Länken är absolut - behåll bara sökväg och fråga.
        url = None
        if next_link:
            parts = urllib.parse.urlsplit(next_link)
            url = parts.path + "?" + parts.query


def month_bounds(month):
    year, number = (int(part) for part in month.split("-"))
    start = date(year, number, 1)
    end = date(year + number // 12, number % 12 + 1, 1)
    return start.isoformat() + "T00:00:00Z", end.isoformat() + "T00:00:00Z"


def main():
    if not API_KEY or len(sys.argv) != 2:
        sys.exit("Användning: FORDONSKOLLEN_API_KEY=... python3 korjournal_till_csv.py ÅÅÅÅ-MM")

    month = sys.argv[1]
    start, end = month_bounds(month)

    vehicles = {
        vehicle["id"]: vehicle["attributes"]["registration_number"]
        for vehicle in all_pages(
            "/api/v1/vehicles",
            {"fields[vehicle]": "registration_number", "page[limit]": 200},
        )
    }

    trips = all_pages(
        "/api/v1/trips",
        {
            "filter[started_at][greater_than_or_equal]": start,
            "filter[started_at][less_than]": end,
            "sort": "started_at",
            "page[limit]": 200,
        },
    )

    filename = "korjournal-" + month + ".csv"
    labels = {"tjanst": "Tjänst", "privat": "Privat", None: "Oklassad"}
    count = 0

    # utf-8-sig: Excel läser å, ä och ö rätt.
    with open(filename, "w", newline="", encoding="utf-8-sig") as file:
        writer = csv.writer(file, delimiter=";")
        writer.writerow(
            ["Start", "Slut", "Fordon", "Förare", "Km", "Typ", "Syfte", "Från", "Till"]
        )
        for trip in trips:
            # .get(): ett fält som inte får lämnas ut saknas helt i svaret,
            # till exempel adressen på en privat resa.
            a = trip["attributes"]
            meters = a.get("distance_m")
            km = "" if meters is None else str(round(meters / 1000, 1)).replace(".", ",")
            writer.writerow(
                [
                    a["started_at"],
                    a.get("ended_at") or "",
                    vehicles.get(a.get("vehicle_id"), ""),
                    a.get("driver_name") or "",
                    km,
                    labels.get(a.get("purpose"), a.get("purpose")),
                    a.get("syfte") or "",
                    a.get("start_address") or "",
                    a.get("end_address") or "",
                ]
            )
            count += 1

    print(str(count) + " resor skrivna till " + filename)


if __name__ == "__main__":
    main()

Node

Inspection watch

Download

Lists vehicles due for inspection within a number of days. Run it every week and send the result to email, Slack or Teams.

node besiktningsbevakning.mjs 30
Show the code · besiktningsbevakning.mjs
#!/usr/bin/env node
// Besiktningsbevakning - exempel för Fordonskollens JSON-API.
//
// Listar de fordon som ska besiktas inom ett antal dagar, närmast först.
// Kör den varje måndag och skicka resultatet dit ni vill: mejl, Slack, Teams.
// Behöver Node 18 eller senare, inga extra paket.
//
//   export FORDONSKOLLEN_API_KEY=fordonskollen_...
//   node besiktningsbevakning.mjs 30

const BASE_URL = process.env.FORDONSKOLLEN_URL ?? "https://fordonskollen.com";
const API_KEY = process.env.FORDONSKOLLEN_API_KEY;
const days = Number(process.argv[2] ?? 30);

if (!API_KEY || Number.isNaN(days)) {
  console.error("Användning: FORDONSKOLLEN_API_KEY=... node besiktningsbevakning.mjs [dagar]");
  process.exit(1);
}

const today = new Date();
const limit = new Date(today.getTime() + days * 24 * 60 * 60 * 1000);
const isoDate = (date) => date.toISOString().slice(0, 10);

const params = new URLSearchParams({
  "fields[vehicle]": "registration_number,brand,model,inspection_date,status",
  "filter[inspection_date][less_than_or_equal]": isoDate(limit),
  // Sålda fordon ligger kvar i registret - hoppa över dem.
  "filter[sold_at][is_nil]": "true",
  sort: "inspection_date",
  "page[limit]": "200",
});

const response = await fetch(`${BASE_URL}/api/v1/vehicles?${params}`, {
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    Accept: "application/vnd.api+json",
  },
});

if (!response.ok) {
  // 401 = fel eller återkallad nyckel, 403 = API ingår inte i planen,
  // 429 = för många anrop (vänta det antal sekunder Retry-After anger).
  console.error(`API:t svarade ${response.status}: ${await response.text()}`);
  process.exit(1);
}

const { data } = await response.json();

if (data.length === 0) {
  console.log(`Inga fordon ska besiktas inom ${days} dagar.`);
} else {
  console.log(`Besiktning senast om ${days} dagar:\n`);
  for (const { attributes: vehicle } of data) {
    const left = Math.ceil((new Date(vehicle.inspection_date) - today) / (24 * 60 * 60 * 1000));
    const when = left < 0 ? `FÖRSENAD ${-left} dagar` : `om ${left} dagar`;
    const name = [vehicle.brand, vehicle.model].filter(Boolean).join(" ");
    console.log(
      `${vehicle.registration_number.padEnd(8)} ${vehicle.inspection_date}  ${when.padEnd(20)} ${name}`,
    );
  }
}

Node.js

Live map

Download

A map in the browser where vehicles move as soon as a new position arrives, without asking over and over. The server keeps the key and gives the browser a short-lived stream ticket.

node live_karta.mjs   # öppna http://localhost:8080
Show the code · live_karta.mjs
#!/usr/bin/env node
// Live-karta - exempel för Fordonskollens ström av positioner.
//
// Startar en liten webbserver på http://localhost:8080 med en karta där
// fordonen flyttar sig så fort en ny position kommer in. Ingen fråga var
// 15:e sekund: webbläsaren håller en ström öppen (Server-Sent Events).
//
// API-nyckeln stannar på servern. Webbläsaren får bara en strömbiljett som
// gäller i fem minuter, hämtad via /ticket nedan.
// Behöver Node 18 eller senare, inga extra paket.
//
//   export FORDONSKOLLEN_API_KEY=fordonskollen_...
//   node live_karta.mjs

import { createServer } from "node:http";

const BASE_URL = process.env.FORDONSKOLLEN_URL ?? "https://fordonskollen.com";
const API_KEY = process.env.FORDONSKOLLEN_API_KEY;
const PORT = Number(process.env.PORT ?? 8080);

if (!API_KEY) {
  console.error("Användning: FORDONSKOLLEN_API_KEY=... node live_karta.mjs");
  process.exit(1);
}

// Byter API-nyckeln mot en strömbiljett. Körs på servern - aldrig i webbläsaren.
async function fetchTicket() {
  const response = await fetch(`${BASE_URL}/api/v1/positions/stream-tickets`, {
    method: "POST",
    headers: { Authorization: `Bearer ${API_KEY}`, Accept: "application/json" },
  });

  if (!response.ok) throw new Error(`Biljetten nekades: ${response.status}`);
  return response.json();
}

const page = `<!doctype html>
<html lang="sv">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Live-karta</title>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
  <style>
    html, body, #map { height: 100%; margin: 0; }
    #status { position: absolute; z-index: 1000; top: 10px; right: 10px;
              background: white; padding: 6px 10px; font: 13px sans-serif; }
  </style>
</head>
<body>
  <div id="map"></div>
  <div id="status">Ansluter…</div>
  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
  <script>
    const BASE_URL = ${JSON.stringify(BASE_URL)};
    const map = L.map("map").setView([62, 15], 5);
    L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution: "© OpenStreetMap",
    }).addTo(map);

    const markers = new Map();
    const status = document.getElementById("status");

    function place(position) {
      const latLng = [position.lat, position.lng];
      const label = position.vehicle_id + "<br>" + new Date(position.recorded_at).toLocaleString("sv-SE");

      if (markers.has(position.vehicle_id)) {
        markers.get(position.vehicle_id).setLatLng(latLng).setPopupContent(label);
      } else {
        markers.set(position.vehicle_id, L.marker(latLng).bindPopup(label).addTo(map));
      }
    }

    let fitted = false;

    async function connect() {
      let ticket;
      try {
        // Ny biljett vid varje uppkoppling: den gäller bara i fem minuter.
        // Nyckeln är densamma hela tiden - den ligger kvar på servern.
        ({ ticket } = await fetch("/ticket").then((r) => r.json()));
      } catch {
        status.textContent = "Får ingen biljett, försöker igen…";
        return setTimeout(connect, 5000);
      }

      const stream = new EventSource(BASE_URL + "/api/v1/positions/stream?ticket=" + encodeURIComponent(ticket));

      stream.addEventListener("snapshot", (event) => {
        const positions = JSON.parse(event.data);
        positions.forEach(place);
        // Zooma bara första gången - ögonblicksbilden kommer igen vid
        // varje återanslutning.
        if (!fitted && positions.length) {
          map.fitBounds(positions.map((p) => [p.lat, p.lng]), { maxZoom: 13 });
          fitted = true;
        }
        status.textContent = positions.length + " fordon, live";
      });

      stream.addEventListener("position", (event) => place(JSON.parse(event.data)));

      // Servern stänger strömmen efter 30 minuter, eller när en nyare ström
      // tar platsen. Koppla upp direkt med en ny biljett - EventSource egen
      // återanslutning skulle använda den gamla, som har gått ut.
      stream.addEventListener("closed", () => {
        stream.close();
        connect();
      });

      // Avbrott (deploy, nätverk): stäng och koppla upp med en ny biljett.
      // Ögonblicksbilden kommer igen och fyller på.
      stream.onerror = () => {
        stream.close();
        status.textContent = "Tappade anslutningen, försöker igen…";
        setTimeout(connect, 5000);
      };
    }

    connect();
  </script>
</body>
</html>`;

createServer(async (request, response) => {
  try {
    if (request.url === "/ticket") {
      const ticket = await fetchTicket();
      response.writeHead(200, { "Content-Type": "application/json" });
      response.end(JSON.stringify(ticket));
    } else if (request.url === "/") {
      response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
      response.end(page);
    } else {
      response.writeHead(404).end();
    }
  } catch (error) {
    console.error(error.message);
    response.writeHead(502, { "Content-Type": "application/json" });
    response.end(JSON.stringify({ error: error.message }));
  }
}).listen(PORT, () => console.log(`Live-karta på http://localhost:${PORT}`));

Python

MCP client without an SDK

Download

Does what an AI agent does against the MCP server: connects, lists the tools and calls two of them. Good for understanding the protocol.

python3 mcp_klient.py
Show the code · mcp_klient.py
#!/usr/bin/env python3
"""MCP-klient utan SDK - exempel för Fordonskollens agent-API.

Visar vad en AI-agent gör mot MCP-servern: ansluter, frågar vilka verktyg som
finns och anropar två av dem. Protokollet är JSON-RPC över HTTP, så det går
att följa steg för steg. Behöver bara Python 3.8+.

    export FORDONSKOLLEN_API_KEY=fordonskollen_...
    python3 mcp_klient.py

I en riktig agent sköter klienten (Claude, ett MCP-SDK) de här stegen. Se
dokumentationen för hur du lägger till servern där.
"""
import json
import os
import sys
import urllib.request

BASE_URL = os.environ.get("FORDONSKOLLEN_URL", "https://fordonskollen.com")
API_KEY = os.environ.get("FORDONSKOLLEN_API_KEY")

request_id = 0


def call(method, params=None):
    global request_id
    request_id += 1
    payload = {"jsonrpc": "2.0", "id": request_id, "method": method}
    if params is not None:
        payload["params"] = params

    request = urllib.request.Request(
        BASE_URL + "/mcp",
        data=json.dumps(payload).encode(),
        headers={
            "Authorization": "Bearer " + API_KEY,
            "Content-Type": "application/json",
            "Accept": "application/json, text/event-stream",
        },
    )
    with urllib.request.urlopen(request) as response:
        body = json.load(response)

    if "error" in body:
        sys.exit("MCP-fel: " + json.dumps(body["error"], ensure_ascii=False))
    return body["result"]


def tool(name, arguments):
    """Anropar ett verktyg. Svaret är JSON som text, precis som agenten får det."""
    result = call("tools/call", {"name": name, "arguments": arguments})
    return json.loads(result["content"][0]["text"])


def main():
    if not API_KEY:
        sys.exit("Användning: FORDONSKOLLEN_API_KEY=... python3 mcp_klient.py")

    call(
        "initialize",
        {
            "protocolVersion": "2024-11-05",
            "capabilities": {},
            "clientInfo": {"name": "fordonskollen-exempel", "version": "1.0"},
        },
    )

    print("Verktyg:")
    for available in call("tools/list")["tools"]:
        print("  " + available["name"] + " - " + available["description"])

    # Samma filterformat som agenten använder: fält, operator, värde.
    vehicles = tool(
        "list_vehicles",
        {
            "filter": {"field": "status", "operator": "in", "value": ["red", "yellow"]},
            "sort": [{"field": "inspection_date", "direction": "asc"}],
            "limit": 10,
        },
    )
    print("\nFordon som behöver uppmärksamhet (röd eller gul status):")
    for vehicle in vehicles:
        print("  " + vehicle["registration_number"] + "  besiktning " + str(vehicle.get("inspection_date")))

    positions = tool("latest_vehicle_positions", {"limit": 5})
    print("\nSenaste positioner:")
    for position in positions:
        print("  " + position["vehicle_id"] + "  " + str(position["lat"]) + ", " + str(position["lng"]) + "  " + position["recorded_at"])


if __name__ == "__main__":
    main()

Stuck, or missing something?

Write to us and we will help you get going: info@fordonskollen.com