Velo: Accessing 3rd-Party Services with the Fetch API

Visit the Velo by Wix website to onboard and continue learning.

Using Velo you can write code to access 3rd-party web services. The Fetch API contains two functions for sending HTTP requests: getJSON() and fetch(). For simple GET requests for retrieving a JSON object we recommend using getJSON(). For more complex requests, fetch() provides greater functionality.

Although you can use the Fetch API in frontend (client-side) or backend (server-side) code, it's usually best to send requests to external APIs from your backend code. This is more secure, especially if the API requires a key or other authentication, and it avoids CORS issues that can occur when sending some requests from the front end.

Note: Because all Wix sites use HTTPS, you can't request HTTP content from a service in your site's code. Invalid requests cause an error that you can see using your browser's developer tools.

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.

Making a GET Request Using getJSON( )

Suppose we want to call a 3rd-party service to GET a set of greetings in random languages at the click of a button, as demonstrated in the example below:

First we need to write a getGreetings() function in a web method to make our service call. (For reference, we called the web method dataFetcher.web.js. Later we will need to import getGreetings() from it in our frontend code.)

Copy Code
import {Permissions, webMethod} from "wix-web-module";
import { getJSON } from 'wix-fetch';
// GET call using getJSON
export const getGreetings = webMethod(Permissions.Anyone, async () => {
const response = await getJSON('https://velo-examples.wixsite.com/training-tester/_functions/greetings');
return response;
});

We start by importing the webMethod function and the Permissions enum from the wix-web-module module, as well as the Fetch API's getJSON() function. Then in our getGreetings() function we call the webMethod function with Permissions.Anyone, and the getJSON() function, and return the response.

Now we can write frontend code to respond to our "Fetch Greetings" button click by calling our getGreetings() backend function and displaying the results.

Copy Code
import { getGreetings } from 'backend/dataFetcher.web';
// See the dataFetcher.web.js web method in the backend for the service call //
$w.onReady(function () {
$w('#fetchAllButton').onClick(async () => {
$w('#fetchAllButton').disable();
const fetchedData = await getGreetings();
const repeaterData = fetchedData.map(item => {
item._id = item.id.toString();
return item;
});
$w('#helloRepeater').data = repeaterData;
$w('#helloRepeater').show();
$w('#fetchAllButton').enable();
});
$w('#helloRepeater').onItemReady( ($item, itemData) => {
$item('#repeatedLanguageText').text = itemData.language;
$item('#repeatedHelloText').text = itemData.greeting;
});
});

We start by importing our getGreetings() function from our web method dataFetcher.web.js.

When the "Fetch Greetings" button is clicked, we call getGreetings() and await the response. When it arrives, we convert the recieved ids to strings and use them to populate a repeater.

For more information on the above example and to experiment with it yourself, see our Hello Fetch example page.

Making a GET Request Using fetch( )

Now lets consider a similar example using fetch().

Suppose we want to call a 3rd-party service to GET a greeting in a random language at the click of a button, as demonstrated in the example below:

First we need to write a getRandomGreeting() function in a web method to make our service call. (For reference, we called the web method dataFetcher.web.js. Later we will need to import getRandomGreeting() from it in our frontend code.)

Copy Code
import {Permissions, webMethod} from "wix-web-module";
import { fetch } from 'wix-fetch';
// GET call using fetch
export const getRandomGreeting = webMethod(Permissions.Anyone, async () => {
const response = await fetch('https://velo-examples.wixsite.com/training-tester/_functions/randomgreeting');
if(response.ok) {
const json = await response.json();
return json.greeting;
} else {
return Promise.reject("Fetch did not succeed");
}
});

We start by importing the webMethod function and the Permissions enum from the wix-web-module module, as well as the Fetch API's fetch() function. Then in our getRandomGreeting() function we call the webMethod function with Permissions.Anyone, and the fetch() function, and return the response. If the call succeeded, we convert the response into a JSON file, and then return its greeting object. If it failed we return a Promise.reject message.

Now we can write frontend code to respond to our "Fetch Random Greeting" button click by calling our getRandomGreeting() backend function and displaying the results.

Copy Code
import { getRandomGreeting } from 'backend/dataFetcher.web';
// See the dataFetcher.web.js web method in the backend for the service call //
$w.onReady(function () {
$w('#fetchRandomButton').onClick(async () => {
$w('#fetchRandomButton').disable();
const fetchedData = await getRandomGreeting();
$w('#languageText').text = fetchedData.language;
$w('#helloText').text = fetchedData.message;
$w('#languageText').show();
$w('#helloText').show();
$w('#fetchRandomButton').enable();
});
});

We start by importing our getRandomGreeting() function from our web method dataFetcher.web.js.

When the "Fetch Random Greeting" button is clicked, we call getRandomGreeting() and await the response. When it arrives, we use our text fields to dsiplay the data.

For more information on the above example and to experiment with it yourself, see our Hello Fetch example page.

Making a POST Request Using fetch( )

fetch() can also be used to make other types of requests to 3rd-party services, such as POST.

Suppose we want to call a 3rd-party service to POST a greeting in a specified language at the click of a button, as demonstrated in the example below:

First we need to write a postGreeting() function in a web method to make our service call. (For reference, we called the web method dataFetcher.web.js. Later we will need to import postGreeting() from it in our frontend code.)

Copy Code
import {Permissions, webMethod} from "wix-web-module";
import { fetch } from 'wix-fetch';
// POST call using fetch
export const postGreeting = webMethod(Permissions.Anyone, async (language, greeting) => {
const jsonBody = {
language,
greeting
};
const fetchOptions = {
method: 'post',
headers: 'application/json',
body: JSON.stringify(jsonBody)
};
const response = await fetch('https://velo-examples.wixsite.com/training-tester/_functions/greeting', fetchOptions);
return response.json();
});

We start by importing the webMethod function and the Permissions enum from the wix-web-module module, as well as the Fetch API's fetch() function. Then in our postGreeting() function we call the webMethod function with Permissions.Anyone. Our postGreeting() function accepts language and greeting parameters, which will be passed from the frontend, and POSTs them to the 3rd-party service.

This time we need to pass additional options parameters to fetch() which we called fetchOptions. These options contain the requested method (post), a header describing the format of the data being sent (application/json) and a jsonBody object containing the language and greeting values.

Now we can write frontend code to respond to our "Post Greeting" button click by calling our postGreeting() backend function.

Copy Code
import { postGreeting} from 'backend/dataFetcher.web';
// See the dataFetcher.web.js web method in the backend for the service call //
$w.onReady(function () {
$w('#postButton').onClick(async () => {
$w('#postButton').disable();
const putResponse = await postGreeting($w('#languageInput').value, $w('#greetingInput').value);
console.log(putResponse);
if(putResponse.success) {
$w('#successIcon').show();
$w('#errorIcon').hide();
$w('#responseMessage').text = putResponse.success;
}
else {
$w('#successIcon').hide();
$w('#errorIcon').show();
$w('#responseMessage').text = putResponse.error;
}
$w('#responseMessage').show();
$w('#postButton').enable();
});
});

We start by importing our postGreeting() function from our web method dataFetcher.web.js.

When the "Post Greeting" button is clicked, we call postGreeting() with language and greeting vales from our corresponding input elements and await the response. When it arrives, we use a text field to show whether the call succeeded or failed.

For more information on the above example and to experiment with it yourself, see our Hello Fetch example page.

Working With API Keys

Often you will need an API key to access 3rd-party web services.

When working with API keys we recommend:

  1. Storing the API key in the Secrets Manager.
  2. Writing code that will extract the API key using the Secrets API and making the service call in a web method. 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. 

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 web method to call the weather service and retrieve the data:

Copy Code
// serviceModule.web.js
import {Permissions, webMethod} from "wix-web-module";
import {fetch} from 'wix-fetch';
import {getSecret} from 'wix-secrets-backend';
export const getCurrentTemp = webMethod(Permissions.Anyone, async (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 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.

Was this helpful?
Yes
No