I’ve always wanted to do a project with a live public transport api!
I found mta’s realtime data feed apis here.
I first worked on creating a REST api using node js server. I had a simple get request to the mta api which I got a ton of gibberish on. I did some googling which helped me realize it was a specific format (GTFS). I then found a library called GTFSrealtimebindings to help me decode the GTFS into an array that I can read.
What this does is runs the async function to retrieve the data from the mta url. When the user accesses the server’s url, it returns the data array.
let data = [];
(async () => {
try {
const response = await fetch("<https://api-endpoint.mta.info/Dataservice/mtagtfsfeeds/nyct%2Fgtfs-ace>", {
headers: {
"x-api-key": "CW9mrwIkgX3h8TLJwbJmb1J9AeecajQUaQ5fevxU",
// replace with your GTFS-realtime source's auth token
// e.g. x-api-key is the header value used for NY's MTA GTFS APIs
},
});
if (!response.ok) {
const error = new Error(`${response.url}: ${response.status} ${response.statusText}`);
error.response = response;
throw error;
process.exit(1);
}
const buffer = await response.arrayBuffer();
const feed = GtfsRealtimeBindings.transit_realtime.FeedMessage.decode(
new Uint8Array(buffer)
);
feed.entity.forEach((entity) => {
data.push(entity);
if (entity.tripUpdate) {
data.push(entity.tripUpdate);
console.log(entity.tripUpdate);
}
});
}
catch (error) {
console.log(error);
process.exit(1);
}
})();
router.get("/", (req, res) => {
res.send(data);
});
Because I couldn’t decide which api i wanted (ac train or subway alerts), created two routes for access /actrain or /subwayalerts
Now that that worked, I served it using heroku so that I can access it online:
https://mta-api-8604211baccf.herokuapp.com/subwayalerts
https://mta-api-8604211baccf.herokuapp.com/actrain
Unfortunately, getting it on P5 is where I got stuck. I tried a few things but it kept giving me this same error with no additional information I can work on. Things I tried: