Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
API Basics APIs APIs From Zero to Real-World API Testing & Automation JavaScript Module 4 — Real API Requests

How to Call an API from the Browser (GET Requests)

Reviewed & accurate
AI Summary

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&current=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&current=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

  1. fetch(url) sends a GET request and returns a Promise that resolves to a Response object.
  2. await response.json() reads the response body and parses it as JSON.
  3. 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.

  1. Open any website (e.g., twitter.com).
  2. Right-click → Inspect → Network tab.
  3. Filter by "Fetch/XHR".
  4. Reload the page or interact with the site.
  5. 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

  1. Browser sends the request with an Origin header.
  2. Server responds with Access-Control-Allow-Origin: * or Access-Control-Allow-Origin: https://app.example.com.
  3. 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.
CORS is a browser security feature, not a server feature. cURL, Postman, and server-side code (Node.js, Python) ignore CORS entirely. It only affects browser-based requests.

Common Mistakes

  1. Forgetting await. fetch returns a Promise. Without await, you get a Promise object, not the data.
  2. Forgetting response.json(). The response is a stream; you must parse it.
  3. Not checking response.ok. 4xx and 5xx do not throw. You silently get bad data.
  4. Building JSON by hand. Use JSON.stringify(obj) for the body. Never concatenate strings.
  5. Hard-coding API keys in frontend code. Anyone viewing the page source can steal them. Use a backend proxy for authenticated APIs.
  6. Forgetting Content-Type on POST. The server does not know your body is JSON without it.

Practical Exercise (10 minutes)

  1. Open the browser console on any page.
  2. Use fetch() to call https://api.open-meteo.com/v1/forecast?latitude=19.07&longitude=72.87&current=temperature_2m.
  3. Print the temperature value.
  4. Open the Network tab. Find your request. Inspect the request headers, response headers, and response body.
  5. Try calling https://api.github.com/repos/facebook/react from 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. Use await, then call response.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.
Course continuity
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+.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments