paint-brush
The API fetch Module as the Way to Accessing 3rd-Party Services by@velo
395 reads
395 reads

The API fetch Module as the Way to Accessing 3rd-Party Services

by Velo by WixJuly 3rd, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Wix Velo is a full-stack development platform that empowers you to rapidly build, manage and deploy professional web apps. You can call a 3rd-party service directly from your client-side code. If you have security concerns, such as exposing API keys, you can call the service from a backend web module. In the following examples we use the wix-fetch module to call a service, but the Node.js http, http, and net modules are also available.
featured image - The API fetch Module as the Way to Accessing 3rd-Party Services
Velo by Wix HackerNoon profile picture

Using Velo you can write code to access 3rd-party web services. You can call a 3rd-party service directly from your client-side code. However, if you
have security concerns, such as exposing API keys, you can call the service from a backend web module.

Note: You cannot request HTTP content from a service if your site is an HTTPS site. Invalid requests will cause an error that you can see using your browser's developer tools. To fix the request, you can either use the HTTPS protocol to fetch the requested resources from you HTTPS site or you can turn off SSL on your site to fetch an HTTP resource.

Advanced: Modules available for calling services

In the following examples we use the wix-fetch module to call a service, but the Node.js http, https, and net modules are also available.

Client-Side Service Call

For example, suppose you want to call a 3rd-party service to look up a currency exchange rate.

For this example, we've created a simple form with the following elements:

When you have the form set up, you can set the button's properties so that its

onClick
handler will call the following function:

export function buttonFetchRate_click(event) {
  let url = "https://api.exchangeratesapi.io/latest?base=USD";
  let symbol = $w("#textInputSymbol").value; 
  let fullUrl = url + "&symbols=" + symbol; 
 
  fetch(fullUrl, {method: 'get'})
    .then(response => response.json())
    .then(json => $w("#textRate").text = json.rates[symbol].toString());
}

In this example, you start by constructing the full URL for the fetch request. The URL is made up of the service's address and some query parameters. For simplicity, we'll always convert U.S. dollars, so the base parameter's value is hardcoded to USD. The value for the symbols parameter is pulled from the form. Then the function makes the actual request. When it receives a response, it pulls out the conversion rate for the symbol we passed and sets it as the label's text.

Note: Certain CORS (Cross-Origin Resource Sharing) requests are restricted when originating from a browser. Usually, GET requests and certain POST requests can be made from your site's Public, Page, or Site code. All other requests need to be made from your site's Backend code. Invalid requests will cause an error that you can see using your browser's developer tools. If you are experiencing an issue with a fetch call due to a CORS restriction, move the call to the backend as described below.

Backend Service Call

Making a service call from the backend is done in 3 parts:

  1. Store the API key in the Secrets Manager.
  2. Write code that will extract the API key using the Secrets API and make the service call in a backend web module. This avoids the security concerns, such as exposing API keys, that would arise if you tried to call the service from your client-side code.
  3. Write client-side code to trigger the backend service call, returning data if necessary.

For example, suppose you want to call a 3rd-party weather service to find the current weather in a city the user has chosen.

First, you create a function in a backend web module to call the weather service and retrieve the data:

//serviceModule.jsw

import {fetch} from 'wix-fetch'; 
import (getSecret} from 'wix-secrets-backend';

export async function getCurrentTemp(city) {
  const url = 'https://api.openweathermap.org/data/2.5/weather?q=';
  const key = await getSecret(WeatherApiKey);
    
  let fullUrl = url + city + '&APPID=' + key + '&units=imperial'; 
  
  return fetch(fullUrl, {method: 'get'})
    .then(response => response.json())
    .then(json => json.main.temp);
}

In this example, you start by importing the functions needed to to make https requests and to get secrets from the Secrets Manager. Then you create a new function that takes in a city whose weather you want to look up. The function begins by constructing the full URL for the fetch request. The URL is made up of the service's address and an API key. To make this example work, you'd have to store your API in the Secrets Manager with the name "WeatherApiKey". Then the function makes the actual request. When it receives a response, it pulls out the temperature data. That temperature data will be received by the client-side call.

On the client side, you need to decide where to call the backend function and what to do with the data it returns.

For this example, we've created a simple form that has the following elements:

When you have the form set up, you can set the button's properties so that its

onClick
handler calls the function you wrote in the backend module.

//Form's page code

import {getCurrentTemp} from 'backend/serviceModule';

//...

export function buttonFetchTemp_click(event) {
 getCurrentTemp($w("#textInputCity").value)
  .then(temp => $w("#textTemp").text = temp + "°");
}

You start here by importing the function that you wrote in the backend. Then, in the button's event handler, call the

getCurrentTemp
function. The Input element's value gets passed as the
city
argument. When the function has finished running, set the text label to display the temperature that was returned.

Previously published at https://support.wix.com/en/article/velo-accessing-3rd-party-services-with-the-fetch-api