You need to show which ports are backed up right now and by how much, then surface it in your product as a simple “Port Directory” with live occupancy. By the end of this guide you’ll call Vessels API to list ports, fetch AIS-derived congestion for a selected port_id, store the occupancy fields, and serve them reliably in production.
What “AIS port congestion” means for a Port Directory
Congestion is the real-time occupancy signal for a cataloged port based on AIS. In practical terms, it tells your users whether a port is busy and trending up or down. It’s the core metric that powers features like “Is my destination jammed?”, “Which port should I re-route to?”, and “How long might we wait to berth?”.
If you’re building a Port Directory, you’ll typically start with a list of ports, let the user pick one, and then load its congestion metrics. Because the data updates over time, you’ll also want a caching and polling strategy so your UI stays fresh without over-fetching.
Endpoints you will call
Vessels API exposes congestion right next to the base ports listing:
- GET /api/V1/ports — list ports in the catalog so you can look up the port_id you need.
- Congestion path that takes a port_id — use the port_id from the ports list to fetch live occupancy. The official sample uses port_id=84; you’ll substitute whatever port_id your users select.
Base URL: https://vessels-api.com/api/V1. Authenticate every request with the X-API-Key header you get after registering. The same pattern applies whether you’re testing locally or running in production.
Go live in minutes
- Register for a 7-day trial: Register. Starter is $19.99/mo after trial.
- Copy your X-API-Key from your account.
- Call GET /api/V1/ports to find the port_id your users care about. Then call the congestion path with that port_id.
- Persist the live occupancy fields in your database or cache so your directory loads instantly for repeat views.
Note: This is not FreightPulse PortWatch. It’s the Vessels API congestion signal integrated directly into your workflow.
Official sample: congestion for a catalog port
The sample below demonstrates reading congestion for a specific catalog port. It uses port_id=84 so you can see a real end-to-end request and response. To use a different port, just pass its port_id instead of 84.
curl -H "X-API-Key: YOUR_API_KEY" "https://vessels-api.com/api/V1/ports"
Reading and using the response
The JSON you receive includes the occupancy fields you need to render a “congestion at a glance” view. Here’s how to work with it in a production app:
- Occupancy fields: Treat these as the primary congestion signal. Store them alongside the port_id and the timestamp you received them so you can display a recent reading and a change over time.
- Timestamps and timezone: Parse any timestamp fields exactly as provided. If the payload includes timezone info, prefer it. If a field omits timezone details, handle it cautiously and default your display to UTC in your UI to avoid ambiguity.
- Missing values: Some ports may have partial coverage at a given moment. Check for null/absent values before calculation. If a field is missing, display “—” or “Unavailable” rather than zero to avoid misleading math.
- Error signaling: On non-2xx HTTP status codes, treat the call as failed and follow your retry policy. If the response includes a success boolean and it’s false, surface a soft error to your logs and skip updating cached values until the next poll.
- Units: Use the fields as-is; do not convert unless the response explicitly provides units and you need to standardize your UI. Label any derived metrics clearly.
Persistence strategy:
- Write congestion readings to a time-series table keyed by port_id and timestamp. That lets you render simple sparklines or “change since last hour” without recomputing from scratch.
- Maintain a current snapshot keyed by port_id for fast directory views. Background jobs can refresh snapshots on a fixed interval appropriate for your users.
Python example: call the congestion endpoint and store occupancy
The snippet below sends the same request as the official curl and extracts the occupancy fields. Replace YOUR_API_KEY with your key. Use the same congestion URL shown in the official sample above (it includes the correct path and port_id placeholder).
import os
import time
import json
import requests
API_KEY = os.getenv("VESSELS_API_KEY", "YOUR_API_KEY")
HEADERS = {"X-API-Key": API_KEY}
# Use the same congestion URL from the curl sample above, substituting your port_id as needed.
# For example, if the curl shows .../ports/<port_id>/congestion for port_id=84, then:
congestion_url = "PASTE_THE_CONGESTION_URL_FROM_THE_CURL_SAMPLE_HERE"
def fetch_congestion():
resp = requests.get(congestion_url, headers=HEADERS, timeout=20)
# Basic HTTP error handling
if resp.status_code >= 400:
raise RuntimeError(f"HTTP {resp.status_code}: {resp.text}")
data = resp.json()
# If the API includes a success flag, respect it. Otherwise proceed with data validation.
if isinstance(data, dict) and "success" in data and data["success"] is False:
raise RuntimeError(f"API reported success=false: {json.dumps(data)}")
# Extract occupancy-related fields defensively.
# Use the field names exactly as returned in the official JSON above.
# For example:
# occupancy = data.get("occupancy")
# updated_at = data.get("updated_at")
# Any additional fields you care about:
# queue = data.get("queue")
# utilization = data.get("berth_utilization")
# Save raw for auditing; save selected fields for fast UI display
return data
if __name__ == "__main__":
try:
reading = fetch_congestion()
# Persist to your store. Here we just print:
print(json.dumps(reading, indent=2))
except Exception as e:
# Production code should log error details and apply a backoff before retrying
print(f"Error: {e}")
time.sleep(5)
From API to a working Port Directory
1) Identify a port_id
Call GET /api/V1/ports to show a searchable list. When a user selects a port, save its port_id. You only need the port listing occasionally; keep it cached so your UI loads instantly.
2) Fetch congestion using port_id
Call the congestion path using that specific port_id. The official sample uses port_id=84; in your app, substitute the selected port’s id so the request targets the right port. Always send your X-API-Key header.
3) Persist the occupancy fields
Write the occupancy fields and the request timestamp. If the response supplies its own timestamp, prefer that for your “last updated” label. Storing a trail of recent readings lets you display day-over-day or hour-over-hour deltas with almost no extra work.
4) Serve it in your UI
For directory pages, render the current snapshot for each port with a timestamp and a short note if any field is temporarily unavailable. Let users drill into a single port for a slightly richer view using the historical readings you saved.
Operational guidance that saves you time
- Authentication: Always include X-API-Key with your requests. Rotate keys through environment variables, not source control.
- Caching: Cache port listings for hours or days depending on your UX. Cache congestion for only as long as your users can tolerate stale occupancy. Keep a fallback snapshot in case your next poll fails.
- Polling: Schedule background jobs to refresh congestion. If you experience transient errors or timeouts, use exponential backoff and keep the previous good value.
- Partial data: Some readings may be incomplete. Build UI states for “data temporarily unavailable” per field, not just per page.
- Serialization: Log everything you persist. Store the raw JSON alongside normalized fields so you can reprocess if your analytics change.
- Pagination: The ports listing may be paginated. Iterate until you’ve collected the full catalog you need, then cache the result.
- Monitoring: Track request latency, success ratios, and your cache hit rate. Alert on consecutive failures so your directory doesn’t silently drift out of date.
Testing and troubleshooting
- Reproducibility: Save the exact request URL (including port_id) and response payloads in your test fixtures so you can reproduce UI states.
- Validation: Verify that all occupancy fields you display are present before rendering. If a field is missing, don’t coerce it to zero; display a clear placeholder.
- HTTP errors: For 4xx, review your auth header or path. For 5xx, keep your last known good value and retry later.
- Schema drift: If new fields appear, ignore them until you explicitly support them. This keeps your UI stable.
Where to learn more and manage access
- Register for an API key (7-day trial): Register
- Browse reference and field-level details: Documentation
- Manage credentials and access: MCP
FAQ
How do I find the correct port_id?
Call GET /api/V1/ports, search or filter to the port your user selects, and read its port_id. Use that id in the congestion request. The sample request demonstrates port_id=84; replace 84 with your port’s id.
What if the response has success=false or is missing fields?
Treat success=false as a soft failure: don’t overwrite your last good snapshot and try again later. For missing fields, show a placeholder rather than a zero. Always log the raw JSON so you can audit later.
What timezone should I display?
Use the timestamp fields as returned. If the response includes timezone info, display it. If not, standardize your UI on UTC and include “UTC” in the label.
How often should I poll congestion?
Poll only as frequently as your users need up-to-date occupancy. Cache results between polls and keep the previous good value on transient errors. Avoid tight loops; add backoff on failures.
Is this FreightPulse PortWatch?
No. This is the Vessels API congestion signal exposed alongside the ports catalog. It integrates directly into your stack via a simple REST call with X-API-Key authentication.
Ready to add live congestion to your Port Directory? Start your 7-day trial, get your key, and ship an end-to-end integration today: Register. For field-level references, keep the Documentation open, and manage your keys in MCP.