An API, or Application Programming Interface, is like a bridge that allows two different software systems to talk to each other. It defines a set of rules and protocols that enable programs to request and exchange information in a structured way.
Think of an API as a waiter in a restaurant. You (the customer) don’t go into the kitchen to prepare your food; instead, you place an order with the waiter. The waiter takes your request to the kitchen, which prepares the dish, and then the waiter brings it back to you. In this analogy:
You don’t need to know how the kitchen prepares the food; you just trust the waiter to bring the correct dish.
APIs allow your app to interact with other software or services, often over the internet. They let you:
APIs handle the details of how the data is formatted and transferred, so developers can focus on building the app’s features.
Most websites and applications rely on data and services provided by others. For example:
Without APIs, integrating these external services would be difficult and time-consuming.
APIs are the invisible helpers that connect different software systems. They simplify communication, allow data sharing, and enable developers to create powerful apps that leverage existing services — making the web more connected and interactive than ever before.
fetch
to Make HTTP RequestsThe fetch
API is a modern, built-in way to make HTTP requests in JavaScript. It allows your web app to communicate with servers and retrieve or send data over the internet. Let's explore how to use fetch
to perform a basic GET request, handle responses, and manage errors.
fetch
A GET request is used to retrieve data from a server. Here’s how you make a simple GET request using fetch
:
fetch('https://api.agify.io?name=michael')
.then(response => response.json()) // Parse JSON from the response
.then(data => {
console.log(data); // Log the fetched data
})
.catch(error => {
console.error('Error fetching data:', error);
});
fetch()
: The fetch
function takes the URL of the resource you want to access and returns a Promise.Response
object..json()
on the Response
object, which also returns a Promise that resolves to the JavaScript object..then()
, you work with the parsed data..catch()
block handles any network errors or issues with fetching the data.Try this example in your browser’s console or a JavaScript environment that supports fetch
:
fetch('https://api.agify.io?name=sarah')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log(`Predicted age for Sarah: ${data.age}`);
})
.catch(error => {
console.error('Failed to fetch:', error);
});
fetch
API does not reject the Promise on HTTP errors like 404 or 500; you need to check response.ok
to handle such cases manually..json()
method parses the response body as JSON asynchronously..catch()
to handle network failures or other unexpected errors.fetch(url)
to initiate a network request; it returns a Promise.response.ok
to confirm the HTTP status is successful..json()
to convert it into usable JavaScript objects..catch()
to ensure your app stays robust.Next, we'll look at how to read and work with JSON responses in more detail.
When working with APIs, the most common data format you’ll encounter is JSON (JavaScript Object Notation). JSON is a lightweight, human-readable format for exchanging data between servers and clients.
JSON looks like JavaScript objects but is actually a string format that represents data as key-value pairs, arrays, and nested structures. For example:
{
"name": "Alice",
"age": 28,
"hobbies": ["reading", "traveling", "coding"]
}
This JSON represents a person’s profile with a name, age, and a list of hobbies.
.json()
When you use the fetch
API, the response body is received as a stream of bytes. To convert it into a usable JavaScript object, you call the .json()
method on the response. This method parses the JSON string and returns a Promise that resolves with the resulting object.
fetch('https://api.agify.io?name=emma')
.then(response => response.json()) // Parse JSON data
.then(data => {
console.log(data); // Output the whole object
console.log(`Name: ${data.name}`); // Access individual properties
console.log(`Predicted Age: ${data.age}`);
})
.catch(error => {
console.error('Error:', error);
});
Sample output:
{ name: "emma", age: 29, count: 12345 }
Name: emma
Predicted Age: 29
Sometimes, APIs return arrays of objects. Here’s an example of working with such data:
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => {
users.forEach(user => {
console.log(`User: ${user.name}, Email: ${user.email}`);
});
})
.catch(error => {
console.error('Failed to load users:', error);
});
This fetches an array of users and logs each user’s name and email.
.json()
method on a fetch response to parse JSON into JavaScript objects or arrays.In the next section, we’ll put all this together by building a simple weather app that fetches real data from a public API!
In this section, we'll build a simple weather app that fetches live weather data from a public API, parses the JSON response, and dynamically updates the webpage with the information. We’ll also add error handling to ensure the app works smoothly.
We’ll use the OpenWeatherMap API, which provides free weather data. You need to sign up for a free API key.
For this example, let's assume you have an API key stored in a variable:
const apiKey = 'YOUR_API_KEY_HERE';
Create a simple HTML structure with an input box to enter a city name, a button to fetch weather, and an area to display results:
<input type="text" id="cityInput" placeholder="Enter city name" />
<button id="getWeatherBtn">Get Weather</button>
<div id="weatherResult"></div>
Write a function to fetch weather data from the API using the city name:
const apiKey = 'YOUR_API_KEY_HERE'; // Replace with your actual API key
async function fetchWeather(city) {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&appid=${apiKey}&units=metric`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('City not found');
}
const data = await response.json();
return data;
} catch (error) {
throw error; // Propagate error to caller
}
}
units=metric
to get temperature in Celsius.Next, create a function to display weather information or errors on the page:
function displayWeather(data) {
const weatherDiv = document.getElementById('weatherResult');
weatherDiv.innerHTML = `
<h2>Weather in ${data.name}</h2>
<p>Temperature: ${data.main.temp} °C</p>
<p>Conditions: ${data.weather[0].description}</p>
<p>Humidity: ${data.main.humidity}%</p>
`;
}
function displayError(message) {
const weatherDiv = document.getElementById('weatherResult');
weatherDiv.innerHTML = `<p style="color: red;">Error: ${message}</p>`;
}
Add an event listener to the button to get the city input, fetch the weather, and update the page:
document.getElementById('getWeatherBtn').addEventListener('click', async () => {
const city = document.getElementById('cityInput').value.trim();
if (!city) {
displayError('Please enter a city name');
return;
}
displayError(''); // Clear previous errors
document.getElementById('weatherResult').textContent = 'Loading...';
try {
const weatherData = await fetchWeather(city);
displayWeather(weatherData);
} catch (error) {
displayError(error.message);
}
});
You’ve now created a working weather app that demonstrates:
fetch
and async
/await
.This simple project is a great example of how JavaScript interacts with APIs to build real-world applications!