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

Source: https://support.wix.com/en/article/velo-accessing-3rd-party-services-with-the-fetch-api (updated 2024-12-30)
Related: Wix developer documentation, https://dev.wix.com/docs/llms.txt; Help Center index, https://support.wix.com/en/llms.txt

Visit the [Velo by Wix website](https://www.wix.com/velo) 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](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) issues that can occur when sending some requests from the front end.

> **Note:** Because all Wix sites use [HTTPS](https://support.wix.com/en/article/about-ssl-and-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](https://developer.mozilla.org/en-US/docs/Learn/Common%5Fquestions/What%5Fare%5Fbrowser%5Fdeveloper%5Ftools).

**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:

[Embedded content](https://velo-examples.wixsite.com/hello-fetch-m/getjson)

First we need to write a `getGreetings()` function in a [backend web module](https://support.wix.com/en/article/velo-web-modules-calling-backend-code-from-the-frontend) 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.)

```javascript
import { getJSON } from 'wix-fetch';

// GET call using getJSON
export async function getGreetings() {
  const response = await getJSON('https://velo-examples.wixsite.com/training-tester/_functions/greetings');
  return response;
}
```

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.

```javascript
import { getGreetings } from 'backend/dataFetcher';

// See the dataFetcher.jsw web module 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 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](https://www.wix.com/velo/example/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:

[Embedded content](https://velo-examples.wixsite.com/hello-fetch-m)

First we need to write a `getRandomGreeting()` function in a [backend web module](https://support.wix.com/en/article/velo-web-modules-calling-backend-code-from-the-frontend) 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.)

```javascript
import { fetch } from 'wix-fetch';

// GET call using fetch
export async function getRandomGreeting() {
  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 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.

```javascript
import { getRandomGreeting } from 'backend/dataFetcher';

// See the dataFetcher.jsw web module 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 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](https://www.wix.com/velo/example/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:

[Embedded content](https://velo-examples.wixsite.com/hello-fetch-m/post-fetch)

First we need to write a `postGreeting()` function in a [backend web module](https://support.wix.com/en/article/velo-web-modules-calling-backend-code-from-the-frontend) 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.)

```javascript
import { fetch } from 'wix-fetch';

// POST call using fetch
export async function postGreeting(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 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.

```javascript
import { postGreeting} from 'backend/dataFetcher';

// See the dataFetcher.jsw web module 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 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](https://www.wix.com/velo/example/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](https://support.wix.com/en/article/velo-about-the-secrets-manager).
2. Writing code that will extract the API key using the [Secrets API](https://www.wix.com/velo/reference/wix-secrets-backend) and making the service call in a [backend web module](https://support.wix.com/en/article/velo-web-modules-calling-backend-code-from-the-frontend). 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 backend web module to call the weather service and retrieve the data:

```javascript
//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 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.
