Call the endpoint and generate a CSV
In this tutorial, we are gonna look at how to call the Tracking History endpoint, retrieve the desired dataset, and export the results in a CSV file.
#
Source codeYou can find and download the source code for this example here.
#
Geo filteringFirst, let's look at a particular area, such as a larger Paris area, represented by this GeoJSON:
Which is represented like that on a map:
#
Calling the Tracking History APIUsing the coordinates previously shown, we can filter the API results for the area we want:
- Latitude range:
48.122101028190805,49.5822260446217
need to be South to North, so values can vary from-90
to90
. - Longitude range:
0.9008789062499999,3.8452148437499996
need to be West to East, so values can vary from-170
to170
.
#
Parsing resultsWe can now parse the response, which is a set of JSON objects each separated by a new line. We can then just simply iterate through those lines and parse the JSON using response.iter_lines
object in each of them.
#
Writing CSV outputFinally, we can now create a new output file data.csv
.
We need to find the JSON item with the most keys in it, to have all the necessary CSV columns created. For that we can use max(data, key=lambda item: len(item.keys()))
, which is gonna loop through the JSON objects and count their respective entries, returning the element with the biggest number.
With this newly obtained element with the most entries, we write our first row containing the CSV's headers: csv_writer.writerow(most_keys.keys())
.
We are now all ready to write all the contents of the CSV by looping through the entries again, and getting the associated values for each key, or ""
if that key is not present in the object.