What You'll Learn
- Three ways to call an API from a browser
- How to use
fetch()in JavaScript - How to inspect API calls using the browser's Network tab
- The limitations of browser-based API calls (CORS)
Why This Matters
The browser is the most accessible API client you have. You can test simple GET endpoints without installing anything. Once you know how to inspect and call APIs from the browser, you can debug any front-end issue and learn any API by experimenting.
Method 1 — The Address Bar (Simplest GET)
For GET requests that need no authentication, you can paste the URL directly into the browser address bar:
https://api.open-meteo.com/v1/forecast?latitude=19.07&longitude=72.87¤t=temperature_2m
The browser sends a GET request and displays the response body. This works only for:
- GET requests (you cannot send POST from the address bar)
- Public APIs (no authentication)
- APIs that allow cross-origin browser access (CORS — covered below)
Method 2 — JavaScript fetch()
For real web apps, you call APIs from JavaScript. The modern way is fetch():
Open the browser console
Right-click anywhere on a webpage → Inspect → Console. Paste this code:
// Simplest GET request
const response = await fetch("https://api.open-meteo.com/v1/forecast?latitude=19.07&longitude=72.87¤t=temperature_2m");
const data = await response.json();
console.log(data);
console.log("Temperature:", data.current.temperature_2m);
The browser will print the response object and the temperature value.
Step by step
fetch(url)sends a GET request and returns a Promise that resolves to a Response object.await response.json()reads the response body and parses it as JSON.- The result is a normal JavaScript object you can access.
Handling errors
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (err) {
console.error("Request failed:", err.message);
}
fetch does not throw on 4xx or 5xx responses — it only throws on network failures. Always check response.ok (true for 2xx, false otherwise).
Sending headers
const response = await fetch(url, {
headers: {
"Accept": "application/json",
"Authorization": "Bearer YOUR_TOKEN"
}
});
POST request with body
const response = await fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({name: "Anita", email: "anita@example.com"})
});
Method 3 — The Network Tab
The browser's DevTools Network tab lets you see every API call any website makes. Useful for learning how real APIs are called.
- Open any website (e.g., twitter.com).
- Right-click → Inspect → Network tab.
- Filter by "Fetch/XHR".
- Reload the page or interact with the site.
- Click any request to see its headers, response, and timing.
This is how developers reverse-engineer undocumented APIs and debug their own front-end code.
The CORS Limitation
Browsers block cross-origin requests by default for security. If your frontend at https://app.example.com calls https://api.different.com, the browser blocks it unless the API explicitly allows your origin.
How CORS works
- Browser sends the request with an
Originheader. - Server responds with
Access-Control-Allow-Origin: *orAccess-Control-Allow-Origin: https://app.example.com. - If the origin is not allowed, the browser blocks the response.
What this means in practice
- Public APIs (Open-Meteo, JSONPlaceholder) usually allow all origins. They work from the browser.
- Authenticated APIs often restrict origins. They do not work from a browser unless your origin is whitelisted.
- For testing restricted APIs, use cURL or Postman instead — they do not enforce CORS.
Common Mistakes
- Forgetting
await.fetchreturns a Promise. Withoutawait, you get a Promise object, not the data. - Forgetting
response.json(). The response is a stream; you must parse it. - Not checking
response.ok. 4xx and 5xx do not throw. You silently get bad data. - Building JSON by hand. Use
JSON.stringify(obj)for the body. Never concatenate strings. - Hard-coding API keys in frontend code. Anyone viewing the page source can steal them. Use a backend proxy for authenticated APIs.
- Forgetting
Content-Typeon POST. The server does not know your body is JSON without it.
Practical Exercise (10 minutes)
- Open the browser console on any page.
- Use
fetch()to callhttps://api.open-meteo.com/v1/forecast?latitude=19.07&longitude=72.87¤t=temperature_2m. - Print the temperature value.
- Open the Network tab. Find your request. Inspect the request headers, response headers, and response body.
- Try calling
https://api.github.com/repos/facebook/reactfrom the console. Print the stars count.
Mini Challenge
Write a JavaScript function getWeather(lat, lon) that calls the Open-Meteo API and returns just the temperature. Call it with Mumbai (19.07, 72.87), Delhi (28.61, 77.21), and Bengaluru (12.97, 77.59). Print all three temperatures.
Key Takeaways
- Three ways to call an API from a browser: address bar (GET only),
fetch()in JS, and the Network tab to inspect. fetch(url)returns a Promise. Useawait, then callresponse.json()to parse the body.- Always check
response.ok— 4xx and 5xx do not throw. - CORS blocks cross-origin browser requests unless the server allows your origin.
- Never hard-code API keys in frontend JavaScript. Use a backend proxy for authenticated APIs.
Previously: Module 3 (lessons 16–21) covered REST principles.
Today: You learned to call APIs from a browser — the most accessible API client.
Next: Lesson 23 introduces cURL, the most powerful command-line API client.
FAQ
What is the difference between fetch and XMLHttpRequest?
XMLHttpRequest (XHR) is the older API for HTTP requests in browsers. fetch is the modern replacement — cleaner syntax, Promise-based, easier error handling. Use fetch for new code; you'll only see XHR in older codebases.
Should I use Axios instead of fetch?
Axios is a popular library that wraps fetch with a nicer API and automatic JSON parsing. It's a good choice for large projects. For learning and simple cases, fetch is enough — and it's built into every browser and Node.js 18+.
Comments
Comments
Post a Comment