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.
Possible uses of FlightXML include:
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.
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.
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.
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. You can also use the FlightXML Push Notification Testing Interface page to manually generate sample messages to be sent to your endpoint.
{
"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:
(view legacy 1.0 documentation instead)
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. For this example we used Visual Studio 2017 but the same process should work for Visual Studio 2013 or newer.
RequirementsExample Steps
This example will step through creating a unit test in Visual Studio 2017 that queries FlightXML2 and writes the results out to the console. It is meant to give an overall view of the requirements so that you can adopt this to your own project.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="FlightXML2Soap">
<security mode="Transport">
<transport clientCredentialType="Basic" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://flightxml.flightaware.com/soap/FlightXML2/op"
binding="basicHttpBinding" bindingConfiguration="FlightXML2Soap"
contract="FlightXML2.FlightXML2Soap" name="FlightXML2Soap" />
</client>
</system.serviceModel>
</configuration>
Here are the contents of our UnitTest1.cs file that connects to FlightXML2 to retrieve Enroute flights for Houston Hobby and METAR info for Austin.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using fxmltext.FlightXML2;
namespace fxmltext
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
FlightXML2SoapClient client = new FlightXML2SoapClient();
client.ClientCredentials.UserName.UserName = "sampleUser";
client.ClientCredentials.UserName.Password = "abc123abc123abc123abc123abc123";
EnrouteStruct r = client.Enroute("KHOU", 10, "", 0);
foreach(EnrouteFlightStruct e in r.enroute)
{
Console.WriteLine(e.ident);
}
Console.WriteLine(client.Metar("KAUS"));
}
}
}
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.
RequirementsSave 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 https://flightxml.flightaware.com/soap/FlightXML2/wsdl
csc.exe test.cs FlightXML2.cs
test.exe
The built-in SoapClient provided in PHP5 supports modern Document/Literal SOAP services, like FlightXML2.
RequirementsSave 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);
?>
The NuSOAP toolkit for PHP can be used with FlightXML2.
RequirementsSave 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);
}
?>
The Perl CPAN module SOAP::WSDL is a modern SOAP client that fully supports Document/Literal services.
RequirementsSave 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
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.
RequirementsSave 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
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
Requirements
Save the following file as test2.java, but substitute your actual username and API key:
import org.apache.axis2.transport.http.*;
import org.apache.axis2.transport.http.impl.httpclient4.HttpTransportPropertiesImpl;
import com.flightaware.flightxml.soap.flightxml2.*;
class test2 {
public static void main(String[] args)
{
try {
HTTPAuthenticator auth = new HttpTransportPropertiesImpl.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.
EnrouteRequest req1 = new EnrouteRequest();
req1.setHowMany(10);
req1.setAirport("KAUS");
req1.setFilter("");
req1.setOffset(0);
EnrouteRequestE req1e = new EnrouteRequestE();
req1e.setEnrouteRequest(req1);
for (EnrouteFlightStruct e:
stub.enroute(req1e).getEnrouteResults().getEnrouteResult().getEnroute()) {
System.out.println(e.getIdent() + " (" + e.getAircrafttype() + ") \t" +
e.getOriginName() + " (" + e.getOrigin() + ")");
}
// Get the weather.
MetarRequest req2 = new MetarRequest();
req2.setAirport("KAUS");
MetarRequestE req2e = new 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.7.4/lib/*.jar | tr ' ' ':')
./axis2-1.7.4/bin/wsdl2java.sh -S . -uri http://flightxml.flightaware.com/soap/FlightXML2/wsdl
javac test2.java
java test2
Requirements
Steps to start developing a JAX-WS Web Service Client in NetBeans
Observations
Additional documentation on developing a JAX-WS Web Service Client in NetBeans can be found on netbeans.com:
Client Example
In order to have a working example, you need to substitute your actual username and API key in the Authenticator, in the new PasswordAuthentication("username", "key".toCharArray());.
import java.util.List;
import com.flightaware.flightxml.soap.flightxml2.*;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyFlightXML {
public static void main(String[] args) {
// The java.net.Authenticator class is used to enable authentication and to provide access to a store of usernames and passwords
// which are then used in the respective authentication schemes.
// When authentication is required, the system will invoke one of the requestPasswordAuthentication() methods
// which in turn will call the getPasswordAuthentication() method of the registered object.
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "key".toCharArray());
}
});
// Connect and authenticate
FlightXML2 locator = new FlightXML2();
//if you don't have wsdl already loaded:
//String WSDL_URL = "https://flightxml.flightaware.com/soap/FlightXML2/wsdl";
//URL wsdl_url = null;
//try {
// wsdl_url = new URL(WSDL_URL);
//} catch (MalformedURLException ex) {
// Logger.getLogger(MyFlightXML.class.getName()).log(Level.SEVERE, null, ex);
//}
//FlightXML2 locator = new FlightXML2(wsdl_url);
// get the stub that provides the methods needed
FlightXML2Soap df = locator.getFlightXML2Soap();
///////////////////////////////////////////////////////////////////////////////////////
// Get the list of enroute aircraft.
System.out.println("\n---------- PRINT ENROUTE AIRCRAFT ----------\n");
// set request first:
EnrouteRequest enroute_req = new EnrouteRequest();
enroute_req.setHowMany(10);
enroute_req.setAirport("KAUS");
enroute_req.setFilter("");
enroute_req.setOffset(0);
// retrieve result of request
EnrouteStruct struct = (df.enroute(enroute_req)).getEnrouteResult();
for (EnrouteFlightStruct flight : struct.getEnroute()) {
// print the ident; EnrouteFlightStruct offers many more methods
System.out.println(flight.getIdent());
}
///////////////////////////////////////////////////////////////////////////////////////
// get the weather
System.out.println("\n---------- PRINT WEATHER ----------\n");
// set request first:
MetarRequest weather_req = new MetarRequest();
weather_req.setAirport("KAUS");
// retrieve result of request
MetarResults weather = df.metar(weather_req);
System.out.println(weather.getMetarResult());
///////////////////////////////////////////////////////////////////////////////////////
// show all airlines
System.out.println("\n---------- PRINT ALL AIRLINES ----------\n");
// set request first:
AllAirlinesRequest all_airlines_req = new AllAirlinesRequest();
// retrieve result of request
AllAirlinesResults all_airlines_result = df.allAirlines(all_airlines_req);
// use provided sequence of methods to get to the airline string
ArrayOfString array = all_airlines_result.getAllAirlinesResult();
List<String> list_all_airlines = array.getData();
// walk the list result
for (String airline : list_all_airlines) {
System.out.println(airline);
}
}
}
Requirements
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
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, timeout=None):
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
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
Requirements
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
Requirements
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
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>
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.
RequirementsSave 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': 10, 'offset': 0 },
success : function(result) {
if (result.error) {
alert('Failed to fetch flight: ' + result.error);
return;
}
for (flight of result.FlightInfoExResult.flights) {
if (flight.actualdeparturetime > 0) {
// display some textual details about the flight.
$('#results').html('Flight ' + flight.ident + ' from ' + flight.origin + ' to ' + flight.destination);
// display the route on a map.
fetchAndRenderRoute(flight.faFlightID);
return;
}
}
alert('Did not find any useful flights');
},
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) {
if (result.error) {
alert('Failed to decode route: ' + result.error);
return;
}
// 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="UAL423" />
<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>
This example is a Node.JS console application written in Javascript that accesses FlightXML2 over its JSON interface.
RequirementsSave 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
This example demonstrates how to access FlightXML2 over its JSON interface using classic ASP.
RequirementsSave 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
%>
This example demonstrates how to access FlightXML2 over its JSON interface using Objective C on Mac OS X.
RequirementsSave 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;
}
Requirements
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
The following list summarizes the functional changes between FlightXML 1.0 and FlightXML 2.0 to date: