Velo: Accessing 3rd-Party Services with the Fetch API
- Making a GET Request Using getJSON( )
- Making a GET Request Using fetch( )
- Making a POST Request Using fetch( )
- Working With API Keys
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.
Making a GET Request Using getJSON( )
First we need to write a getGreetings()
function in a backend web module to make our service call. (For reference, we called the web module dataFetcher.jsw
. Later we will need to import getGreetings()
from it in our frontend code.)
1import { getJSON } from 'wix-fetch';
2
3// GET call using getJSON
4export async function getGreetings() {
5 const response = await getJSON('https://velo-examples.wixsite.com/training-tester/_functions/greetings');
6 return response;
7}
We start by importing the Fetch API's getJSON()
function, then in our getGreetings()
function we simply call getJSON()
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.
1import { getGreetings } from 'backend/dataFetcher';
2
3// See the dataFetcher.jsw web module 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 backend web module dataFetcher.jsw
.
When the "Fetch Greetings" button is clicked, we call getGreetings()
and await the response. When it arrives, we convert the received 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 backend web module to make our service call. (For reference, we called the web module dataFetcher.jsw
. Later we will need to import getRandomGreeting()
from it in our frontend code.)
1import { fetch } from 'wix-fetch';
2
3// GET call using fetch
4export async function getRandomGreeting() {
5 const response = await fetch('https://velo-examples.wixsite.com/training-tester/_functions/randomgreeting');
6 if(response.ok) {
7 const json = await response.json();
8 return json.greeting;
9 } else {
10 return Promise.reject("Fetch did not succeed");
11 }
12}
We start by importing the Fetch API's fetch()
function which we call in our getRandomGreeting()
code. 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.
1import { getRandomGreeting } from 'backend/dataFetcher';
2
3// See the dataFetcher.jsw web module 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 backend web module dataFetcher.jsw
.
When the "Fetch Random Greeting" button is clicked, we call getRandomGreeting()
and await the response. When it arrives, we use our text fields to display 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 backend web module to make our service call. (For reference, we called the web module dataFetcher.jsw
. Later we will need to import postGreeting()
from it in our frontend code.)
1import { fetch } from 'wix-fetch';
2
3// POST call using fetch
4export async function postGreeting(language, greeting) {
5 const jsonBody = {
6 language,
7 greeting
8 };
9
10 const fetchOptions = {
11 method: 'post',
12 headers: 'application/json',
13 body: JSON.stringify(jsonBody)
14 };
15
16 const response = await fetch('https://velo-examples.wixsite.com/training-tester/_functions/greeting', fetchOptions);
17 return response.json();
18}
We start by importing the Fetch API's fetch()
which we call in our postGreeting()
function.
Our 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.
1import { postGreeting} from 'backend/dataFetcher';
2
3// See the dataFetcher.jsw web module 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 backend web module dataFetcher.jsw
.
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
- Storing the API key in the Secrets Manager.
- Writing code that will extract the API key using the Secrets API and making 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.
First, you create a function in a backend web module to call the weather service and retrieve the data:
1//serviceModule.jsw
2
3import {fetch} from 'wix-fetch';
4import {getSecret} from 'wix-secrets-backend';
5
6export async function getCurrentTemp(city) {
7 const url = 'https://api.openweathermap.org/data/2.5/weather?q=';
8 const key = await getSecret(WeatherApiKey);
9
10 let fullUrl = url + city + '&APPID=' + key + '&units=imperial';
11
12 return fetch(fullUrl, {method: 'get'})
13 .then(response => response.json())
14 .then(json => json.main.temp);
15}
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.