Skip to main content

A Python client for the Flightradar24 API with CLI support

Project description

Pyfr24

Pyfr24 is a Python client for the Flightradar24 API. This package provides a simple interface to fetch, plot and analyze flight data, including live flights, historical tracks and detailed flight information. With Pyfr24, you can easily investigate incidents, export flight data in multiple formats (CSV, GeoJSON, KML) and generate quick flight path plots. The package includes both a Python API and a command-line interface for quick access to flight data without writing code. The API requires a Flightradar24 subscription.

Features

  • Flight data retrieval
  • Live flight tracking
  • Flight track history
  • Airline and airport information
  • Export flight data to CSV, GeoJSON, KML and plot
  • Error handling and logging
  • Command-line interface

Installation

Clone the repository and install the package in editable mode. Pyfr24 requires Python 3 and the following dependencies:

  • requests
  • geopandas
  • contextily
  • matplotlib
  • shapely
  • pandas

To install, run:

pip install -e .

Or install directly from PyPI:

pip install pyfr24

How to use

API Token

You can provide your Flightradar24 API token in one of three ways:

  1. Command line argument (easiest for one-time use):
pyfr24 --token "your_api_token" flight-summary --flight BA123 --from-date "2023-01-01T00:00:00Z" --to-date "2023-01-01T23:59:59Z"
  1. Environment variable (good for repeated use):
export FLIGHTRADAR_API_KEY="your_api_token"
pyfr24 flight-summary --flight BA123 --from-date "2023-01-01T00:00:00Z" --to-date "2023-01-01T23:59:59Z"
  1. Interactive prompt (when no token is provided):
pyfr24 flight-summary --flight BA123 --from-date "2023-01-01T00:00:00Z" --to-date "2023-01-01T23:59:59Z"
Please enter your Flightradar24 API token: your_api_token

Using the Python API

Import and use the package in your project:

import os
import json
from pyfr24 import FR24API, configure_logging

# Configure logging (optional)
configure_logging(level=logging.INFO, log_file="pyfr24.log")

# Get the API token from the environment
token = os.environ.get("FLIGHTRADAR_API_KEY")
if not token:
    raise ValueError("FLIGHTRADAR_API_KEY environment variable not set.")

# Initialize the API client.
api = FR24API(token)

# Example a: Get live flights for a specific aircraft registration.
live_flights = api.get_live_flights_by_registration("HL7637")
print(json.dumps(live_flights, indent=2))

# Example b: Get basic airline information by ICAO code.
airline_info = api.get_airline_light("AAL")
print(json.dumps(airline_info, indent=2))

# Example c: Get flight tracks for a specific flight based on the FR24 flight ID.
tracks = api.get_flight_tracks("39bebe6e")
print(json.dumps(tracks, indent=2))

# Example d: Export flight data.
# This creates a directory named after the flight ID containing:
#   - data.csv: CSV of flight track points
#   - points.geojson: GeoJSON of track points
#   - line.geojson: GeoJSON LineString connecting the points
#   - track.kml: Flight path in KML format
#   - plot.png: A quick map plot of the flight path
output_dir = api.export_flight_data("39bebe6e")
print(f"Flight data exported to directory: {output_dir}")

# Get airline information
airline = api.get_airline_info("BAW")

# Get airport information
airport = api.get_airport_info("LHR")

You can also fetch detailed flight summaries and full airport data using the other available methods.

Using the command-line interface

Pyfr24 provides a command-line interface for quick access to the API. All commands support both long and short option forms:

# Get flight summary
pyfr24 flight-summary -F AA123 -f "2023-01-01" -t "2023-01-01"
# or
pyfr24 flight-summary --flight AA123 --from-date "2023-01-01" --to-date "2023-01-01"

# Get live flights for an aircraft
pyfr24 live-flights -R N12345
# or
pyfr24 live-flights --registration N12345

# Get flight tracks
pyfr24 flight-tracks -i 39a84c3c
# or
pyfr24 flight-tracks --flight-id 39a84c3c

# Export flight data
pyfr24 export-flight -i 39a84c3c -o data/flight_39a84c3c
# or
pyfr24 export-flight --flight-id 39a84c3c --output-dir data/flight_39a84c3c

# Get airline information
pyfr24 airline-info -i AAL
# or
pyfr24 airline-info --icao AAL

# Get airport information
pyfr24 airport-info -c JFK
# or
pyfr24 airport-info --code JFK

# Get flight positions within a bounding box (Los Angeles area)
pyfr24 flight-positions -b "33.5,-118.8,34.5,-117.5"
# or
pyfr24 flight-positions --bounds "33.5,-118.8,34.5,-117.5"

# Get flight IDs for an aircraft registration
pyfr24 flight-ids -R N216MH -f "2025-01-01" -t "2025-04-10"
# or
pyfr24 flight-ids --registration N216MH --from-date "2025-01-01" --to-date "2025-04-10"
# Save results to a file
pyfr24 flight-ids -R N216MH -f "2025-01-01" -t "2025-04-10" -o flight_ids.json

Common options available for all commands:

  • -t, --token: API token (can also be set via FLIGHTRADAR_API_KEY env var)
  • -l, --log-level: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  • -f, --log-file: Log file path
  • -o, --output: Output file path (JSON)

For more options and detailed help, use:

pyfr24 --help
pyfr24 flight-summary --help

Error handling

The client includes robust error handling with custom exception classes:

from pyfr24 import FR24API, FR24AuthenticationError, FR24NotFoundError

try:
    api = FR24API("your_token")
    data = api.get_flight_summary_light(
        flights="AA123",
        flight_datetime_from="2023-01-01T00:00:00Z",
        flight_datetime_to="2023-01-01T23:59:59Z"
    )
except FR24AuthenticationError as e:
    print(f"Authentication error: {e}")
except FR24NotFoundError as e:
    print(f"Flight not found: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")

Logging

The client includes a logging configuration that can be customized:

import logging
from pyfr24 import configure_logging

# Configure logging with default settings
configure_logging()

# Configure logging with custom settings
configure_logging(
    level=logging.DEBUG,
    log_file="pyfr24.log",
    log_format="%(asctime)s - %(levelname)s - %(message)s"
)

Case study: incident investigation

Imagine you receive word that a Delta flight, DL2983, took off from DCA and came close to a military jet, D061, flying near the airport. Later, you learn it was actually an American Eagle flight, AA5308, that had a closer call. You can use Pyfr24 to investigate this incident by comparing flight summaries and tracking data.

For each reported flight, you can:

  • Retrieve the flight summary to obtain the internal fr24_id for each flight and aircraft.
  • Export the flight tracks (CSV, GeoJSON and a quick plot for reference) for further analysis. The export functionality automatically saves files under a directory structure of the form data/flight_id.
  • Compare the exported maps and data to determine which flight path came closest to the military jet.

Here's an example script for such an scenario:

import os
import json
from pyfr24 import FR24API, configure_logging

# Configure logging
configure_logging(level=logging.INFO, log_file="investigation.log")

def investigate_incident(api, flight_ids, date_from, date_to):
    """
    For each flight (by reported flight number or call sign),
    retrieve the flight summary, extract the internal "fr24_id" and
    then export flight track data using that ID.
    
    Returns a dictionary mapping each original flight ID to a list
    of results containing the internal fr24_id, summary details and export directory.
    """
    results = {}
    for fid in flight_ids:
        print(f"\nProcessing flight: {fid}")
        try:
            summary = api.get_flight_summary_full(
                flights=fid, 
                flight_datetime_from=date_from, 
                flight_datetime_to=date_to
            )
            print(f"Summary for {fid}:")
            print(json.dumps(summary, indent=2))
        except Exception as e:
            print(f"Error fetching summary for {fid}: {e}")
            continue

        data = summary.get("data", [])
        if not data:
            print(f"No summary data returned for flight {fid}")
            continue

        results[fid] = []
        # Process each summary entry (if more than one, there might be multiple segments)
        for entry in data:
            internal_id = entry.get("fr24_id")
            if not internal_id:
                print(f"No fr24_id found in summary entry: {entry}")
                continue
            try:
                # Create an output directory named using both the reported flight and its internal ID.
                export_dir = api.export_flight_data(internal_id, output_dir=f"data/{fid}_{internal_id}")
                print(f"Flight tracks for {fid} (internal id: {internal_id}) exported to: {export_dir}")
                results[fid].append({
                    "fr24_id": internal_id,
                    "summary": entry,
                    "export_dir": export_dir
                })
            except Exception as e:
                print(f"Error exporting flight tracks for {fid} (internal id: {internal_id}): {e}")
    return results

if __name__ == "__main__":
    token = os.environ.get("FLIGHTRADAR_API_KEY")
    if not token:
        raise ValueError("FLIGHTRADAR_API_KEY environment variable not set.")
    
    api = FR24API(token)
    
    # Flight numbers/callsigns from the scenario.
    flight_ids = ["DL2983", "DO61", "AA5308"]
    # Define a time window covering the incident.
    date_from = "2025-03-28T12:15:01Z"
    date_to   = "2025-03-28T23:18:01Z"
    
    investigation_results = investigate_incident(api, flight_ids, date_from, date_to)
    print("\nInvestigation results:")
    print(json.dumps(investigation_results, indent=2))

    # Save the investigation results to a JSON file.
    results_file = "investigation_results.json"
    with open(results_file, "w") as f:
        json.dump(investigation_results, f, indent=2)
    print(f"Investigation results saved to {results_file}")

Testing

The package includes a comprehensive test suite. To run the tests:

# From the project root
python run_tests.py

Roadmap

This project is under development. Some features to tackle next:

  • More API coverage
    Add support for more endpoints such as full flight positions, flight counts, historical endpoints and usage statistics

  • Add asynchronous support
    Provide async methods using asyncio so users can integrate the client in asynchronous applications

  • Caching and rate limit handling
    Add caching support to reduce redundant API calls and build in rate limit awareness to prevent overuse

  • Better docs
    Improve docs with more examples and an API reference

Contributing

Contributions are welcome. Please fork the repository and submit a pull request. Make sure to add tests for your changes and run tests with:

python run_tests.py

License

This project is licensed under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyfr24-0.1.3.tar.gz (22.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyfr24-0.1.3-py3-none-any.whl (21.2 kB view details)

Uploaded Python 3

File details

Details for the file pyfr24-0.1.3.tar.gz.

File metadata

  • Download URL: pyfr24-0.1.3.tar.gz
  • Upload date:
  • Size: 22.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for pyfr24-0.1.3.tar.gz
Algorithm Hash digest
SHA256 3ed4ead448d8503e70e64b59646022bffe70e8a2385de8040b1a44c88eb48c58
MD5 15454f5893c5c3957dc1d767ca6131e7
BLAKE2b-256 453e66a47f32a3ee5a34cd3d4dbd52173bdc7f5e184cd23488f049240fc3f219

See more details on using hashes here.

File details

Details for the file pyfr24-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: pyfr24-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 21.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for pyfr24-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 38b8a1c03f8071040de5b3bdec83dbeb7c6f1cad30bce23b9b2ae6ae82e0b088
MD5 2a8238b7757246fce8a3584fef658989
BLAKE2b-256 965dde7479f38e7a99e68f57d745bf85ce296d523302024a06ce98afd5bdbb91

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page