Fetch Api

A deep dive into making HTTP requests, API architecture, JSON handling, security, CORS, streaming, authentication, pagination, rate limits, real-world examples, and more.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

What You'll Learn in This Lesson

💡 Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:

📡 Real-World Analogy: The Fetch API is like ordering from a drive-thru :

🌐 Fetch API — The Backbone of Modern Web Applications

The Fetch API is the heart of modern JavaScript development. Every interactive, data-driven website uses fetch() behind the scenes:

HTTP Method

Purpose

Real Example

GET

Retrieve data

Loading user profile

POST

Send new data

Creating a new post

PUT/PATCH

Update data

Editing your bio

DELETE

Remove data

Deleting a comment

Fetch is the engine connecting the browser (your JavaScript) to servers, databases, APIs, clouds, and backend systems around the world.

If you understand fetch deeply, you can build:

🚀 What Exactly Is the Fetch API?

The Fetch API is a modern browser interface for making HTTP requests: GET, POST, PUT, DELETE, PATCH — everything.

Before fetch(), developers used XMLHttpRequest (XHR). Fetch replaces ALL of it with a cleaner, Promise-based approach.

Old (XHR)

Modern (Fetch)

📬 Basic GET Request — The Foundation

We will cover ALL of this in this mega lesson.

🧠 Understanding the Fetch Response Object

🧪 Full Syntax of fetch()

We will break down each one deeply in this lesson.

📡 Real Example — Fetching JSONPlaceholder API

This free API is used in thousands of tutorials.

🔥 Using Async/Await With Fetch (The Best Way)

🛑 Error Handling: Fetch Does NOT Throw on 400/500 Errors

🧨 Handling Failed JSON Parsing

This happens more often than beginners expect.

📥 POST Requests — Sending Data

📝 Common Fetch Methods

Create new data

Update existing data

📦 Sending FormData (No Need to JSON.stringify)

🌍 CORS — The Gatekeeper of APIs

CORS = Cross-Origin Resource Sharing One of the MOST misunderstood web concepts.

Browser blocks request → API says: "You're not allowed."

CORS Modes in fetch:

🔐 Authorization Headers (Tokens, API Keys, JWT)

🔄 PUT, PATCH, DELETE Requests

PUT (Overwrite)

PATCH (Partial Update)

DELETE

⚡ AbortController — Cancel Fetch Requests

Imagine the user types fast into a search bar. You must cancel old requests:

📊 Fetching Large Lists with Pagination

📡 Parallel Fetching With Promise.all()

🔥 Real Example: Loading a Dashboard

🌐 GET Request with Query Parameters

Easier and cleaner than string concatenation.

🌐 Understanding HTTP Status Codes

Fetch won't throw errors automatically, so YOU must check status codes manually.

🟢 Success Codes

🔐 Authentication Errors

🔴 Client Errors

🔥 Server Errors

Mastering status codes = mastering error handling.

🎯 Fetch with Retry Logic

Real APIs sometimes fail. So you need retry strategies.

🧠 Real-World Example: Authenticate User & Get Profile

This is how dashboards like Facebook, YouTube Studio, Amazon Seller Central, and TikTok Business load your data securely.

🛡️ Security Best Practices

🎯 Practice Challenge

🏁 Recap

The Fetch API is the foundation of modern web communication. Once you master it, you can build any data-driven application with confidence.

📋 Quick Reference — Fetch API

Action

Code Snippet

Basic GET

const res = await fetch(url);

Get JSON

const data = await res.json();

Check Success

if (!res.ok) throw new Error();

POST JSON

fetch(url, { method: 'POST', body: ... } )

Headers

headers: { 'Content-Type': 'application/json' }

Lesson 9 Complete — Fetch API!

You can now connect your JavaScript code to the outside world — fetching data, sending forms, and building real dynamic applications.

Up next: Error Handling — making your applications crash-proof and professional! 🛡️

Practice quiz

Which HTTP method does the lesson use to retrieve data?

  • POST
  • DELETE
  • GET
  • PUT

Answer: GET. GET retrieves data, like loading a user profile; POST sends new data.

How do you parse a JSON response from fetch?

  • response.json()
  • response.parse()
  • JSON.fetch(response)
  • response.toJSON()

Answer: response.json(). await response.json() reads the body and parses it as JSON.

Does fetch reject (throw) on a 404 or 500 HTTP status?

  • Yes, it throws on any error status
  • Only on 500, not 404
  • Only when using async/await
  • No — you must check response.ok or response.status yourself

Answer: No — you must check response.ok or response.status yourself. Fetch only rejects on network failures; for 4xx/5xx you must check response.ok manually.

What does response.ok tell you?

  • The body is valid JSON
  • The status is in the 200-299 range
  • The request used HTTPS
  • The server supports CORS

Answer: The status is in the 200-299 range. response.ok is true when the status code is 200-299.

When sending JSON in a POST, which header should you set?

  • Content-Type: application/json
  • Accept: text/html
  • Authorization: Bearer
  • X-Requested-With

Answer: Content-Type: application/json. Set Content-Type to application/json and send JSON.stringify(data) as the body.

What does CORS stand for?

  • Client Origin Request Security
  • Cached Object Response System
  • Cross-Origin Resource Sharing
  • Cross-Object Reference Standard

Answer: Cross-Origin Resource Sharing. CORS = Cross-Origin Resource Sharing; the server grants access via Access-Control-Allow-Origin.

What is AbortController used for with fetch?

  • Parsing JSON faster
  • Cancelling in-flight requests via a signal
  • Retrying failed requests
  • Adding auth headers

Answer: Cancelling in-flight requests via a signal. You pass controller.signal to fetch and call controller.abort() to cancel, e.g. for live search.

How do you run several fetches in parallel and wait for all of them?

  • A for loop with await each
  • fetch.all(...)

Promise.all waits for all the requests, which overlap so total time is roughly the slowest one.

Which status code commonly signals API rate-limiting?

  • 204 No Content
  • 429 Too Many Requests
  • 301 Moved Permanently
  • 418 I'm a teapot

Answer: 429 Too Many Requests. 429 Too Many Requests indicates you have hit a rate limit.

Which is a security best practice the lesson stresses?

  • Put secret API keys in the frontend URL
  • Disable CORS entirely
  • Never expose API keys in frontend code
  • Always use no-cors mode

Answer: Never expose API keys in frontend code. Never expose secret keys client-side; route private API calls through your own backend.

Continue this course