Example Description
In this example, we demonstrate how to use the Fetch API to work with 3rd party APIs. We show usage of the GET HTTP method using both the `fetch()` function and the shortcut `getJSON` function. We also show how to perform a POST request using the `fetch()` function.
How We Built It
Page Elements
Each of the 3 site pages contains elements used to call backend functions and display the results. The backend functions each make HTTP requests using the Fetch API. There is no need to look at the UI code in this example to understand the fetch operations, so we will not analyze it here.
Code
The backend 'dataFetcher.jsw' file contains the code that makes the fetch calls to the 3rd party APIs. It contains the following 3 functions:
`getRandomGreeting()`: This function uses `fetch()` to call a 3rd party API. Notice that there are two promises that we need to deal with here. The first is returned by the `fetch()` function and the second is returned by the `json()` function that's used to retrieve the JSON body of the response.
`getGreetings()` This function uses `getJSON()` to call a 3rd party API. Notice that there is only one promise that we need to deal with here. We can use this shortcut function when we know the 3rd party API returns a JSON response and we don't need to use any of the fetch options.
`postGreeting()`: This function uses `fetch()` to make a POST request to a 3rd party API. We start by building an object that will be used as the request body. Then we create an options object to define the request method, headers, and body. Finally, we make the call to the `fetch()` function using the options and return the JSON response.
Related Examples
Did this help?
|
Thanks for your feedback!
Add to Cart Gallery
Let customers to add products to their cart
INTERMEDIATE
Hide and Show Elements
Hide and show elements in response to user interactions
BEGGINER
Hide and Show Elements
Hide and show elements in response to user interactions
BEGGINER