Wix .fetch

Codecademy Team
Utilize "wix-fetch" to make a GET request and take your website to the next level.

Getting Information

Information is continuously changing - things like hit song charts, the stock market, and the weather are in constant flux. For any information to be relevant, it has to stay up-to-date. Now, imagine if you had a site that maintains the prices of stocks to help you make better trading decisions.

To implement this process, we could create a full backend application that continually tracks stock prices on top of our frontend website. Even so, this complex solution could take days, weeks, or even months to complete. Another solution is to manually create a website that tracks stock prices in real-time, however, we would have to constantly update the website’s stock prices which is just not feasible.

Instead, a practical solution is to “ask” other existing websites for stock price information to avoid reinventing the wheel and cut down on development time. This handy solution is where the wix-fetch module comes into place.

The wix-fetch Module

For traditional web development, the JavaScript Fetch API is used to make data requests to other websites. Wix has streamlined this complex process through its very own wix-fetch module, which makes it even easier to access and use the data that is returned from other websites.

The wix-fetch module comes out-of-the-box with two important functions: fetch() and getJSON().

  • Wix’s fetch() method is used on both the frontend and the backend to retrieve the specified resource from the network.
    • We’ll cover more in a later article, but sometimes, these requests must be made via the backend.
  • The getJSON() function is used on the frontend and retrieves the specified resource from the network in the JSON format.

In this article, we’ll focus on learning how to use Wix’s getJSON() function to easily request data.

The getJSON() function

To understand why the getJSON() function is invaluable to our Wix websites, we must first learn the basics of JavaScript Object Notation (JSON). Put simply, JSON is a text syntax used for storing and exchanging data between the browser and server where each data object can contain multiple name/value pairs. This standardized format allows data to be stored in a predictable way so that when we request this data, we know what to expect and how to use it.

{
"stocks": [
{ "stockName": "Apple", "price": 393.43 },
{ "stockName": "Walmart", "price": 131.47 },
{ "stockName": "Tesla", "price": 1643.00 }
]
}

Above is an example of JSON containing a stocks array of three different stocks’ information.

Like other features of Wix, the getJSON() function handles the complexity behind the scenes by allowing us to easily retrieve JSON from a specified location using a GET request. The GET request is the “ask” that enables us to retrieve data from other websites.

Implementing getJSON()

To retrieve JSON data from the specified location, we use the following boilerplate syntax in the Wix Code Panel:

import { getJSON } from 'wix-fetch';
getJSON('https://someapi.com/api/someendpoint')

Let’s examine the getJSON() request syntax above:

  • We must import the getJSON function from the wix-fetch module.
  • Next, we need to call the getJSON() function to retrieve the JSON data from the specified location.
  • The getJSON() function expects a url string argument that tells it which site to ask information from (the specified location for the example is this mocked up endpoint: “https://someapi.com/api/someendpoint”).

Handling the getJSON() Response

Wix’s getJSON() function is an asynchronous operation that returns a Promise containing one of two values:

  • Fulfilled: the JSON response of the fetch operation (the data is received).
  • Rejected: the error that caused the rejection (there was a problem with retrieving the data).

To handle the two potential values of the Promise object from getJSON(), we need to chain the .then() and .catch() methods.

import { getJSON } from 'wix-fetch';
getJSON("https://someapi.com/api/someendpoint")
.then(json => console.log(json.importantData))
.catch(err => console.log(err));

Taking note of the code above:

  • We called getJSON() on the specified url to get some JSON data.
  • The .then() method enables us to get the json data response from the getJSON() function.
  • In .then()’s callback function, we use the json data that is returned by printing out json.importantData in the console. However, in more complex programs, we can implement logic to use the data more effectively (such as manipulating a Wix element with the data using the $w selector).
  • If we fail to receive the proper json data response, the .catch() method is executed which is the case for printing out the error.

Putting It Together

Using the getJSON() function described above, we can dynamically retrieve updated information every time the stock prices website reloads.

import { getJSON } from 'wix-fetch';
$w.onReady(function () {
getJSON("https://finnhub.io/api/v1/quote?symbol=AAPL&token=<personal api key>")
.then(json => {
$w("#currentPrice").text = `Current Price: $${pricesJson.c.toFixed(2)}`;
$w("#lowestPrice").text = `Lowest Price: $${pricesJson.l.toFixed(2)}`;
$w("#highestPrice").text = `Highest Price: $${pricesJson.h.toFixed(2)}`;
})
.catch(err => console.log(err))
});

Apple Stock Prices Today As can be seen above, we used the wix-fetch module to automate the process of fetching the current Apple stock price information. Essentially, we implemented the getJSON() function to get updated stock price information from another site and update our website without us needing to manually input the values.

Note: In our code example, we used the endpoint: "https://finnhub.io/api/v1/quote?symbol=AAPL&token=<personal api key>" which contains some information about a "<personal api key>". Oftentimes external APIs require some special token or API key. These keys can usually be created through the API’s site by signing up for an account. In this case, we signed up through the Finnhub API to get information about stock prices. Since API keys should be kept private, we opted to leave "<personal api key>" as a placeholder rather than providing the actual key. If the code snippet was copied and pasted exactly as is, the code wouldn’t work because of this placeholder.

Wrapping Up

Congratulations! Like so many other Wix features that reduce the complexity of programming concepts, the wix-fetch module allows us to easily retrieve data from other sources and take our websites to the next level while cutting down on development time.

In this article, we covered:

  • Why getting information from other sites is so important.
  • An overview of the wix-fetch module and its fetch() and getJSON() functions.
  • What JSON is and how it’s used.
  • How to make a GET request using the getJSON() function.
  • Handling the response of the getJSON() function by chaining the .then() and .catch() methods.

The wix-fetch module gives us the freedom to request data from many third-party sources. Imagine the possibilities! Below are some potential applications of the wix-fetch module:

  • Finnhub provides real-time information on stocks. In this article, we used Finnhub’s API “Quote” feature to get updated Apple stock prices.
  • Open Weather Map allows us to get real-time weather data.
  • NASA supplies data from various research/missions they are conducting.

Go ahead and apply the techniques that you learned in this article towards building even more powerful Wix sites - the sky’s the limit!