FlightAware FlightXML and R
I’ve been slowly fixing the typos and making small revisions to one of my R tutorials that includes some aviation data. For this particular tutorial, I was only looking at three flights, so I just copy-pasted the tracklogs from the FlightAware site, and then I cleaned them up. But I’m starting to make plans for something more sophisticated, so I decided to spend part of yesterday afternoon learning more about the FlightXML API.
I’ve experimented with it before using some of their sample code in Python. I had to install a bunch of packages that I wasn’t entirely thrilled with in order to get it to work. And the example code they had available at the time seemed to assume that the person using it was much more experienced with Python than I am, and it was based on SOAP, which I’m not familiar with at all. It was OK, but I wasn’t happy working on it.
Since I’m much more comfortable with R, I decided to see if I could figure out how to
get data from FlightXML from R. (They don’t have any sample code in R on their site.)
I decided to use httr
, and it seemed to go pretty well.
Here’s my sample code (mostly so that I don’t lose it). If you want to run it yourself, you would need a FlightXML API key of your very own, which you can get for free. Queries from FlightXML2 cost money; the new FlightXML3 will have monthly pricing. So far all my experiments have racked up about 57 cents in charges, which makes this one of my cheaper hobbies.
# To get an API key, see: https://flightaware.com/commercial/flightxml/
username <- "jane_doe"
my_API_key <- "abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd"
library(httr)
library(jsonlite)
# Example: Let's get the weather at San Diego International Airport (KSAN)
# MetarEx docs: https://flightaware.com/commercial/flightxml/explorer/#op_MetarEx
# Makes the request; returns what FlightAware calls a ArrayOfMetarStruct.
request <- GET("http://flightxml.flightaware.com/json/FlightXML2/MetarEx?airport=KSAN&startTime=0&howMany=1&offset=0",
authenticate(user=username, password=my_API_key, type = "basic"))
stop_for_status(request)
# Converts this response to a more useful data structure, mostly made of lists
KSAN_weather <- content(request)
# We can now index into this and ask some questions
# How windy is it?
KSAN_weather$MetarExResult$metar[[1]]$wind_friendly
# What time was the request?
as.POSIXct(KSAN_weather$MetarExResult$metar[[1]]$time, origin="1970-01-01")
# We can flatten our data sturture into a dataframe with jsonlite::flatten
flat_KSAN_weather <- flatten(as.data.frame(KSAN_weather))
# What are the clouds like?
flat_KSAN_weather$MetarExResult.metar.cloud_friendly
# How warm is it?
flat_KSAN_weather$MetarExResult.metar.temp_air
# How warm is it in 'Murica?
1.8 * flat_KSAN_weather$MetarExResult.metar.temp_air + 32