Using the MarketStack API in a Ruby CLI App
When I first started working on this CLI (Command Line Interface) application I was unsure of what capability I wanted it to have. I knew I wanted it to somehow pull raw data from the New York Stock Exchange, which would allow the program to retrieve latest price updates, volume, and what index that stock was held in. The most common way to do something like this is to use an API. An API (Application Programming Interface) is an information gateway that allows information and data to be requested and used in a program. You will be accepted permission to the data using the proper endpoints given by the API. The program would start by sending a GET request to the API requesting data to be sent back to the program to be used.
From here, you can go and look beforehand how your data will be structured when sent back to your program, so you know how to handle it. In MarketStack, there are 9 different API endpoints to choose from. Each with their own different data. We only need 2 for what we want to achieve, the “Tickers” endpoint and the “End Of Day” endpoint.
Before we request this data, we’re going to need an access key. Do this by pressing “Free API Key” on the screen. When starting your code, your first method should be responsible for requesting the first API endpoint, Tickers. You’re going to want to start by setting a variable that holds the response of the API, see below.
Now that variable holds a data structure full of stock market data, now it just needs parsed. We do this by using “JSON.parse().
Once its parsed and stored into our hash variable, we can then go on to sort our hash into an array that will be filled with individual stocks, collectively sorted together.
Now you have an array that can be sorted in anyway you want. You can search for whatever stock you’d like by their symbol (AAPL = Apple Inc). To retrieve stock price data using the End Of Day endpoints, you would request it the same way. Here is an example: