DEV Community

Sathish Kumar
Sathish Kumar

Posted on

How to call an API in JavaScript:

If you are learning JavaScript, calling an API is one of the most exciting things you will learn. It allows your website to talk to other servers and get data (like weather, user profiles, or products).

​Here is the easiest way to do it using fetch() and async/await:

Example:

async function getUserData() {
try {
// 1. Fetch data from the API URL
const response = await fetch('https://api.github.com/users/octocat');

// 2. Convert the response into JSON format
const data = await response.json();

// 3. Print the data in the console
console.log(data);
Enter fullscreen mode Exit fullscreen mode

} catch (error) {
// Handle any errors here
console.error('Error fetching data:', error);
}
}

getUserData();

Top comments (0)