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
1
import {Permissions, webMethod} from "wix-web-module";
2
import { getJSON } from 'wix-fetch';
3
4
// GET call using getJSON
5
export const getGreetings = webMethod(Permissions.Anyone, async () => {
6
const response = await getJSON('https://velo-examples.wixsite.com/training-tester/_functions/greetings');
7
return response;
8
});

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
1
import { getGreetings } from 'backend/dataFetcher.web';
2
3
// See the dataFetcher.web.js web method in the backend for the service call //
4
5
$w.onReady(function () {
6
$w('#fetchAllButton').onClick(async () => {
7
$w('#fetchAllButton').disable();
8
9
const fetchedData = await getGreetings();
10
const repeaterData = fetchedData.map(item => {
11
item._id = item.id.toString();
12
return item;
13
});
14
15
$w('#helloRepeater').data = repeaterData;
16
$w('#helloRepeater').show();
17
18
$w('#fetchAllButton').enable();
19
});
20
21
$w('#helloRepeater').onItemReady( ($item, itemData) => {
22
$item('#repeatedLanguageText').text = itemData.language;
23
$item('#repeatedHelloText').text = itemData.greeting;
24
});
25
});

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
1
import {Permissions, webMethod} from "wix-web-module";
2
import { fetch } from 'wix-fetch';
3
4
// GET call using fetch
5
export const getRandomGreeting = webMethod(Permissions.Anyone, async () => {
6
const response = await fetch('https://velo-examples.wixsite.com/training-tester/_functions/randomgreeting');
7
if(response.ok) {
8
const json = await response.json();
9
return json.greeting;
10
} else {
11
return Promise.reject("Fetch did not succeed");
12
}
13
});

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
1
import { getRandomGreeting } from 'backend/dataFetcher.web';
2
3
// See the dataFetcher.web.js web method in the backend for the service call //
4
5
$w.onReady(function () {
6
$w('#fetchRandomButton').onClick(async () => {
7
$w('#fetchRandomButton').disable();
8
9
const fetchedData = await getRandomGreeting();
10
11
$w('#languageText').text = fetchedData.language;
12
$w('#helloText').text = fetchedData.message;
13
14
$w('#languageText').show();
15
$w('#helloText').show();
16
17
$w('#fetchRandomButton').enable();
18
});
19
});

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
1
import {Permissions, webMethod} from "wix-web-module";
2
import { fetch } from 'wix-fetch';
3
4
// POST call using fetch
5
export const postGreeting = webMethod(Permissions.Anyone, async (language, greeting) => {
6
const jsonBody = {
7
language,
8
greeting
9
};
10
11
const fetchOptions = {
12
method: 'post',
13
headers: 'application/json',
14
body: JSON.stringify(jsonBody)
15
};
16
17
const response = await fetch('https://velo-examples.wixsite.com/training-tester/_functions/greeting', fetchOptions);
18
return response.json();
19
});

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
1
import { postGreeting} from 'backend/dataFetcher.web';
2
3
// See the dataFetcher.web.js web method in the backend for the service call //
4
5
$w.onReady(function () {
6
$w('#postButton').onClick(async () => {
7
$w('#postButton').disable();
8
9
const putResponse = await postGreeting($w('#languageInput').value, $w('#greetingInput').value);
10
11
console.log(putResponse);
12
13
if(putResponse.success) {
14
$w('#successIcon').show();
15
$w('#errorIcon').hide();
16
$w('#responseMessage').text = putResponse.success;
17
}
18
else {
19
$w('#successIcon').hide();
20
$w('#errorIcon').show();
21
$w('#responseMessage').text = putResponse.error;
22
}
23
24
$w('#responseMessage').show();
25
$w('#postButton').enable();
26
});
27
});

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
1
// serviceModule.web.js
2
3
import {Permissions, webMethod} from "wix-web-module";
4
import {fetch} from 'wix-fetch';
5
import {getSecret} from 'wix-secrets-backend';
6
7
export const getCurrentTemp = webMethod(Permissions.Anyone, async (city) => {
8
const url = 'https://api.openweathermap.org/data/2.5/weather?q=';
9
const key = await getSecret(WeatherApiKey);
10
11
let fullUrl = url + city + '&APPID=' + key + '&units=imperial';
12
13
return fetch(fullUrl, {method: 'get'})
14
.then(response => response.json())
15
.then(json => json.main.temp);
16
});

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