How to Build a Flight Delay Tracker with an API
A flight can depart late, recover time in the air or arrive later than its latest estimate. By combining a FlightLabs real-time flight response with scheduled and actual timestamps, you can build a tracker that reports those changes without treating an estimate as a final result.
Choose the data for the tracker
Start with the FlightLabs real-time flight tracking endpoint. Its example response contains a flight identifier, status, departure and arrival details, and position data. For a delay tracker, the timestamps and status are more important than the aircraft position.
Use flight schedules when you need to build a list of planned services before tracking them. The schedule example includes flight numbers and scheduled times, but a planned time alone does not tell you whether a flight actually departed or arrived late.
| Data | Relevant example fields | Use in the tracker |
|---|---|---|
| Flight identity and state | iata, icao, number, status |
Label the flight and decide how to describe its current state. |
| Departure | scheduled, actual, terminal, gate |
Calculate an observed departure difference and display departure information. |
| Arrival | scheduled, estimated, terminal, gate |
Calculate an estimated arrival difference and display arrival information. |
| Position | latitude, longitude, altitude, speed, heading |
Optionally show position separately from delay calculations. |
The example real-time response identifies flight AA123 as en-route, departing from JFK and arriving at LAX. Treat those values as an illustration of the response shape, not as a current flight update.
For the current request format, authentication, supported filters and response details, consult the Documentation. FlightLabs authenticates requests with an API key; keep that key on your server rather than embedding it in a browser or mobile app.
Calculate departure and arrival differences
Subtract the scheduled departure from the actual departure to get an observed departure difference. For arrival, subtract the scheduled arrival from the estimated arrival to get a projected difference. A positive result is later than scheduled; a negative result is earlier.
In the example response, the departure is scheduled for 2024-03-20T10:00:00Z and actual departure is 2024-03-20T10:05:00Z. That is an observed difference of five minutes. The scheduled and estimated arrival times also differ by five minutes, but that arrival difference remains an estimate.
The example does not include a dedicated delay field. Calculating the difference yourself makes the basis of the display explicit: users can see whether a number comes from an actual event or a forecast. Preserve the original timestamps alongside the calculation so you can reprocess or audit the result later.
Normalize timestamps before subtracting
The Z suffix in the example timestamps means UTC. Parse timestamps as timezone-aware values and compare instants in UTC; do not subtract formatted local-time strings. Convert to the relevant airport’s local timezone only when presenting a time to a user.
Keep the date visible when local display times could fall on a different calendar day. Daylight-saving changes also make a timezone identifier more useful than a fixed offset for display conversion. The airport information example uses America/New_York for JFK.
Process a real-time response
The following Python code reads a real-time response from standard input. It handles missing timestamps, rejects timestamps without a timezone and labels arrival as estimated rather than actual. Feed it the response returned by your authenticated FlightLabs request.
import json
import sys
from datetime import datetime, timezone
def parse_instant(value):
if not value:
return None
try:
instant = datetime.fromisoformat(value.replace("Z", "+00:00"))
except (TypeError, ValueError):
return None
if instant.tzinfo is None or instant.utcoffset() is None:
return None
return instant.astimezone(timezone.utc)
def difference_minutes(scheduled, observed):
start = parse_instant(scheduled)
end = parse_instant(observed)
if start is None or end is None:
return None
return (end - start).total_seconds() / 60
response = json.load(sys.stdin)
if response.get("success") is not True:
sys.exit("FlightLabs response was not successful")
flight = (response.get("data") or {}).get("flight") or {}
if not flight:
sys.exit("No flight data in the response")
departure = flight.get("departure") or {}
arrival = flight.get("arrival") or {}
departure_minutes = difference_minutes(
departure.get("scheduled"), departure.get("actual")
)
arrival_minutes = difference_minutes(
arrival.get("scheduled"), arrival.get("estimated")
)
print("Flight:", flight.get("iata") or "unknown")
print("Status:", flight.get("status") or "unknown")
print("Departure difference, actual minutes:", departure_minutes)
print("Arrival difference, estimated minutes:", arrival_minutes)
print("Departure terminal:", departure.get("terminal") or "unknown")
print("Departure gate:", departure.get("gate") or "unknown")
print("Arrival terminal:", arrival.get("terminal") or "unknown")
print("Arrival gate:", arrival.get("gate") or "unknown")
A None difference means the calculation could not be made; it does not mean the flight is on time. In a user interface, show the relevant time as unavailable rather than displaying zero minutes. Also distinguish an API or network failure from a successful response that lacks a particular field.
Turn updates into a usable tracker
Store the latest successful response and the time your application received it. When a new response arrives, compare its status, timestamps, terminals and gates with the previous snapshot. Update the display when a value changes, and retain enough history to explain why a notification was sent.
The example places terminal and gate under both departure and arrival. Label each with its corresponding airport so a traveler does not mistake the arrival gate for the departure gate. If either field is absent, show it as unavailable; do not carry a previous value forward as though it were confirmed by the latest response.
Poll and cache deliberately
Polling frequency is an application choice, not a guarantee of how often flight information changes. Choose a cadence appropriate to the display and your plan, then use the same cached result for users watching the same flight. Avoid making a separate upstream request every time a visitor opens or refreshes a page.
Keep the last successful snapshot if a refresh fails, but mark it as stale and show when it was last updated. Use backoff after failures and avoid retrying continuously. A dashboard can refresh more deliberately when a flight is relevant to the user than when it is no longer being watched.
For notifications, compare consecutive successful snapshots rather than sending an alert on every poll. For example, notify on a changed estimate or gate only when the new value is available and differs from the previous value. Include the observation time and identify an estimated arrival as an estimate.
Handle cancelled and diverted flights
Give the flight status precedence over a simple minutes-late label. If the API indicates a cancellation, show that state prominently instead of presenting a missing actual time as an on-time departure. Do not assume that a scheduled time will eventually become an actual time.
If the API indicates a diversion, flag it for the user and review the latest arrival information before describing the original destination as confirmed. Treat unavailable or unfamiliar status values as unknown until your application can interpret them reliably. Use the endpoint documentation to determine the supported status values and how diversion information is represented.
Keep codeshares distinct
A flight may be sold under more than one flight identifier. The example real-time response includes iata, icao and number, but it does not show a codeshare field. Display the identifier returned for the tracked flight, and consult the documentation before attempting to group marketed and operating identifiers into one service.
Do not deduplicate flights solely because their scheduled times and airports match. If your product links multiple identifiers, retain the identifier the user searched for as well as the identity returned by the API, so notifications remain understandable.
Build the watch list from schedules
A schedule-driven display can first retrieve planned services, then track selected flights using real-time data. The schedule example provides flight_number, departure and arrival airports, and scheduled times. It also includes terminal information, aircraft details and an airline object; use those as planning context rather than evidence of an actual departure.
Process every available page before treating a schedule result as complete. Follow the pagination mechanism for the schedule endpoint in the documentation, and avoid assuming that the first response contains the full set. If a page request fails, record that the list is incomplete and retry that part rather than silently presenting a partial list as complete.
When matching a schedule entry to a live flight, account for the flight identifier and the relevant service date and route. Preserve the scheduled values used for the original display, but refresh them when the source changes. A live response with no actual or estimated time should not overwrite a useful scheduled time with an implied delay.
FAQ
Is an estimated arrival delay the same as an actual delay?
No. An estimated difference can change while the flight is underway. Label it as estimated and calculate it from the scheduled and estimated arrival timestamps.
What should the tracker show when a timestamp is missing?
Show that the time or delay is unavailable. Do not substitute zero or use a scheduled time as an actual time.
How often should I refresh a flight?
Choose a cadence based on how quickly your users need updates and the requests available on your plan. Share cached responses across viewers, back off after failures and expose the last successful update time.
Can I use schedules to determine whether a flight is delayed?
Schedules provide planned times. Compare those with actual or estimated times from flight tracking to calculate an observed or projected difference.
How do I start testing?
FlightLabs Starter is listed at $24.99 per month, with a 7-day or 50-request trial. Check the current plan and trial terms when registering.
Register to get an API key and test the tracker with FlightLabs data. You can also explore MCP for another way to work with FlightLabs tools.