Fetch API
Reviewed & published by Brayan K
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
- Make GET, POST, PUT and DELETE requests
- Parse JSON responses correctly
- Handle errors and bad HTTP status codes
- Send data with request headers and body
- Understand CORS and how to deal with it
- Implement retry logic and AbortController
๐ก 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)
const req = new XMLHttpRequest();
req.open("GET", "/api");
req.onload = function() {
console.log(req.responseText);
};
req.send();Modern (Fetch)
const res = await fetch("/api");
const data = await res.json();Cleaner. Faster. Easier. More powerful.
๐ฌ Basic GET Request โ The Foundation
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);But behind those 2 lines is a HUGE world:
- 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
response.ok // true/false if status is 200โ299
response.status // e.g., 200, 404, 500
response.statusText // human readable text
response.headers // all server headers
response.url // final resolved URL
response.redirected // boolean
response.type // basic, cors, error, opaque
response.body // ReadableStreamresponse.json() // parse JSON
response.text() // raw text
response.blob() // files, images
response.arrayBuffer() // binary
response.formData()Fetch is far more than just .json().
๐งช Full Syntax of fetch()
fetch(url, {
method: "GET",
headers: { ... },
body: "...",
mode: "cors",
cache: "no-cache",
credentials: "include",
redirect: "follow",
referrerPolicy: "no-referrer"
});We will break down each one deeply in this lesson.
๐ก Real Example โ Fetching JSONPlaceholder API
This free API is used in thousands of tutorials.
const res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const post = await res.json();
console.log(post);{
"userId": 1,
"id": 1,
"title": "...",
"body": "..."
}๐ฅ Using Async/Await With Fetch (The Best Way)
Async/await + fetch = modern JavaScript.
๐ Error Handling: Fetch Does NOT Throw on 400/500 Errors
This surprises most developers.
Fetch only throws on:
- DNS failures
- network disconnect
But it DOES NOT throw on:
- 404 Not Found
- 500 Internal Server Error
- 403 Forbidden
๐งจ Handling Failed JSON Parsing
Server may return invalid JSON:
try {
const data = await res.json();
} catch (err) {
console.error("Bad JSON:", err);
}This happens more often than beginners expect.
๐ฅ POST Requests โ Sending Data
Fetch makes POST simple:
const res = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Brayan", age: 16 })
});๐ Common Fetch Methods
| GET | Retrieve data |
| POST | Create new data |
| PUT/PATCH | Update existing data |
| DELETE | Remove data |
๐ฆ Sending FormData (No Need to JSON.stringify)
const form = new FormData();
form.append("file", fileInput.files[0]);
fetch("/upload", {
method: "POST",
body: form
});- profile pictures
This is how Instagram/TikTok upload images.
๐ 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."
Access-Control-Allow-Origin: *CORS Modes in fetch:
mode: "cors" // default for most APIs
mode: "no-cors" // restricted, only opaque responses
mode: "same-origin" // only internal requests๐ Authorization Headers (Tokens, API Keys, JWT)
- Fortnite API
- GTA V stat API
fetch("/private", {
headers: {
"Authorization": "Bearer SECRET_TOKEN"
}
});๐ PUT, PATCH, DELETE Requests
PUT (Overwrite)
fetch("/api/user/1", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Boopie" })
});PATCH (Partial Update)
fetch("/api/user/1", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ age: 17 })
});DELETE
fetch("/api/user/1", {
method: "DELETE"
});โก AbortController โ Cancel Fetch Requests
Imagine the user types fast into a search bar. You must cancel old requests:
const controller = new AbortController();
fetch("/search?q=hello", {
signal: controller.signal
});
// Cancel
controller.abort();- auto-complete
- dashboard filtering
๐ Fetching Large Lists with Pagination
/posts?limit=10&page=2Used in every real platform:
๐ก Parallel Fetching With Promise.all()
const [user, posts, comments] = await Promise.all([
fetch("/user/1").then(r => r.json()),
fetch("/posts").then(r => r.json()),
fetch("/comments").then(r => r.json())
]);This is how dashboards load instantly.
๐ฅ Real Example: Loading a Dashboard
async function loadDashboard() {
const [
stats,
notifications,
recent
] = await Promise.all([
fetch("/dashboard/stats").then(r => r.json()),
fetch("/dashboard/notifications").then(r => r.json()),
fetch("/dashboard/recent").then(r => r.json())
]);
return { stats, notifications, recent };
}- admin panels
- personal accounts
๐ GET Request with Query Parameters
const url = new URL("https://api.example.com/search");
url.searchParams.set("q", "javascript");
url.searchParams.set("limit", 20);
const res = await fetch(url);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.
async function retryFetch(url, attempts = 3) {
for (let i = 0; i < attempts; i++) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error();
return res.json();
} catch (err) {
if (i === attempts - 1) throw err;
await new Promise(r => setTimeout(r, 500));
}
}
}- 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.
fetch(`https://api.example.com?key=SECRET`)- โ 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 Complete โ Fetch API!
You can now connect your JavaScript code to the outside world โ fetching data, sending forms, and building real dynamic applications.
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.race([...])
- Promise.all([...])
Answer: Promise.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 โ Catch and handle errors with try/catch and graceful fallbacks
- Quick reference: JavaScript cheat sheet
- From the blog: Async/Await in JavaScript Explained ยท How to Learn to Code Fast (Without Burning Out)