How to query an API for your React Project!

hellonathanchung

Nathan Chung

Posted on October 9, 2020

How to query an API for your React Project!

This post requires previous knowledge/understanding of React and JS

For my capstone project, I noticed that there aren't many user forums giving access to Stock Market data. After spending some time going through stock market documentation, I now understand why.

What is an API?

API stands for Application Programming Interface. Many companies build API's for users to use and create their own awesome applications. In our case, we want to look into the stocks and a company like MarketStack for our project.

First, we'll be using Insomnia to fetch market data and MarketStack as our API. Luckily, most API's return JSON readable format which we'll make it easy for us to use!

Insomnia allows you to test and query API's without needing to have everything built out. We'll be using Insomnia to test GET requests from MarketStack. Make sure to install Insomnia Core

MarketStack provides free real-time and historical stock market data with thousands of tickers via REST API in JSON format, access to tons of exchanges, and you get 1000 queries a month. (10,000 for $10.00)

Head on over to https://marketstack.com/ and click the following.

image

Once you're there, you'll be directed to sign up and register and you'll then have your own API key.

Save it and write it down and make sure you don't expose it publicly.

If you head over to MarketStack's documentation, there is a ton of data; end-of-day data, intraday data, stock exchanges, currencies, and everything you can think of... financially.

The basic way you'll write a query for Apple like this:

http://api.marketstack.com/v1/eod?access_key=YOURAPIKEY&symbols=AAPL
Enter fullscreen mode Exit fullscreen mode

Using Insomnia

Now let's take that to Insomnia.

In this program, you have a bunch of ways to test API's, send data to your own backend, and more! For our example, we'll send a fetch request to get information on Apple.

Take the same query from above and paste it into Insomnia. Make sure your options are set to 'GET'. You'll receive a 200 OK message along with all your stock data!

stocks

Now that we have our data, let's see an example of its usage within a React project.

Hiding your API key

  1. Create a .env file within your React at the highest level. This is important because in most cases, API keys are private and for you/your group. Exposing your API key could literally be very costly.

.env

then in .gitignore be sure to add .env to prevent uploading to Github!

Now in your .env, set your API key by starting off with
REACT_APP_MARKETSTACK_API_KEY='YOUR_API_KEY'

Replace the single quotes with your own API key. Make sure to include REACT_APP, otherwise it won't work.

run npm start to spin up your server and let's check if everything worked correctly.

Testing Fetch Requests

Now to ensure that it's working, go to a component and type the following:

    componentDidMount() {
        console.log(process.env.REACT_APP_MARKETSTACK_API_KEY)
    }
Enter fullscreen mode Exit fullscreen mode

If all things went correctly, you should see your API key now showing in the console.

  1. Now the API key is hidden we can fetch certain data. Within your React application, we can run fetch.

In one of my components, I'm going to run a fetch request.

We'll break it down into a few parts.

let API_KEY = process.env.REACT_APP_MARKETSTACK_API_KEY

let stockTicker = 'MSFT'

let URL = `http://api.marketstack.com/v1/eod access_key=${API_KEY}&symbols=${stockTicker}`

Enter fullscreen mode Exit fullscreen mode

Let me explain what we did. We set the variable API_KEY to our API Key stored in our .env file. We call it with process.env

We set stockTicker to MSFT for now so that we can include it within our URL, taking our API and providing the previous variables within the link.

This way, we're avoiding hardcoding data, except for the stockTicker which we'll implement later, and reducing the lines of code.

Now, let's run our fetch request.

Most fetch requests are done in this format:

fetch('http://example.com/stocks.json')
  .then(response => response.json())
  .then(data => console.log(data));
Enter fullscreen mode Exit fullscreen mode

Here, we're fetching JSON data from an API and sending it to the console. The data is not instantly set, but instead, we're returned a promise containing the response. We extract that JSON content but using .json() on the response and then can handle that data in different ways such as setting it to state or running console.log.

Data can be anything but make sure that the variable names are consistent. For example, data can be stockData if that helps writing cleaner code. Especially, if you're working with multiple fetch requests.

If you have your own backend

    componentDidMount() {
        this.fetchStock()
    }
fetchStock() {
        let API_KEY = process.env.REACT_APP_MARKETSTACK_API_KEY
        let stockTicker = 'MSFT'
        let URL = `http://api.marketstack.com/v1/eod access_key=${API_KEY}&symbols=${stockTicker}`

        fetch(URL).then(res => res.json())
        .then(data => console.log(data))
Enter fullscreen mode Exit fullscreen mode

What you should get in return is a series of Stock data by day.
fetch data

There you have it! The next things you could do is map the X axis by day and the Y axis by highs and lows for that day.

:)

💖 💪 🙅 🚩
hellonathanchung
Nathan Chung

Posted on October 9, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related