01時17分 EDT


 

空港追跡/情報


-または-


 

FlightXML 2.0 Documentation

About

Using the FlightXML API, programs can query the FlightAware live flight information and recent history datasets.

Queries for in-flight aircraft return a set of matching aircraft based on a combination of location, flight or tail number, origin and/or destination airport, aircraft type, and/or a low-to-high range of altitude and/or ground speed, among others. For each matching aircraft, data returned includes the flight or tail number, the aircraft type, origin and destination, time the last position was received, and the longitude, latitude, groundspeed, and altitude of that position. Matching flights' flight tracks can be requested as well.

For airports, FlightXML queries can return a list of scheduled flights, flights that have departed, flights that are enroute to the airport, and flights that have arrived at the airport.

Example Applications

Possible uses of FlightXML include:

  • Integrate FlightXML radar data with your existing flight operations software.
  • Use FlightXML in mobile apps for flight status or notifications.
  • Compile flight activity logs and records in your own database.
  • Create a customized alerting system based on the current status of your fleet.
  • Streamline flight planning by showing common routes as cleared by air traffic control between two airports.
  • Add real flight data to your simulations.
  • Show flight tracks in Google Earth.
  • Create visualizations of traffic patterns.
  • Add live flight information to your company's website.

Authentication

To access FlightXML 2.0, all requests must include a username and FlightXML Key (don't have one?). This data is transmitted via the "basic" HTTP Authentication standard, which is sent to the FlightXML server as a part of each HTTP request.

The web service libraries available in most programming languages allow you to directly specify a username and password as an argument for the request, so that the authentication is transparent to your application as it makes requests. However, with some libraries it may be necessary to manually encode the "user:key" in base64 and send the result in the "Authorization" header as part of each HTTP request.

If data security is a concern, all FlightXML services are also available over SSL by simply substituting "https" as the protocol for any flightxml.flightaware.com URLs.

Web Services / SOAP / WSDL

The primary protocol recommended for use with FlightXML 2.0 is the "Simple Object Access Protocol" (SOAP). Most modern SOAP implementations support use of "Web Services Description Language" (WSDL) definition file, which greatly simplifies accessing web services.

View: FlightXML 2.0 WSDL XML

Although you can read the WSDL and generate SOAP queries manually, it is recommended that you develop your applications using a SOAP library that automatically parses the WSDL and populates your application namespace with the FlightXML functions.

It is strongly suggested that you ensure that your applications cache the WSDL file so that it is not necessary to fetch and parse the WSDL for every request or instance of your application. This will vastly improve the performance and efficiency of your application.

The FlightXML 2.0 WSDL uses the "Document/Literal wrapped" method for encoding SOAP requests and responses. This is a newer method that recent SOAP industry standards dictate should be used instead of the older "RPC/Encoded" method that was used by the FlightXML 1.0 WSDL. Most modern SOAP client libraries fully support this newer method, although some older SOAP libraries are not yet compatible. The SOAP client libraries listed in the examples section have been tested to be compatible.

REST / JSON

FlightXML 2.0 can also be accessed using a light-weight "Representational state transfer" (REST) inspired protocol that returns its responses encoded in "JavaScript Object Notation" (JSON) format. This allows FlightXML to be used in environments in which it is inconvenient or impossible to invoke SOAP services, such as mobile phone applications, web browser applications, or server-side JavaScript environments.

To access any method, simply perform either a GET or POST request to http://flightxml.flightaware.com/json/FlightXML2/METHODNAME using standard CGI-style representation of the arguments. All requests made must supply the username and API Key as a "basic" Authorization HTTP header.

For example, the following URL is how you might request the current weather at John F. Kennedy airport (KJFK) in New York: http://flightxml.flightaware.com/json/FlightXML2/MetarEx?airport=KJFK&startTime=0&howMany=1&offset=0

Requests can be returned in "JSONP" format, allowing a web page to load the response in a way that avoids the same-domain security restrictions enforced by some browsers. To do this, simply specify the optional argument "jsonp_callback" with a value that is the name of the JavaScript function that should be invoked with the JSON data.

Pushed Notifications

Although FlightXML functionality is primarily intended to be accessed through a "pull" oriented request model using the SOAP/WSDL or REST/JSON interfaces, you can also opt to receive a "pushed" notification from our server to yours whenever certain flight events occur. Upon receiving a notification, your server-based application is sent basic information about the flight, its current status, and the triggering event. In response, your server-based application can initiate requests to FlightXML using the normal SOAP/WSDL or REST/JSON interfaces to obtain additional details. This can allow your application to intelligently reduce or increase the rate at which it makes other FlightXML requests at various parts of a flight, reducing your costs by avoiding unnecessary API requests during uneventful time periods.

To use pushed notifications, you must first call the "RegisterAlertEndpoint" method once to configure the URL endpoint where your server-based application can receive POST requests via HTTP or HTTPS. Once the URL endpoint has been registered, you can use the "SetAlert" method to define the triggering event conditions for the notifications that you want to receive.

When an event occurs, your URL endpoint will receive a POST request containing a JSON message. Although you can define alerts using either the SOAP/WSDL or REST/JSON interfaces, pushed notifications are always delivered in a JSON format. Delivery of each alert is attempted only once and is made on a best-effort policy. Your URL endpoint must accept the POST request and return a successful response within 5 seconds. It is recommended that your URL endpoint return a "Content-type" of "text/plain", and a short body (less than 32 characters) that acknowledges receipt of the pushed alert. If troubleshooting of alert delivery is required, the body responses for each delivered alert can be later reviewed on the Recently delivered alerts page.

Show example (JSON push notification)...

{
        "long_desc": "DAL116 arrived at KATL (Hartsfield-Jackson Intl) at 04:11PM EST from KTPA (Tampa Intl)",
        "short_desc": "DAL116 arrived at KATL from KTPA",
        "summary": "DAL116 arrived at KATL from KTPA",
        "eventcode": "arrival",
        "alert_id": 123456,
        "flight": {
                "ident": "DAL116",
                "aircrafttype": "B752",
                "origin": "KTPA",
                "destination": "KATL",
                "filed_ete": "01:15:00",
                "route": "ENDED4 CTY HONIE8",
                "faFlightID": "DAL116-1318311885-airline-0362",
                "filed_altitude": 360,
                "filed_airspeed_kts": 465,
                "filed_time": 1318532269,
                "filed_departuretime": 1318531500,
                "estimatedarrivaltime": 1318536216,
                "actualarrivaltime": 1318536660,
                "actualdeparturetime": 1318532220
        }
}

{
        "long_desc": "Delta #1752 (DC95) has just filed a flight plan.  It is scheduled to depart from Jackson-Evers Intl (KJAN) at 01:05PM CST heading for Hartsfield-Jackson Intl (KATL) for an estimated arrival at 03:34PM EST.",
        "short_desc": "DAL1752 (DC95) filed to depart KJAN @ 01:05PM CST for KATL @ ETA 03:34PM EST  (MEI LGC3)",
        "summary": "DAL1752 filed a flight plan KJAN -> KATL",
        "eventcode": "filed",
        ...rest of sample omitted for brevity...
}

{
        "long_desc": "Delta #116 (B752) departed Detroit Metro Wayne Co (KDTW) at 06:44PM UTC enroute to KATL (Hartsfield-Jackson Intl) for an estimated arrival at 08:30PM UTC",
        "short_desc": "DAL116 (B752) departed KDTW @ 06:44PM UTC for KATL ETA 08:30PM UTC",
        "summary": "DAL116 has departed KDTW for KATL",
        "eventcode": "departure",
        ...rest of sample omitted for brevity...
}
The description of the JSON attributes are as follows:
  • long_desc -- human-readable description of the event (sometimes longer than 80 characters). Not intended to be machine parsed, since this text is localized and the formatting is occasionally altered. (required)
  • short_desc -- human-readable description of the event (generally about 50 characters long). Not intended to be machine parsed, since this text is localized and the formatting is occasionally altered. (required)
  • summary -- human-readable summary of the event (generally about 20 characters long). Not intended to be machine parsed, since this text is localized and the formatting is occasionally altered. (required)
  • eventcode -- Indicates the type of event that has triggered this notification. May have one of the following values: (required)
    • filed -- details about an upcoming flight have been received (generally 1-2 hours before departure)
    • departure -- flight has departed from the origin (runway wheels-up or gate block-off)
    • arrival -- flight has arrived at destination (runway wheels-down or gate block-on)
    • cancelled -- flight has been cancelled prior to departure.
    • minutes_out -- flight is several minutes (usually 30-45 minutes) from its destination.
    • diverted -- flight has been diverted to another airport. To retrieve the new flight details, call FlightInfoEx to access the new flight by faFlightID or ident.
    • change -- some aspect of the flight plan has been modified, such as a departure time delay or a gate change.
  • alert_id -- Integer identifier of the alert that triggered the event. This is the value returned by SetAlert, and can be used with DeleteAlert to stop receiving notifications. (required)
  • flight -- Nested array with more details about the flight. Due to technical data limitations, some of these nested values (such as the actualarrivaltime and actualdeparturetime) may not yet be available for the latest event that is being alerted, but a subsequent call to FlightInfoEx might. Description of the nested values:
    • ident -- Operating identifier or registration for the aircraft (required)
    • aircrafttype -- Type of aircraft, if known (optional)
    • origin -- Origin airport, if known (optional)
    • destination -- Destination airport, if known (optional)
    • filed_ete -- Scheduled flight duration, if known (optional)
    • route -- Filed route waypoints, if known (optional)
    • faFlightID -- Unique FlightAware identifier for the flight, which can be used for FlightInfoEx or other methods (required)
    • filed_altitude -- Altitude of the flight plan, if known (optional)
    • filed_airspeed_kts -- Airspeed of the flight plan, in knots if known (optional)
    • filed_time -- Timestamp of when the flight plan was initially filed, in UNIX epoch seconds since 1970. (required)
    • filed_departuretime -- Scheduled flight departure time from origin, in UNIX epoch seconds since 1970. (required)
    • estimatedarrivaltime -- Estimated arrival time at destination, in UNIX epoch seconds since 1970. May be zero or absent if not known. (optional)
    • actualarrivaltime -- Actual time of arrival at destination, in UNIX epoch seconds since 1970. May be zero or absent if the flight has not yet arrived or the time is not yet known. (optional)
    • actualdeparturetime -- Actualtime of departure from origin, in UNIX epoch seconds since 1970. May be zero or absent if the flight has not yet departed or the time is not yet known. (optional)

Start building a great new aviation app with FlightXML 2.0.

(view legacy 1.0 documentation instead)

Examples (SOAP / WSDL)

Microsoft .NET

Show example (C#)...

Any Microsoft CLR .NET language should be usable to make requests to FlightXML 2.0, however this example is using C#. The procedure for using other languages may vary slightly. The steps described here use the command-line utilities to generate the WSDL stub and compile, but the steps can be adapted for use within the Visual Studio IDE.

Requirements
  • Microsoft Visual Studio 2003 or newer

Save the following file as test.cs, but substitute your actual username and API key:


using System.Net;
class test {
    public static void Main(string[] args)
    {
        FlightXML2 df = new FlightXML2();
        df.Credentials = new NetworkCredential("sampleUser", "abc123abc123abc123abc123abc123");
        df.PreAuthenticate = true;

        // get the flights currently enroute.
        EnrouteStruct r = df.Enroute("KAUS", 10, "", 0);
        foreach (EnrouteFlightStruct e in r.enroute) {
            System.Console.WriteLine(e.ident);
        }

        // get the weather.
        System.Console.WriteLine(df.Metar("KAUS"));
    }
}
    

Run commands:


wsdl.exe http://flightxml.flightaware.com/soap/FlightXML2/wsdl

csc.exe test.cs FlightXML2.cs

test.exe
    

PHP

Show example (SoapClient)...

The built-in SoapClient provided in PHP5 supports modern Document/Literal SOAP services, like FlightXML2.

Requirements
  • PHP5 or above
  • SoapClient
    • if building PHP from source, it must have been compiled with: ./configure --enable-soap
    • on Ubuntu or Debian based systems: sudo aptitude install php-soap
    • on RHEL/Fedora based systems: yum install php-soap

Save the following file as testsoap.php, but substitute your actual username and API key:


<?php

$options = array(
                 'trace' => true,
                 'exceptions' => 0,
                 'login' => 'sampleUser',
                 'password' => 'abc123abc123abc123abc123abc123abc123',
                 );
$client = new SoapClient('http://flightxml.flightaware.com/soap/FlightXML2/wsdl', $options);

// get the weather.
$params = array("airport" => "KAUS");
$result = $client->Metar($params);
print_r($result);

?>
    
Show example (nusoap)...

The NuSOAP toolkit for PHP can be used with FlightXML2.

Requirements
  • PHP4 or PHP5
  • NuSOAP (tested with 0.7.3)
    • on RHEL/Fedora based systems: yum install php-nusoap
    • on FreeBSD systems: cd /usr/ports/net/nusoap && make install
    • otherwise download from the SourceForge project site listed above

Save the following file as testsoap.php, but substitute your actual username and API key:


<?php

require_once( "nusoap/nusoap.php" );

$username = 'sampleUser';
$apiKey = 'abc123abc123abc123abc123abc123abc123';

$baseUri = "http://flightxml.flightaware.com/soap/FlightXML2";

date_default_timezone_set('UTC');
$client = new nusoap_client("$baseUri/wsdl",'wsdl');
$client->setCredentials($username,$apiKey);

if ( $client->getError() ) {
    die "Soap Constructor Error:" . $client->getError();
}

// get the weather.
$params = array("airport" => "KAUS");
$result = $client->call( "Metar", $params);
if ($client->fault) { //soap_fault
    die "Soap Fault: ". $client->faultcode . "(" . $client->faultstring . ")";
}
elseif ( $client->getError() ) {
    die "Soap Error: " . $client->getError();
}
else {
    print_r($result);
}

?>
    

Perl

Show example (SOAP::WSDL)...

The Perl CPAN module SOAP::WSDL is a modern SOAP client that fully supports Document/Literal services.

Requirements
  • Perl5 or above
  • SOAP::WSDL (tested with 2.00.10)
    • On FreeBSD systems: cd /usr/ports/devel/p5-SOAP-WSDL && make install
    • On RHEL/Fedora based systems: rpm -Uvh perl-SOAP-WSDL-2.00-xx-y.zz.rf.noarch.rpm (from the RPMForge repository)
    • Otherwise: perl -MCPAN -e 'install SOAP::WSDL'

Save the following file as testwsdl.pl, but substitute your actual username and API key:


#!/usr/bin/perl

use strict;
use SOAP::WSDL 2.0;

my $username = "sampleUser";
my $apiKey = "abc123abc123abc123abc123abc123";

my $baseUri = "http://flightxml.flightaware.com/soap/FlightXML2";

sub SOAP::WSDL::Transport::HTTP::get_basic_credentials {
    return $username => $apiKey;
}
sub SOAP::Transport::HTTP::Client::get_basic_credentials {
    return $username => $apiKey;
}

# Check if the SOAP result is an exception.
sub is_fault ($) {
    my $result = shift;
    return !defined($result) || ref($result) eq 'SOAP::Fault' || !defined($result->result);
}

# Singleton arrays are changed by SOAP::WSDL into scalars, making you handle either type.
sub coerce_arrayref ($) {
    my $val = shift;
    my @result = (ref($val) eq 'ARRAY' ? @$val : $val) if defined($val);
    return @result;
}

my $soap = SOAP::WSDL->new( wsdl => "$baseUri/wsdl" );

my $enroute = $soap->call('Enroute', EnrouteRequest => {'airport' => "KSMO", 'howMany' => 10, 'filter' => "", 'offset' => 0});
die if is_fault($enroute);

print "Aircraft en route to KSMO:\n";

my @flights = coerce_arrayref($enroute->result->{enroute});

foreach my $flight (@flights) {
   print $flight->{'ident'} . " (" . $flight->{'aircrafttype'} . ") \t" .
       $flight->{'originName'} . " (" . $flight->{'origin'} . ")\n";
}
    

Run commands:


./testwsdl.pl
    
Show example (SOAP::Lite)...

The Perl CPAN module SOAP::Lite is an old and well-known SOAP client for Perl, however it is not especially well-suited for modern "Document/Literal" SOAP services. However, it can be used if you are willing to make calls to explicitly declare the types of all function arguments using the SOAP::Data method. The "stubmaker.pl" utility and the SOAP::Lite WSDL support cannot be used.

Requirements
  • Perl5 or above
  • SOAP::Lite (tested with 0.710.10)
    • On RHEL/Fedora based systems: yum install perl-SOAP-Lite
    • On FreeBSD systems: cd /usr/ports/net/p5-SOAP-Lite && make install
    • Otherwise: perl -MCPAN -e 'install SOAP::Lite'

Save the following file as testlite.pl, but substitute your actual username and API key:


#!/usr/bin/perl

use strict;
use SOAP::Lite;

my $username = "sampleUser";
my $apiKey = "abc123abc123abc123abc123abc123";

my $baseUri = "http://flightxml.flightaware.com/soap/FlightXML2";

sub SOAP::Transport::HTTP::Client::get_basic_credentials {
    return $username => $apiKey;
}

my $soap = SOAP::Lite->default_ns($baseUri)->proxy("$baseUri/op")->autotype(0);

my $enroute = $soap->call("Enroute",
    SOAP::Data->name("airport" => 'KSMO'),
    SOAP::Data->name("howMany" => 10),
    SOAP::Data->name("filter" => ''),
    SOAP::Data->name("offset" => 0)
);
die if !defined($enroute) || $enroute->fault;

print "Aircraft en route to KSMO:\n";
    
my $flights = $enroute->result->{enroute};
    
foreach my $flight (@$flights) {
   print $flight->{'ident'} . " (" . $flight->{'aircrafttype'} . ") \t" .
       $flight->{'originName'} . " (" . $flight->{'origin'} . ")\n";
}
    

Run commands:


./testlite.pl
    

Java

Show example (Apache Axis1)...

Requirements

Save the following file as test.java, but substitute your actual username and API key:


import com.flightaware.flightxml.soap.FlightXML2.*;

class test {
    public static void main(String[] args)
    {
        try {
            FlightXML2Locator locator = new FlightXML2Locator();
            FlightXML2Soap df = locator.getFlightXML2Soap();
            FlightXML2SoapStub stub = (FlightXML2SoapStub)df;
            stub.setUsername("sampleUser");                                                                                                                                                                             
            stub.setPassword("abc123abc123abc123abc123");                                                                                                                                                              

            // Get the list of enroute aircraft.
            EnrouteStruct r = df.enroute(new EnrouteRequest("KAUS", 10, "", 0)).getEnrouteResult();
            for (EnrouteFlightStruct e: r.getEnroute()) {
                System.out.println(e.getIdent());
            }

            // Get the weather.
            System.out.println(df.metar(new MetarRequest("KAUS")).getMetarResult());
        } catch (javax.xml.rpc.ServiceException x) {
            System.err.println(x);
        } catch (java.rmi.RemoteException x) {
            System.err.println(x);
        }
    }
}

    

Run commands (Win32):


set CLASSPATH=axis-1_4\lib\axis-ant.jar;axis-1_4\lib\axis.jar;axis-1_4\lib\commons-discovery-0.2.jar;
  axis-1_4\lib\commons-logging-1.0.4.jar;axis-1_4\lib\jaxrpc.jar;axis-1_4\lib\log4j-1.2.8.jar;
  axis-1_4\lib\saaj.jar;axis-1_4\lib\wsdl4j-1.5.1.jar;.

wget -O wsdl2.xml http://flightxml.flightaware.com/soap/FlightXML2/wsdl

java org.apache.axis2.wsdl.WSDL2Java wsdl2.xml

javac test.java

java test
    
Show example (Apache Axis2)...

Requirements

Save the following file as test2.java, but substitute your actual username and API key:


import com.flightaware.flightxml.soap.flightxml2.*;
import org.apache.axis2.transport.http.*;

class test2 {
    public static void main(String[] args)
    {
        try {
            HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
            auth.setUsername("sampleUser");
            auth.setPassword("abc123abc123abc123abc123");

            FlightXML2Stub stub = new FlightXML2Stub();
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED, false);
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.AUTHENTICATE, auth);


            // Get the list of enroute aircraft.
            FlightXML2Stub.EnrouteRequest req1 = new FlightXML2Stub.EnrouteRequest();
            req1.setHowMany(10);
            req1.setAirport("KAUS");
            req1.setFilter("");
            req1.setOffset(0);
            FlightXML2Stub.EnrouteRequestE req1e = new FlightXML2Stub.EnrouteRequestE();
            req1e.setEnrouteRequest(req1);
            for (FlightXML2Stub.EnrouteFlightStruct e: 
                    stub.enroute(req1e).getEnrouteResults().getEnrouteResult().getEnroute()) {
                System.out.println(e.getIdent() + " (" + e.getAircrafttype() + ") \t" + 
                       e.getOriginName() + " (" + e.getOrigin() + ")");
            }

            // Get the weather.
            FlightXML2Stub.MetarRequest req2 = new FlightXML2Stub.MetarRequest();
            req2.setAirport("KAUS");
            FlightXML2Stub.MetarRequestE req2e = new FlightXML2Stub.MetarRequestE();
            req2e.setMetarRequest(req2);
            System.out.println(stub.metar(req2e).getMetarResults().getMetarResult());

        } catch (java.rmi.RemoteException x) {
            System.err.println(x);
        }
    }
}
    

Run commands (UNIX):



export CLASSPATH=$(echo . axis2-1.5.1/lib/*.jar | tr ' ' ':')

./axis2-1.5.1/bin/wsdl2java.sh -S . -uri http://flightxml.flightaware.com/soap/FlightXML2/wsdl

javac test2.java

java test2
    

Tcl

Show example (tclws)...

Requirements
  • TCL 8.5
  • TCLws (tested with 1.3.0)

Save the following file as test.tcl, but substitute your actual username and API key:


#!/bin/env tclsh8.5

package require WS::Client 1.3.0
package require base64

# uncomment these lines for debugging output
#::log::lvChannelForall stderr
#foreach lev [::log::levels] { ::log::lvSuppress $lev 0 }

set username "sampleUser"
set apiKey "abc123abc123abc123abc123abc123"
set baseUri "http://flightxml.flightaware.com/soap/FlightXML2"

set wsdl [::WS::Client::GetAndParseWsdl "$baseUri/wsdl"]
set apiname [::WS::Client::LoadParsedWsdl $wsdl]
set authheader [list Authorization "Basic [::base64::encode $username:$apiKey]"]


proc get_weather {airport} {
    global apiname authheader
    array set result [::WS::Client::DoCall $apiname Metar [list airport $airport] $authheader]

    puts "Weather for $airport:"
    puts $result(MetarResult)
}

proc get_flights {airport} {
    global apiname authheader
    array set result [::WS::Client::DoCall $apiname Enroute [list airport $airport howMany "10" fiter "" offset "0"] $authheader]
    array set flights $result(EnrouteResult)
    puts "Aircraft en route to $airport:"

    foreach flightdata $flights(enroute) {
        array unset flight
        array set flight $flightdata
        puts "$flight(ident) ($flight(aircrafttype)) $flight(originName) ($flight(origin))"
    }
}

get_weather "KSMO"
get_flights "KSMO"
    

Run commands:


tclsh8.5 test.tcl
    

Python

Show example (soapPy)...

Requirements

Save the following file as test.py, but substitute your actual username and API key:


#!/usr/bin/env python

from SOAPpy import Config, HTTPTransport, SOAPAddress, WSDL

username = 'sampleuser'
apiKey = 'abc123abc123abc123abc123abc123abc123'
wsdlFile = 'http://flightxml.flightaware.com/soap/FlightXML2'

# This is a custom HTTP transport that allows Basic Authentication.
class myHTTPTransport(HTTPTransport):
    username = None
    passwd = None

    @classmethod
    def setAuthentication(cls,u,p):
        cls.username = u
        cls.passwd = p

    def call(self, addr, data, namespace, soapaction=None, encoding=None,
             http_proxy=None, config=Config):

        if not isinstance(addr, SOAPAddress):
            addr=SOAPAddress(addr, config)

        if self.username != None:
            addr.user = self.username+":"+self.passwd

        return HTTPTransport.call(self, addr, data, namespace, soapaction,
                                  encoding, http_proxy, config)


# Make a FlightXML server request.
myHTTPTransport.setAuthentication(username, apiKey)
DF = WSDL.Proxy(wsdlFile, transport=myHTTPTransport)

enroute = DF.Enroute('KSMO',10,'',0)

flights = enroute['enroute']

print "Aircraft en route to KSMO:"
for flight in flights:
    print "%s (%s) \t%s (%s)" % ( flight['ident'], flight['aircrafttype'],
                              flight['originName'], flight['origin'])
    

Run commands:


./test.py
    
Show example (suds)...

Requirements

Save the following file as test.py, but substitute your actual username and API key:


#!/usr/bin/python

import sys
from suds import null, WebFault
from suds.client import Client
import logging


username = 'sampleUser'
apiKey = 'abc123abc123abc123abc123abc123abc123'
url = 'http://flightxml.flightaware.com/soap/FlightXML2/wsdl'


logging.basicConfig(level=logging.INFO)
api = Client(url, username=username, password=apiKey)
#print api

# Get the weather
result = api.service.Metar('KAUS')
print result

# Get the flights enroute
result = api.service.Enroute('KSMO', 10, '', 0)
flights = result['enroute']

print "Aircraft en route to KSMO:"
for flight in flights:
    print "%s (%s) \t%s (%s)" % ( flight['ident'], flight['aircrafttype'],
                                  flight['originName'], flight['origin'])

    

Run commands:


./test.py
    

Ruby

Show example (soap4r)...

Requirements
  • Ruby 1.8 or above
  • soap4r
    • For Ruby 1.8: gem install soap4r
    • For Ruby 1.9: gem install soap4r-ruby1.9
  • flightxml2-client-ruby

Save the following file as test.rb, but substitute your actual username and API key:


#!/usr/bin/env ruby
require 'FlightXML2Driver.rb'

username = 'sampleuser'
apiKey = 'abc123abc123abc123abc123abc123abc123'

$api = FlightXML2Soap.new(username, apiKey)

result = $api.enroute(EnrouteRequest.new('KSMO',10,'',0))

flights = result.enrouteResult.enroute

print "Aircraft en route to KSMO:\n"
flights.each { |flight|
    print "#{flight.ident} (#{flight.aircrafttype}) \t#{flight.originName} (#{flight.origin})\n"
}
    

Run commands:


./test.rb
    
Show example (savon)...

Requirements
  • Ruby 1.8 or above
  • Heavy metal Ruby SOAP client library (savon): homepage, github
    • gem install savon

Save the following file as test.rb, but substitute your actual username and API key:


#!/usr/bin/env ruby

require 'rubygems'
require 'savon'

SOAP_URL = 'http://flightxml.flightaware.com/soap/FlightXML2/wsdl'
USERNAME = 'sampleuser'
API_KEY = 'abc123abc123abc123abc123abc123abc123'

client = Savon::Client.new do
  wsdl.document = SOAP_URL
  http.auth.basic USERNAME, API_KEY
end

result = client.request(:enroute) do
  soap.body = {
    :airport => 'KSMO',
    :how_many => 10,
    :filter => '',
    :offset => 0
  }
end

flights = result.to_hash[:enroute_results][:enroute_result][:enroute]

print "Aircraft en route to KSMO:\n"
flights.each { |flight|
  print "#{flight[:ident]} (#{flight[:aircrafttype]}) \t#{flight[:origin_name]} (#{flight[:origin]})\n"
}
    

Run commands:


./test.rb
    

ColdFusion

Show example (cfm)...
Requirements
  • ColdFusion 8 or newer

Save the following file as test.cfm, but substitute your actual username and API key:


<cfscript>
    stAuth = structNew();
    stAuth.username = "sampleuser";
    stAuth.password = "abc123abc123abc123abc123abc123abc123";
    ws = createObject("webservice", "http://flightxml.flightaware.com/soap/FlightXML2/wsdl", stAuth);

    stEnroute = structNew();
    stEnroute.airport = "KSFO";
    stEnroute.howMany = 15;
    stEnroute.filter = "";
    stEnroute.offset = 0;

    aEnrouteStruct = ws.Enroute(stEnroute);
</cfscript>
<cfset EnrouteFlights = aEnrouteStruct.getEnrouteResult().getEnroute()>

<cfloop from="1" to="#ArrayLen(EnrouteFlights)#" index="i">
    <cfset dtime = DateAdd("s",EnrouteFlights[i].actualdeparturetime,DateConvert("utc2Local", "January 1 1970 00:00"))>
    <cfoutput>#EnrouteFlights[i].ident# = #EnrouteFlights[i].aircrafttype# departed at #dtime#<br></cfoutput>
</cfloop>

Examples (REST / JSON)

JavaScript

Show example (jQuery)...

This example is a static HTML page using JavaScript and jQuery to access FlightXML2 over its JSON interface. We recommend that this technique be only used in protected Intranet environment, since embedding your FlightXML API key in public web pages will allow other users to copy your key and make unauthorized use against your account.

Requirements
  • Web browser (tested with Firefox, Safari, Chrome. Not compatible with Internet Explorer)
  • Web server (static HTML)

Save the following file as test.html, but substitute your actual username and API key:


<html>
  <head>

<!--
 This example uses:
 * the FlightXML2 FlightInfoEx and DecodeFlightRoute functions over REST:
      http://flightaware.com/commercial/flightxml/
 * Google Maps API:
      http://code.google.com/apis/visualization/documentation/gallery/map.html
 * jQuery, hosted by Google API
-->


<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">

var fxml_url = 'http://YOUR_USERNAME:YOUR_API_KEY@flightxml.flightaware.com/json/FlightXML2/';


google.load("visualization", "1", {packages:["map"]});


// When the button is clicked, fetch the details about the entered flight ident.
$(document).ready(function() {
    $('#go_button').click(function() {
    $.ajax({
       type: 'GET',
       url: fxml_url + 'FlightInfoEx', 
       data: { 'ident': $('#ident_text').val(), 'howMany': 1, 'offset': 0 },
       success : function(result) {
          // display some textual details about the flight.
          var flight = result.FlightInfoExResult.flights[0];
          $('#results').html('Flight ' + flight.ident + ' from ' + flight.origin + ' to ' + flight.destination);

          // display the route on a map.
          fetchAndRenderRoute(flight.faFlightID);
       },
       error: function(data, text) { alert('Failed to fetch flight: ' + data); },
       dataType: 'jsonp',
       jsonp: 'jsonp_callback',
       xhrFields: { withCredentials: true }
       });
   });
});


// Fetch the planned route for a specified flight_id.
function fetchAndRenderRoute(flight_id) {
   $.ajax({
       type: 'GET',
       url: fxml_url + 'DecodeFlightRoute', 
       data: { 'faFlightID': flight_id },
       success : function(result) {
           // Initialize a data table using the Google API.
           var table = new google.visualization.DataTable();
           table.addColumn('number', 'Lat');
           table.addColumn('number', 'Lon');
           table.addColumn('string', 'Name');

           // Insert all of the points into the data table.
           var points = result.DecodeFlightRouteResult.data;
           table.addRows(points.length);
           for (rowid = 0; rowid < points.length; rowid++) {
                table.setCell(rowid, 0, points[rowid].latitude);
                table.setCell(rowid, 1, points[rowid].longitude);
                table.setCell(rowid, 2, points[rowid].name + ' (' + points[rowid].type + ')' );
           }

           // Render the data table into a map using Google Maps API.
           var map = new google.visualization.Map(document.getElementById('map_div'));
           map.draw(table, {showTip: true, showLine: true, lineWidth: 3, lineColor: '#009900'});
       },
       error: function(data, text) { alert('Failed to decode route: ' + data); },
       dataType: 'jsonp',
       jsonp: 'jsonp_callback',
       xhrFields: { withCredentials: true }
   });
}


</script>
  </head>

  <body>

    <form onsubmit="return false;">
    <p>Enter a flight ident to track: 
    <input type="text" name="ident" id="ident_text" value="COA423" />
    <input type="submit" id="go_button" value="Go" />
    </p>
    </form>

    <div id="results"></div>
    <div id="map_div" style="width: 400px; height: 300px"></div>

  </body>
</html>
    
Show example (Node.js)...

This example is a Node.JS console application written in Javascript that accesses FlightXML2 over its JSON interface.

Requirements

Save the following file as test.js, but substitute your actual username and API key:


/*
 * This requires: restler
 * To install, type 'npm install restler'
 * Tested with node.js v0.6.14
 */

var util = require('util');
var restclient = require('restler');

var fxml_url = 'http://flightxml.flightaware.com/json/FlightXML2/';
var username = 'YOUR_USERNAME';
var apiKey = 'YOUR_APIKEY';


restclient.get(fxml_url + 'MetarEx', {
    username: username,
    password: apiKey,
    query: {airport: 'KAUS', howMany: 1}
}).on('success', function(result, response) {
    // util.puts(util.inspect(result, true, null));
    var entry = result.MetarExResult.metar[0];
    util.puts('The temperature at ' + entry.airport + ' is ' + entry.temp_air + 'C');
});

restclient.get(fxml_url + 'Enroute', {
    username: username,
    password: apiKey,
    query: {airport: 'KIAH', howMany: 10, filter: '', offset: 0}
}).on('success', function(result, response) {
    util.puts('Aircraft en route to KIAH:');
    //util.puts(util.inspect(result, true, null));
    var flights = result.EnrouteResult.enroute;
    for (i in flights) {
      var flight = flights[i];
      //util.puts(util.inspect(flight));
      util.puts(flight.ident + ' (' + flight.aircrafttype + ')\t' + 
          flight.originName + ' (' + flight.origin + ')');
    }
});

    

Run commands:


node test.js
    

Microsoft classic ASP

Show example (classic ASP)...

This example demonstrates how to access FlightXML2 over its JSON interface using classic ASP.

Requirements

Save the following file as test.asp, but substitute your actual username and API key:



<script language="javascript" runat="server" src="json2.js"></script>
<%
Dim postData, httpRequest, jsonResponse

postData = "airport=KAUS"
postData = postData & "&howMany=10"
postData = postData & "&filter=airline"

Set httpRequest = Server.CreateObject("MSXML2.ServerXMLHTTP")
httpRequest.Open "POST", "http://flightxml.flightaware.com/json/FlightXML2/Arrived", False, "YOUR_USERNAME", "YOUR_APIKEY"
httpRequest.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
httpRequest.Send postData

If httpRequest.status = 200 Then
    Set jsonResponse = JSON.parse(httpRequest.responseText)

    For Each flight In jsonResponse.ArrivedResult.arrivals
        Response.Write("Flight " & flight.ident & " is arriving from " & flight.origin & "<br>") 
    Next
Else
    Response.Write("Error occurred")
End If

Set httpRequest = Nothing
%>
    

Objective C

Show example (Objective C)...

This example demonstrates how to access FlightXML2 over its JSON interface using Objective C on Mac OS X.

Requirements
  • Download and install Xcode from the Apple Store
  • File->New->Project->Command line tools (type choose Foundation)

Save the following file as test.m, but substitute your actual username and API key:


#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        
        NSString* path = @"http://YOUR_USERNAME:YOUR_APIKEY@flightxml.flightaware.com/json/FlightXML2/Enroute?airport=KSMO&filter=''&howMany=10&offset=0";
        
                
        NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
        
        [_request setHTTPMethod:@"GET"];
        
        
        NSURLResponse *response = nil;
        
        NSError *error = nil;
        
        
        NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
        
        if(nil != error)
        {
            NSLog(@"Error: %@", error);
        }
        else
        {
            
            NSMutableDictionary* json = nil;
            
            
            if(nil != _connectionData)
            {
                json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
            }
            
            if (error || !json)
            {
                NSLog(@"Could not parse loaded json with error:%@", error);
            }
            else
            {
                
                NSMutableDictionary *routeRes;
                
                routeRes = [json objectForKey:@"EnrouteResult"];
                
                NSMutableArray *res;
                
                res = [routeRes objectForKey:@"enroute"];
                
                for(NSMutableDictionary *flight in res)
                {
                    NSLog(@"ident is %@, aircrafttype is %@, originName is %@, origin is %@", [flight objectForKey:@"ident"], [flight objectForKey:@"aircrafttype"], [flight objectForKey:@"originName"], [flight objectForKey:@"origin"]);
                    
                }
                
            }
            
            _connectionData = nil;
        }
        
    }
    return 0;
}

Ruby

Show example (Ruby)...

Requirements
  • Ruby 1.9 or above
  • FlightXML2 JSON REST Client for Ruby by auzroz: github
    • gem install FlightXML2RESTDriver

Save the following file as test.rb, but substitute your actual username and API key:


#!/usr/bin/env ruby

require './FlightXML2RESTDriver.rb'
require './FlightXML2Rest.rb'

username = 'YourUserName'
apiKey = 'YourAPIKey'

# This provides the basis for all future calls to the API
test = FlightXML2REST.new(username, apiKey)

# Enroute
print "Aircraft en route to KSMO:\n"
result = test.Enroute(EnrouteRequest.new('KSMO', 'ga', 15, 0 ))
pp result.enrouteResult

    

Run commands:


./test.rb
    

Changelog

The following list summarizes the functional changes between FlightXML 1.0 and FlightXML 2.0 to date:

  • (2010-06) Renamed METAR to Metar, TAF to Taf, NTAF to NTaf
  • (2010-06) Renamed MapFlight_Beta to MapFlight, countAirportOperations to CountAirportOperations, blockIdentCheck to BlockIdentCheck
  • (2010-06) Added FleetScheduled
  • (2010-06) Added CountAllEnrouteAirlineOperations
  • (2010-06) Added AllAirlines
  • (2010-06) Added AirlineInfo
  • (2010-06) Added beta DistressedAircraftDetector (since removed)
  • (2010-06) Added RoutesBetweenAirportsEx
  • (2010-06) Added GetHistoricalTrack
  • (2010-06) Added SetMaximumResultSize
  • (2010-06) Added MetarEx
  • (2010-06) Added SearchBirdseyeInFlight
  • (2010-06) Changed RoutesBetweenAirportsEx to return ArrayOfRoutesBetweenAirportsExStruct and add min/max altitude, last departure, next_offset
  • (2010-06) Added SearchBirdseyePositions
  • (2010-07) Added MapFlightEx
  • (2010-07) Added FlightInfoEx and GetFlightID
  • (2010-07) Removed beta DistressedAircraftDetector, which can be implemented in terms of SearchBirdseyeInFlight with "{!= physClass P} {> circles 3}"
  • (2010-07) Added DecodeFlightRoute and DecodeRoute
  • (2010-07) Changed GetHistoricalTrack to take faFlightID as argument
  • (2011-02) Added AirlineFlightInfo
  • (2011-02) Changed GetHistoricalTrack, DecodeFlightRoute, MapFlightEx, and AirlineFlightInfo to allow "ident@departureTime" syntax to optionally be used instead of a faFlightID, saving the need to explicitly use GetFlightID first.
  • (2011-02) Changed FlightInfo, FlightInfoEx, InFlightInfo, GetLastTrack, GetFlightID, TailOwner, and MapFlight to handle codeshare or alternate ident lookups automatically. GetHistoricalTrack, DecodeFlightRoute, MapFlightEx, and AirlineFlightInfo allow codeshare and alternte idents when using the "ident@departureTime" syntax.
  • (2011-03) Added AirlineFlightSchedules (since removed)
  • (2011-04) Removed AirlineFlightSchedules
  • (2011-05) Added AirlineInsight
  • (2011-07) Added InboundFlightInfo. Enhanced SearchBirdseyeInFlight to add the special operators: orig_or_dest, airline, aircraftType, ident.
  • (2011-09) Introduced support for REST/JSON clients of all current FlightXML2 methods.
  • (2011-10) Introduced support for pushed FlightXML flight alerts. Added GetAlerts, SetAlert, DeleteAlert, RegisterAlertEndpoint methods.
  • (2012-03) Added support for Australian airspace. To receive these flights, you must use the API key request page to obtain a new key and agree to the distribution terms. Otherwise such flights may appear in your results with an ident of "BLKFA" and its other fields will be blank/zero.
  • (2012-04) Enhanced FlightInfoEx to allow a faFlightID to be requested.
  • (2012-04) Changed AirportInfo to now return timezones conforming to the official IANA zoneinfo database.
  • (2012-04) Changed FlightInfo and FlightInfoEx to now return results sorted by filed_departuretime instead of file_time.
  • (2012-04) Changed RoutesBetweenAirportsEx to now allow maxDepartureAge and maxFileAge to be specified as blank to search the maximum routes available.
  • (2012-09) Added AirlineFlightSchedules again
  • (2013-03) FlightInfo and FlightInfoEx can now return results for tail/registration numbers for flights operating under a different callsign. FlightInfoEx also now supports "ident@departureTime" syntax, avoiding the need to call GetFlightID first
  • (2013-12) Added ident_or_reg operator to SearchBirdseyeInFlight