Corvid: get res api Fetch API

Corvid: Accessing Third-Party Services with the Fetch API

Visit the Corvid by Wix website to onboard and continue learning.
Using Corvid you can write code to access third-party web services. You can call a third-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.
 

Client-Side Service Call

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

For this example, we've created a simple form with the following elements:
TypeIDUsage
InputtextInputSymbolFor entering the currency to look up
ButtonbuttonFetchRateFor submitting the request
TexttextRateA label for displaying the result

When you have the form set up, you can set the button's properties so that its onClick handler will call the following function:

1
2
3
4
5
6
7
8
9
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 two parts. First, you write code that will 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. Then, you write client-side code to trigger the backend service call, returning data if necessary.
For example, suppose you want to call a third-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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//serviceModule.jsw

import {fetch} from 'wix-fetch';  

export function getCurrentTemp(city) {
  const url = 'https://api.openweathermap.org/data/2.5/weather?q=';
  const key = '<api key placeholder>';
    
  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 fetch from wix-fetch, which is used to make https requests. 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 replace <api key placeholder> with your own API key. 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:  
TypeIDUsage
Text InputtextInputCityFor entering the name of the city
ButtonbuttonFetchTempFor submitting the request
TexttextTempA label for displaying the result

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.

1
2
3
4
5
6
7
8
9
10
//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.

Did this help?
SHARE

Oscar perez

Arquitecto especialista en gestion de proyectos si necesitas desarrollar algun proyecto en Bogota contactame en el 3006825874 o visita mi pagina en www.arquitectobogota.tk

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comentarios:

Publicar un comentario