Last active
December 22, 2023 11:15
-
-
Save PabloAballe/8bd270f3f873f78a99646d6548fde71c to your computer and use it in GitHub Desktop.
Fetch API Connection Snippet: Demonstrates how to use Fetch to connect to external APIs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Fetch API Connection Snippet | |
| * Brief Description: Demonstrates how to use Fetch to connect to external APIs. | |
| * | |
| * Author: Pablo Aballe | |
| * Date: 2023-12-22 | |
| */ | |
| /** | |
| * Connects to an external API using Fetch. | |
| * @param {string} url - The URL of the API endpoint. | |
| * @returns {Promise} - A promise that resolves with the response data. | |
| */ | |
| function fetchApiData(url) { | |
| return fetch(url) | |
| .then(response => { | |
| if (!response.ok) { | |
| throw new Error('Network response was not ok'); | |
| } | |
| return response.json(); | |
| }) | |
| .catch(error => console.error('Fetch error:', error)); | |
| } | |
| // Usage Example | |
| const apiUrl = "https://api.example.com/data"; | |
| fetchApiData(apiUrl) | |
| .then(data => console.log(data)) | |
| .catch(error => console.log(error)); | |
| // Additional Notes: | |
| // Remember to handle errors and check for a successful response. | |
| // This function returns a promise, so it should be used with .then() or async/await. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment