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:
- Download Node.js to run JavaScript on your computer
- Use your browser's Developer Console (Press F12) to test code snippets
- Create a .html file with <script> tags and open it in your browser
📡 Real-World Analogy: The Fetch API is like ordering from a drive-thru :
- • You send a request (speak into the microphone)
- • You wait for a response (they prepare your order)
- • You receive data (they hand you the bag)
- • Sometimes things go wrong (they're out of fries) — you need error handling !
🌐 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
- TikTok for loading videos
- YouTube for comments, videos, and metadata
- Roblox for catalog items
- Fortnite and GTA V stat tracking
- Shopify for product details
- Amazon for recommendations
- Spotify for playlists
- Instagram for posts, stories, reels
- Trading platforms for live stock data
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:
- ✔ dashboards
- ✔ analytics tools
- ✔ admin panels
- ✔ full-stack apps
- ✔ weather apps
- ✔ stock trackers
- ✔ game utilities
- ✔ e-learning platforms
- ✔ AI interfaces
🚀 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
- status codes
- authentication
- JSON parsing
- network errors
- body handling
- abort controllers
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
- DNS failures
- network disconnect
- 404 Not Found
- 500 Internal Server Error
- 403 Forbidden
🧨 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)
- profile pictures
🌍 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)
- Fortnite API
- GTA V stat API
🔄 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:
- auto-complete
- dashboard filtering
📊 Fetching Large Lists with Pagination
📡 Parallel Fetching With Promise.all()
🔥 Real Example: Loading a Dashboard
- admin panels
- personal accounts
🌐 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
- 204 No Content
🔐 Authentication Errors
- 401 Unauthorized
🔴 Client Errors
- 429 Too Many Requests → API rate-limiting (very common)
🔥 Server Errors
- 502 Bad Gateway
- 503 Service Unavailable
- 504 Gateway Timeout
Mastering status codes = mastering error handling.
🎯 Fetch with Retry Logic
Real APIs sometimes fail. So you need retry strategies.
- Google Cloud
🧠 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
- ❌ Never expose API keys: Anyone can inspect this.
- ❌ Never use private APIs from frontend - Everything must go through your backend.
- ✔️ Always sanitize user input - Attackers can inject script tags.
- ✔️ Always validate server responses - Servers can get hacked or misconfigured.
🎯 Practice Challenge
- 1️⃣ Fetch data from a public API and display it
- 2️⃣ Create a POST request to send data to an API
- 3️⃣ Add error handling for failed requests
- 4️⃣ Implement retry logic for failed requests
- 5️⃣ Use Promise.all() to fetch multiple resources in parallel
- 6️⃣ Add authentication headers to a request
- 7️⃣ Handle different HTTP status codes appropriately
🏁 Recap
- ✅ Basics of the Fetch API
- ✅ Understanding Response objects
- ✅ GET, POST, PUT, PATCH, DELETE requests
- ✅ Error handling and status codes
- ✅ CORS and how it works
- ✅ Authentication with headers
- ✅ Pagination and parallel fetching
- ✅ AbortController for canceling requests
- ✅ Retry logic for failed requests
- ✅ Security best practices
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
- Previous: Async/Await
- Next: Error Handling