You need to answer a specific operational question: “Is there a research vessel near this port, what is it doing, and when will it arrive or depart?” By the end of this post, you’ll know exactly which endpoints to call from vessels-api.com to find research vessels around a port, retrieve live tracks with recent port calls, snapshot port congestion, and wire everything into a lightweight dashboard or backend job.
What we’ll build with the Vessels API
We’ll cover how to:
- Discover and track a specific research vessel using live AIS.
- Detect research vessels within a radius of a port and display their distance and movement.
- Pull port-level context: congestion, expected arrivals, and live vessel counts.
- Batch-check multiple MMSIs in a single request to power a fleet tile for research campaigns.
Everything is served from a single base URL (https://vessels-api.com/api/V1) with one header (X-API-Key: YOUR_API_KEY). Every response uses the same JSON envelope: {status, success, message, data}. Time values are UTC ISO-8601. Distances are nautical miles (nm), speeds in knots.
Core endpoints for “research vessel near a port”
- GET /vessels/track — Live position, up to 168h history, route, last port visits, optional weather.
- GET /vessels/nearby — All vessels within a radius (NM) of a point; filterable by ship_type.
- GET /ports/data — Detailed info for a port including live vessel counts.
- GET /port/expected-arrivals — Vessels inbound to a port with ETA and origin.
- POST /vessels/fleet — Batch summary for multiple vessels (positions, routes, stats).
We’ll start with a canonical live-track call, then wire regional and port context around it.
Live tracking a research vessel near a port
Use GET /vessels/track to pull the current position, route, and recent port calls. This is your base layer for any “is the vessel near port?” logic, because it provides both the current point and the route context (departure/destination) if available.
Official sample: track by MMSI
The following call and JSON are provided as a documented example. Copy/paste them to validate your client code and response mapping.
curl -H "X-API-Key: YOUR_API_KEY" "https://vessels-api.com/api/V1/vessels/track?mmsi=258785000&hours=48"
{
"status": 200,
"success": true,
"message": "OK",
"data": {
"vessel": {
"imo": "9122556",
"mmsi": "258785000",
"name": null
},
"current_position": {
"latitude": 53.33708,
"longitude": 7.17993,
"position_precision": "precise",
"position_accuracy_nm": null,
"speed_knots": 0,
"course_degrees": 212,
"heading_degrees": null,
"navigational_status": 5,
"timestamp_utc": "2017-01-24T04:07:04+00:00",
"age_minutes": 5160921,
"destination": null,
"eta": null
},
"predicted_eta": null,
"position_history": [],
"route": {
"departure_port": "HERACLIO",
"departure_time": "2026-04-27T21:35:36+00:00",
"destination_port": "HERACLIO",
"eta": null,
"distance_nm": null,
"avg_speed_knots": 17.1
},
"last_port_visits": [
{
"port_id": "156",
"port_name": "EMDEN",
"arrival_time": "2026-07-30T13:00:10+00:00",
"departure_time": null,
"duration_hours": null
},
{
"port_id": "10",
"port_name": "HERACLIO",
"arrival_time": "2026-04-20T12:00:00+00:00",
"departure_time": "2026-04-23T08:00:00+00:00",
"duration_hours": 68
}
],
"weather": null
}
}
Key fields to wire into your app:
- data.current_position.latitude/longitude — plot on your map; compute distance to port.
- data.current_position.timestamp_utc — last AIS datapoint time (UTC); use for staleness checks and caching.
- data.route.departure_port, data.route.destination_port — useful if the research vessel is shuttling to/from the port in question.
- data.last_port_visits — quick way to render “last called at” facts without a separate query.
Python quickstart: get distance to a port and last call
The snippet below calls /vessels/track, then computes a rough distance (great-circle) to a known port center you already store (from GET /ports), and shows the latest port visit in the payload. Replace the coordinates with your target port’s centroid.
import math
import requests
API_KEY = "YOUR_API_KEY"
MMSI = "258785000"
PORT_LAT, PORT_LON = 53.34, 7.20 # Example: port centroid near EMDEN for demo
def nm_distance(lat1, lon1, lat2, lon2):
# Great-circle with Earth radius in nautical miles
R_nm = 3440.065
phi1, phi2 = math.radians(lat1), math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dlambda = math.radians(lon2 - lon1)
a = math.sin(dphi/2)**2 + math.cos(phi1)*math.cos(phi2)*math.sin(dlambda/2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
return R_nm * c
resp = requests.get(
"https://vessels-api.com/api/V1/vessels/track",
params={"mmsi": MMSI, "hours": 48},
headers={"X-API-Key": API_KEY},
timeout=20
)
resp.raise_for_status()
payload = resp.json()
if not payload.get("success"):
raise RuntimeError(payload.get("message", "Unknown API error"))
data = payload["data"]
pos = data.get("current_position") or {}
vlat, vlon = pos.get("latitude"), pos.get("longitude")
if vlat is not None and vlon is not None:
dist_nm = nm_distance(vlat, vlon, PORT_LAT, PORT_LON)
else:
dist_nm = None
last_visits = data.get("last_port_visits") or []
last_visit = last_visits[0] if last_visits else None
print("Current lat/lon:", vlat, vlon)
print("Distance to port (nm):", round(dist_nm, 2) if dist_nm is not None else "n/a")
if last_visit:
print("Last port:", last_visit["port_name"], "arrived", last_visit["arrival_time"])
Find “research vessels near a port” in one request
If you already know your port’s centroid (latitude/longitude), GET /vessels/nearby returns all vessels within a radius in nautical miles. You can optionally filter by ship_type and cap the list with limit. This is the fastest way to answer “what research vessels are within 20 NM of our breakwater?”
cURL: scan 25 NM around a port for research vessels
Response fields to map
The response shape is consistent with the API envelope. Here’s a trimmed example that illustrates the fields you’ll parse:
Focus on data.vessels[].distance_nm to drive near-port alerts. The timestamp_utc confirms sensor freshness; treat stale points (e.g., older than your SLA) as “unknown” and optionally fall back to /vessels/track for a deeper check.
Port context: live counts, expected arrivals, and congestion
When a research mission transits in and out of a port, operations teams also care about berth availability, queue length, and inbound schedules. These endpoints give you the port layer.
GET /ports/data: port overview with live counts
Use this to display current vessels_in_port and vessels_expected alongside your near-port map. You’ll need the port identifier (e.g., ARBUE for Buenos Aires; get a full list via GET /ports).
Key fields:
- data.vessels_in_port — current total at berth/anchorage.
- data.vessels_expected — count of inbound calls on the near horizon.
- data.latitude/longitude — store as the canonical centroid for your /vessels/nearby radius queries.
GET /port/expected-arrivals: schedule view
Show imminent arrivals for the port. This is useful for comparing a research vessel’s own route vs. other inbound traffic.
Typical fields you’ll render:
- data.expected_arrivals[].name, vessel_type — quick card list.
- data.expected_arrivals[].eta — schedule in UTC; convert to the port’s timezone client-side if desired (timezone is available on /ports and /ports/data).
- data.expected_arrivals[].departure_port — provenance.
GET /ports/congestion: anchorage vs. berth snapshot
This snapshot helps forecast berth wait for your instrument offload window. Choose the period granularity that fits your dashboard (24h/3d/7d).
Ensure you render fields exactly as provided by the endpoint:
- data.snapshot.vessels_in_anchorage, data.snapshot.vessels_at_berth — real-time counts.
- data.statistics.avg_wait_time_hours_last_7d — moving average wait time, in hours.
- data.statistics.port_calls_count — call volume for your trend badges.
Batch mode: track multiple research vessels at once
Campaigns often deploy more than one research vessel. Reduce network overhead and simplify your polling loop with POST /vessels/fleet.
You’ll receive a roll-up (data.fleet) and per-vessel blocks that include position and route when requested. Good defaults:
- Poll every 2–5 minutes for near-real-time dashboards.
- Cache by MMSI for the short term based on timestamp_utc; skip redraws if unchanged.
- Surface stale age (e.g., > 30 minutes) as a subtle UI hint on each tile.
JavaScript: end-to-end “near port” query and enrich
This example chains three calls: get the port centroid, scan nearby for research vessels, then hydrate one vessel with /vessels/track to show route context and last port visit. It’s minimal and framework-agnostic.
async function fetchJson(url, headers, params = {}) {
const u = new URL(url);
Object.entries(params).forEach(([k, v]) => u.searchParams.set(k, v));
const res = await fetch(u.toString(), { headers, cache: "no-store" });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body = await res.json();
if (!body.success) throw new Error(body.message || "API error");
return body.data;
}
(async () => {
const headers = { "X-API-Key": "YOUR_API_KEY" };
// 1) Port centroid and live counts
const portId = "ARBUE";
const portData = await fetchJson(
"https://vessels-api.com/api/V1/ports/data",
headers,
{ port: portId }
);
const { latitude, longitude, name: portName, vessels_in_port } = portData;
// 2) Nearby scan for research vessels within 25 NM
const nearby = await fetchJson(
"https://vessels-api.com/api/V1/vessels/nearby",
headers,
{ latitude, longitude, radius: 25, ship_type: "Research", limit: 50 }
);
const candidates = nearby.vessels || [];
if (candidates.length === 0) {
console.log(`No research vessels within 25 NM of ${portName}. In port now:`, vessels_in_port);
return;
}
// 3) Hydrate the closest vessel with full track/route context
candidates.sort((a, b) => (a.distance_nm || 1e9) - (b.distance_nm || 1e9));
const top = candidates[0];
const track = await fetchJson(
"https://vessels-api.com/api/V1/vessels/track",
headers,
{ mmsi: top.mmsi, hours: 48 }
);
console.log("Port:", portName, "Centroid:", latitude, longitude);
console.log("Closest research vessel:", top.name, top.mmsi, "Distance (nm):", top.distance_nm);
console.log("Last port visits:", track.last_port_visits);
console.log("Route:", track.route);
})();
Building blocks for a production-grade research ops dashboard
Here are the practical implementation notes that typically save teams an iteration cycle:
- Authentication: always pass X-API-Key in headers; no OAuth or per-endpoint differences.
- Consistency: every response uses {status, success, message, data}. Check success first and prefer the message field for user-facing errors.
- Timestamps: timestamp_utc is ISO-8601 with timezone suffix (e.g., +00:00 for UTC). Convert to the user’s locale for display, but preserve UTC internally for calculations.
- Units: distances are nautical miles, speeds in knots. Keep calculations in NM/kn to avoid unit drift.
- Pagination: /vessels/search returns pagination metadata {current_page, per_page, total, last_page}. Use per_page up to 100. Nearby already includes a limit parameter, and fleet scales by the size of your POST body.
- Polling: start with a 2–5 minute cadence for dashboards. If using fleet mode, consider backoff on 429. Respect Age/Last-Modified semantics you track from timestamp_utc to skip unnecessary re-renders.
- Ship type filtering: /vessels/nearby supports ship_type filtering. Align your app’s filter values with your own UI taxonomy; display unfiltered results alongside a “Research” quick-toggle if needed.
Optional: search layer to locate a research vessel by name or IDs
When you don’t have an MMSI or IMO yet, use GET /vessels/search. Add filters like ship_type and flag to narrow results before tracking.
Relevant fields from data.vessels[]:
- imo, mmsi — use one of these as the primary key for subsequent calls.
- name, flag, vessel_type — render in your selection UI.
- length_m, width_m, year_built — optional context for berth compatibility checks.
Wire it all together: a minimal flow
- Discover your port’s centroid once via GET /ports or GET /ports/data.
- Call GET /vessels/nearby with radius=25–50 to list research vessels and distances.
- For the closest vessel, hydrate with GET /vessels/track to get last_port_visits and route.
- Call GET /port/expected-arrivals to compare the vessel’s predicted activity with inbound schedules.
- If monitoring more than one MMSI, move to POST /vessels/fleet and poll on a fixed cadence with minimal redraws when timestamp_utc is unchanged.
Error handling and status codes
- 401: Invalid or missing X-API-Key — confirm header inclusion on every request.
- 404: Vessel or port not found — double-check MMSI/IMO/port ID values; consider a fallback search.
- 422: Parameter out of range — verify radius is within 0–200 NM; hours ≤ 168 for /vessels/track.
- 429: Rate limit exceeded — implement retry with exponential backoff.
- 500: Server error — retry with jitter; surface a soft warning in UI.
ESG note: add emissions for compliance or grant reporting
If your research fleet has compliance obligations or grant KPIs, GET /vessels/green returns an IMO CII score and estimated emissions over recent periods (24h, 7d, 30d, 1y). This is often attached to post-mission reports or sustainability dashboards.
Fields to store: data.cii.rating (A–E), data.estimated_emissions.co2_tons and co2_per_nm. Keep results alongside your voyage stats for longitudinal benchmarking.
FAQ
Q: What coordinate should I use for a port when querying /vessels/nearby?
A: Use the port centroid from GET /ports or GET /ports/data (latitude, longitude). Store it in your config and pass it as the nearby center.
Q: How fresh is the “live” position?
A: Check data.current_position.timestamp_utc and/or age_minutes in /vessels/track and timestamp_utc in /vessels/nearby. Always display the data age in your UI to manage expectations.
Q: Should I use MMSI or IMO?
A: Both are accepted across key endpoints. MMSI is generally preferable for frequent polling of live AIS. Use /vessels/search to resolve either from a vessel name.
Q: How do I avoid double-counting or flicker in my map?
A: Cache by MMSI with the latest timestamp_utc. If a subsequent poll returns the same timestamp, skip redraw. For fleets, coalesce updates from /vessels/fleet before rendering.
Q: Can I filter just for “Research” vessels?
A: Yes, pass ship_type=Research to /vessels/nearby or as a filter to /vessels/search. Keep in mind taxonomy variations across data sources; provide a manual override in your UI when needed.
Next steps
Ship your first near-port research vessel view with the endpoints above, then expand with fleet polling and port congestion overlays. For a deeper dive into parameters, optional fields, and edge cases, review the Documentation, try the server-assisted tools in the MCP, and get an API key to start calling endpoints with a sandbox project: Register.