MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Fetching Data from APIs0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
8.1Fetching Data from APIs8.2Handling JSON Responses8.3GET vs POST Requests8.4Mini Project: Random Joke Generator
HomeTutorialsJavaScript for IntermediateFetching Data from APIs
Handling JSON Responses

Fetching Data from APIs

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

Modern web applications communicate with backend servers and cloud microservices through RESTful APIs and GraphQL endpoints. The modern standard for performing HTTP network requests in browsers and modern Node.js runtimes is the Fetch API.


1. Anatomy of the Fetch API

The fetch() global function initiates an HTTP request and returns a Promise that resolves to a Response object representing the response to the request.

1async function loadUserData(userId) {
2 const url = `https://jsonplaceholder.typicode.com/users/${userId}`;
3
4 const response = await fetch(url);
5 console.log('Response Status:', response.status); // e.g. 200, 404, 500
6 console.log('Status Text:', response.statusText); // e.g. "OK", "Not Found"
7 console.log('Headers:', response.headers.get('content-type'));
8}

2. The Critical "Gotcha": fetch() Only Rejects on Network Failures!

Unlike legacy libraries like Axios, fetch() will NOT reject its Promise on HTTP error status codes (like 404 Not Found or 500 Internal Server Error)!

A fetch Promise only rejects if there is a fatal network error (DNS lookup failed, device offline, CORS failure).

1HTTP 404 / 500 Response:
2 fetch() Promise ──► FULFILLED! (response.ok === false)
3 
4No Internet / DNS Failure:
5 fetch() Promise ──► REJECTED! (TypeError: Failed to fetch)

The Standard Production Pattern: Check response.ok

response.ok is a built-in boolean that evaluates to true if the HTTP status code is in the range 200-299:

1async function fetchSecureResource(endpoint) {
2 try {
3 const response = await fetch(endpoint);
4 
5 // MUST CHECK response.ok!
6 if (!response.ok) {
7 throw new Error(`HTTP Error ${response.status}: ${response.statusText}`);
8 }
9 
10 const data = await response.json();
11 return data;
12 } catch (error) {
13 console.error('Fetch operation failed:', error.message);
14 throw error; // Re-throw or handle gracefully
15 }
16}

3. Configuring Request Options

The second argument to fetch() is an options configuration object:

1const response = await fetch('/api/v1/articles', {
2 method: 'GET', // Default is GET
3 headers: {
4 'Accept': 'application/json',
5 'Authorization': 'Bearer YOUR_JWT_TOKEN'
6 },
7 cache: 'no-cache', // Bypass browser cache
8 mode: 'cors' // Enable Cross-Origin Resource Sharing
9});

4. Setting Request Timeouts with AbortSignal.timeout()

Avoid indefinite hanging on slow mobile networks by providing a timeout signal:

1async function fetchWithTimeout(url, ms = 5000) {
2 try {
3 // Abort automatically if server doesn't respond within 5000ms
4 const response = await fetch(url, {
5 signal: AbortSignal.timeout(ms)
6 });
7 
8 if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
9 return await response.json();
10 } catch (err) {
11 if (err.name === 'TimeoutError') {
12 console.error(`Request timed out after ${ms}ms!`);
13 } else {
14 console.error('Network error:', err);
15 }
16 }
17}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
When does the Promise returned by fetch() reject?
Question 2
What property on the Response object should you check to verify if an HTTP request succeeded with a 2xx status code?
Question 3
What is the default HTTP method used by fetch() when no options object is provided?
Question 4
Which modern Web API method provides a clean way to automatically cancel a fetch request after a specified timeout?
Question 5
If a server returns an HTTP 500 status code, what does response.ok evaluate to?
Next Lesson

Handling JSON Responses

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Intro to Async/AwaitHandling JSON Responses

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext