Messages API Python Sample

A sample of a python script to request and store information from the Messages API

import csv, json, requests

endpoint = 'https://ais.spire.com/messages'
token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjdXN0b21lciI6eyJpZCI6IjUzMiIsIm5hbWUiOiJNYXggQWJvdWNoYXIgU3BpcmUiLCJ1dWlkIjoiNTMyIn0sImlzcyI6InNwaXJlLmNvbSIsImlhdCI6MTU1OTc3MDM3NH0.Mm6axFI_0LPAJweQ0RqVK6DPFHJoE3bG1F38iHlVnSk'
headers = {'Authorization': "Bearer " + token, 'Accept': 'application/json'}

since_token = 'CiQ4NjdhZTI5OS03NWUzLTU2ZWUtYmZlNS1jZDYxOWYxNmQ1NTk='

fields_decoded = '&fields=decoded'
other_params = '&limit=1000'


request_url = endpoint + '?since=' + since_token + fields_decoded + other_params

response = requests.get(request_url, headers = headers).json()

all_fields = ['id',
'nmea',
'timestamp',
'msg_id',
'msg_type',
'created_at',
'mmsi',
'collection_type',
'flag',
'flag_short_code',
'longitude',
'latitude',
'position',
'speed',
'course',
'heading',
'status',
'accuracy',
'rot',
'maneuver',
'ais_version',
'name',
'length',
'width',
'ship_and_cargo_type',
'call_sign',
'imo',
'destination',
'eta',
'draught',
'dimensions',
'ship_type']

def write_json(data, file_name):
#takes data and file name and creates a json file
with open(file_name, 'w') as json_file:
json.dump(data, json_file)

def write_csv(data, file_name, columns):
#takes data and writes a csv with given headers

output_csv = open(file_name, 'w', newline='')
csv_writer = csv.DictWriter(output_csv, columns)

csv_writer.writeheader()
for line in data:
csv_writer.writerow(line)

output_csv.close()

write_json(response, 'json_output.json')

write_csv(response['data'], 'csv_output.csv', all_fields)