1️⃣1️⃣ Working With APIs

1️⃣ What is an API?

API = Application Programming Interface

👉 It allows two applications to communicate with each other.

Example:

  • Your app → requests weather data
  • Weather API → sends response (temperature, city, etc.)

👉 Like a waiter:

  • You (client) → request food
  • Waiter (API) → takes request
  • Kitchen (server) → prepares response

2️⃣ Fetch API

fetch() is used to get data from APIs

Basic Syntax:

fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));

Modern (Async/Await):

async function getData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}getData();

3️⃣ JSON (JavaScript Object Notation)

👉 Most APIs return data in JSON format

Example JSON:

{
"name": "Aditya",
"age": 25,
"city": "Delhi"
}

Convert JSON:

let obj = JSON.parse(jsonString);   // JSON → JS Object
let json = JSON.stringify(obj); // JS Object → JSON

4️⃣ Handling API Response

When you call an API, response has:

let response = await fetch(url);console.log(response.status);   // 200, 404, etc.
console.log(response.ok); // true/false

Proper Handling:

if (response.ok) {
let data = await response.json();
console.log(data);
} else {
console.log("Error:", response.status);
}

5️⃣ Error Handling

👉 Always handle errors (network issues, wrong API, etc.)

Example:

async function fetchData() {
try {
let response = await fetch("https://api.example.com/data"); if (!response.ok) {
throw new Error("API Error");
} let data = await response.json();
console.log(data); } catch (error) {
console.log("Something went wrong:", error.message);
}
}

🚀 Practice Project 1: Weather App

Features:

  • Input city name
  • Show temperature, weather condition

API:

👉 https://openweathermap.org/api

Example Code:

async function getWeather() {
let city = document.getElementById("city").value; let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KEY&units=metric`; try {
let res = await fetch(url);
let data = await res.json(); document.getElementById("result").innerHTML =
`🌡 Temp: ${data.main.temp}°C <br>
🌥 Weather: ${data.weather[0].description}`; } catch (err) {
console.log(err);
}
}

🎬 Practice Project 2: Movie Search App

Features:

  • Search movie by name
  • Show poster, title, year

API:

👉 http://www.omdbapi.com/

Example Code:

async function searchMovie() {
let movie = document.getElementById("movie").value; let url = `https://www.omdbapi.com/?apikey=YOUR_API_KEY&s=${movie}`; try {
let res = await fetch(url);
let data = await res.json(); let output = ""; data.Search.forEach(m => {
output += `
<div>
<h3>${m.Title}</h3>
<img src="${m.Poster}" width="100">
<p>${m.Year}</p>
</div>
`;
}); document.getElementById("result").innerHTML = output; } catch (err) {
console.log(err);
}
}

💡 Teaching Tip

Start students in this order:

  1. JSON basics
  2. fetch()
  3. API testing (Postman / browser)
  4. Small project (Weather)
  5. Bigger project (Movie search)

Add advanced features (loading, debounce, pagination)