AIS Vessel Track API in Python: ZJ ATLANTIC 48h

AIS Vessel Track API in Python: ZJ ATLANTIC 48h

You need the last 48 hours of AIS positions for a single ship and you want to do it from Python without wrestling with raw NMEA, scrapers, or browser exports. By the end of this guide you’ll call the Vessels API AIS track endpoint for ZJ ATLANTIC, store a time-ordered array of positions, and handle the practical details that let you ship this to production.

What you’re building: a 48h AIS track for ZJ ATLANTIC

Vessels API exposes a single endpoint for historical tracks of one vessel: a time-ordered series of AIS positions over a requested lookback window. You provide the ship’s identifier and the number of hours to look back; you receive a JSON payload you can persist or plot.

  • Endpoint: GET /api/V1/vessels/track
  • Auth: X-API-Key header
  • Base URL: https://vessels-api.com/api/V1
  • Target vessel in this post: ZJ ATLANTIC (MMSI 258785000), last 48 hours

The official example below uses the same MMSI and a 48-hour window. Note that the reference track dated 2026-02-09 is a documentation sample, not this week’s AIS. When you call the live API, you’ll get the latest 48 hours relative to the moment of your request.

Before you start

Sign up for the API and grab a key. Starter is $19.99/mo with a 7-day trial, which is enough to build and test this flow end-to-end.

  • Register — instant key, 7-day trial.
  • Keep the key handy; you’ll pass it in the X-API-Key header below.
  • Reference docs: Documentation
  • Service status and platform control: MCP

Official example: request ZJ ATLANTIC (48h)

The following request targets the ZJ ATLANTIC by MMSI and asks for the latest 48 hours of track data.

curl -H "X-API-Key: YOUR_API_KEY" \
  "https://vessels-api.com/api/V1/vessels/track?mmsi=258785000&hours=48"

Here is the same contract in Python from the official example.

import os, urllib.request
req = urllib.request.Request(
    "https://vessels-api.com/api/V1/vessels/track?mmsi=258785000&hours=48",
    headers={"X-API-Key": os.environ["VESSELS_KEY"]},
)
print(urllib.request.urlopen(req).read().decode())

The 2026-02-09 trail returned by the example above is the sample used in the docs. Your production calls will return the current 48-hour window.

Call it yourself with curl

Copy-paste the below and replace YOUR_API_KEY with your key. This returns the AIS positions for MMSI 258785000 over the last 48 hours, in time order.

curl -sG "https://vessels-api.com/api/V1/vessels/track" \
  -H "X-API-Key: YOUR_API_KEY" \
  --data-urlencode "mmsi=258785000" \
  --data-urlencode "hours=48"

Python: request, validate, and store the positions array

This minimal example calls the same endpoint, checks for a successful response, and iterates the positions safely without assuming particular field names. It’s ready to drop into a script or a job that persists the data to your store of choice.

import os
import sys
import json
import time
import requests

BASE_URL = "https://vessels-api.com/api/V1"
API_KEY = os.getenv("VESSELS_API_KEY", "YOUR_API_KEY")  # set env var in prod

def get_track(mmsi: str, hours: int = 48) -> dict:
    url = f"{BASE_URL}/vessels/track"
    headers = {"X-API-Key": API_KEY}
    params = {"mmsi": mmsi, "hours": hours}
    r = requests.get(url, headers=headers, params=params, timeout=30)
    # Prefer API-provided status, but always fail on non-2xx
    r.raise_for_status()
    data = r.json()
    # If the API includes a 'success' flag, honor it
    if isinstance(data, dict) and ("success" in data) and (not data["success"]):
        msg = data.get("message") or data.get("error") or "Request failed"
        raise RuntimeError(f"API error: {msg}")
    return data

def store_positions(track: dict) -> None:
    # The API returns a positions array; we avoid hard-coding field names.
    positions = track.get("positions") or track.get("data") or []
    if not isinstance(positions, list):
        raise ValueError("Unexpected payload: positions array not found")

    # Example: print count and preview each point defensively
    print(f"Received {len(positions)} positions")
    for i, p in enumerate(positions[:5]):  # preview first 5
        # Show available keys so you can map them into your schema
        keys = ", ".join(sorted(p.keys()))
        print(f"Point {i+1} keys: {keys}")

    # Persist raw JSON for now; in production, normalize to your schema
    ts = int(time.time())
    out_path = f"track_{ts}.json"
    with open(out_path, "w", encoding="utf-8") as f:
        json.dump(track, f, ensure_ascii=False, separators=(",", ":"))
    print(f"Wrote {out_path}")

if __name__ == "__main__":
    try:
        mmsi = "258785000"  # ZJ ATLANTIC
        hours = 48
        track = get_track(mmsi, hours)
        store_positions(track)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)

Understanding the response (what you will actually use)

Right above you embedded the official example response. Inspect it to confirm:

  • The payload includes a time-ordered array of AIS positions for the requested vessel and hours window.
  • Each element in that array represents one AIS point with consistent keys across the array.
  • There may be top-level metadata and/or a boolean indicating request success. Always check it if present.

You will typically consume:

  • The array of positions (store it raw or map into your schema).
  • The per-point fields necessary for your task (e.g., spatial coordinates and a time reference). Do not assume optional fields are present at every point; handle missing values.
  • Any top-level paging or status indicators returned by the endpoint.

When persisting the data, keep the order intact. The array is time-ordered already, so you can append to an existing track or reindex by your own time key without resorting.

Error handling, missing values, and “success=false”

Design your client to be resilient and observable:

  • HTTP status codes: treat non-2xx as errors and log the body for diagnostics.
  • Explicit failure: if the JSON includes a boolean like “success” and it is false, read a message or error field if present and back off or alert.
  • Missing fields: individual AIS points may omit fields. Use dict.get with defaults and skip points that don’t meet your minimum requirements.
  • Empty arrays: if the returned positions array is empty, it can be a valid state for a quiet period. Decide whether to persist an empty slice or to retry later.

Units, timestamps, and time windows

Work with the timestamps as returned by the API and avoid applying local-time conversions that can reorder points. If you need to display local time, convert at the presentation layer using a reliable timezone database.

The “hours” parameter defines the trailing window relative to your request time. For a consistent 48-hour window across services or cron jobs, schedule your job to run at deterministic intervals and always pass the same hours value.

Caching and storage strategy

For the /vessels/track endpoint, consider:

  • Historical runs: Since you ask for a trailing window, the newest slice overlaps recent calls. To avoid duplicates, de-duplicate by a stable point identifier or by a composite of fields you consider unique for a point.
  • Server-side caching: If multiple services in your stack need the same 48-hour track, cache the raw JSON centrally and set your own TTL aligned with how fresh you need the data to be.
  • Cold storage: Write the raw response to object storage for replay and troubleshooting before transforming into analytics formats.

Go live in four steps

  1. Register — 7-day trial.
  2. Copy the X-API-Key from your dashboard.
  3. GET /api/V1/vessels/track with MMSI 258785000 and hours=48 using the curl or Python code above.
  4. Store the live positions array in your database or data lake for downstream mapping and ETA models.

Troubleshooting checklist

  • 401 or 403: Verify the X-API-Key header is present and correct.
  • Empty positions: Confirm the MMSI and hours parameters. Try a shorter window to test recency.
  • Parsing errors: Log the raw JSON to verify structure; don’t assume field presence across all points.
  • Clock drift: If your system clock is off, your “last 48 hours” may misalign with downstream jobs. Sync time.

FAQ

How do I request the 48-hour track for ZJ ATLANTIC?
Use GET /api/V1/vessels/track with mmsi=258785000 and hours=48. Provide your key in X-API-Key.

Why does the example reference 2026-02-09?
That’s the sample used in the documentation to show the response format. Live calls return the current 48 hours from the moment you request.

What if the response includes success=false?
Treat it as a failure, read the provided message or error field if present, and retry with backoff or alert your on-call.

Which fields should I store?
Persist the entire positions array as returned, then normalize only the fields you actively use in your application. This preserves fidelity for future analytics without another fetch.

Can I call this from a scheduled job?
Yes. Cron your job to run at fixed intervals and request the same hours window. De-duplicate points on ingest.

Build your 48-hour AIS track for ZJ ATLANTIC now. Start your 7-day trial, grab your API key, and ship your first integration in minutes: Register. If you need specifics on parameters or payload structure, keep the Documentation open, and use MCP to monitor and operate your calls.

Ready to get started?

Get your API key and start tracking vessels in minutes.

Get API Key