1. Home
  2. Coding Hub
  3. Coding Notes
  4. Js
  5. Fetch Api
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
13Hrs
25Mins
44Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Js
  5. Fetch Api

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
13Hrs
25Mins
44Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionScript LoadingOutput MechanicsCode CommentsSyntax RulesStrict Mode
Execution Contextvar Keywordlet Keywordconst KeywordHoistingTemporal Dead ZonePrimitive TypesReference Typestypeof OperatorType CoercionStack & Heap
Arithmetic OperatorsAssignment OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsMath ObjectModern Math (ES6+)Date Object
if / elseTernary Operatorswitch Statementfor Loopwhile Loopdo...while Loopbreak & continuefor...in Loopfor...of Loop
Template LiteralsString PropertiesString ExtractionString ModificationString SearchRegex Basics
Array BasicsArray MethodsArray MutatorsArray SearchingArray SortingArray IterationArray map()Array filter()Array reduce()Spread & RestDestructuring
Declarations vs ExpressionsArrow FunctionsParameters & ArgumentsReturn StatementsScope ChainClosuresIIFEsCallbacksthis KeywordCall, Apply, Bind
Object BasicsObject IterationObject DestructuringDeep vs Shallow CopiesMapsSetsWeakMap & WeakSetJSON Methods
try / catchthrow StatementThe Error ObjectCustom Errorsfinally Block
What is the DOM?Selecting ElementsChanging HTML & TextChanging Styles & ClassesEvent ListenersEvent BubblingCreating Elements
Sync vs AsyncsetTimeoutPromisesAsync / AwaitFetch APICORS Basics
JavaScript

Fetch API

Overview

The fetch() API is the modern, native browser method for making network requests (HTTP requests) to a server.

It completely replaces the older, clunky XMLHttpRequest (AJAX). fetch natively returns a Promise, making it extremely easy to use with async/await.

One crucial quirk: fetch only throws a network Error if the user loses internet connection. It does NOT throw an error for bad HTTP statuses (like 404 or 500). You must check response.ok manually.

Syntax

Standard GET Request
javascript
async function loadTodos() {
  const res = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  
  // You MUST check if the HTTP status was successful (200-299)
  if (!res.ok) {
    throw new Error(`HTTP error! status: ${res.status}`);
  }
  
  const data = await res.json();
  console.log(data);
}
POST Request with Data
javascript
async function createTodo() {
  const res = await fetch('https://api.example.com/todos', {
    method: 'POST', // Override the default GET
    headers: {
      'Content-Type': 'application/json' // Tell server we are sending JSON
    },
    body: JSON.stringify({ title: "Buy Milk", completed: false })
  });
  
  return await res.json();
}

Common Pitfalls

  • Forgetting to call .json(). The initial fetch response is a raw HTTP Response object (containing headers and metadata), NOT your JSON data. You must call await res.json() to parse the data stream into a JS object.

Interview Questions

If a fetch request returns a 404 Not Found status, does the Promise reject and trigger the catch block?

No! fetch only rejects a promise if there is a fundamental network failure (like the wifi turning off). For all HTTP error statuses (404, 500, 401), the promise resolves normally. You must manually check if response.ok is true.

Real-World Example

Submitting a user login form to the backend authentication server.

example
javascript
const response = await fetch('/api/login', {
  method: 'POST',
  body: JSON.stringify({ email, password })
});

Check Your Knowledge

Test your understanding of Fetch API with these quick questions.

Question 1

Which object does the `fetch()` method return?

Take JavaScript Quiz
Outline
IntroductionScript LoadingOutput MechanicsCode CommentsSyntax RulesStrict Mode
Execution Contextvar Keywordlet Keywordconst KeywordHoistingTemporal Dead ZonePrimitive TypesReference Typestypeof OperatorType CoercionStack & Heap
Arithmetic OperatorsAssignment OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsMath ObjectModern Math (ES6+)Date Object
if / elseTernary Operatorswitch Statementfor Loopwhile Loopdo...while Loopbreak & continuefor...in Loopfor...of Loop
Template LiteralsString PropertiesString ExtractionString ModificationString SearchRegex Basics
Array BasicsArray MethodsArray MutatorsArray SearchingArray SortingArray IterationArray map()Array filter()Array reduce()Spread & RestDestructuring
Declarations vs ExpressionsArrow FunctionsParameters & ArgumentsReturn StatementsScope ChainClosuresIIFEsCallbacksthis KeywordCall, Apply, Bind
Object BasicsObject IterationObject DestructuringDeep vs Shallow CopiesMapsSetsWeakMap & WeakSetJSON Methods
try / catchthrow StatementThe Error ObjectCustom Errorsfinally Block
What is the DOM?Selecting ElementsChanging HTML & TextChanging Styles & ClassesEvent ListenersEvent BubblingCreating Elements
Sync vs AsyncsetTimeoutPromisesAsync / AwaitFetch APICORS Basics
JavaScript

Fetch API

Overview

The fetch() API is the modern, native browser method for making network requests (HTTP requests) to a server.

It completely replaces the older, clunky XMLHttpRequest (AJAX). fetch natively returns a Promise, making it extremely easy to use with async/await.

One crucial quirk: fetch only throws a network Error if the user loses internet connection. It does NOT throw an error for bad HTTP statuses (like 404 or 500). You must check response.ok manually.

Syntax

Standard GET Request
javascript
async function loadTodos() {
  const res = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  
  // You MUST check if the HTTP status was successful (200-299)
  if (!res.ok) {
    throw new Error(`HTTP error! status: ${res.status}`);
  }
  
  const data = await res.json();
  console.log(data);
}
POST Request with Data
javascript
async function createTodo() {
  const res = await fetch('https://api.example.com/todos', {
    method: 'POST', // Override the default GET
    headers: {
      'Content-Type': 'application/json' // Tell server we are sending JSON
    },
    body: JSON.stringify({ title: "Buy Milk", completed: false })
  });
  
  return await res.json();
}

Common Pitfalls

  • Forgetting to call .json(). The initial fetch response is a raw HTTP Response object (containing headers and metadata), NOT your JSON data. You must call await res.json() to parse the data stream into a JS object.

Interview Questions

If a fetch request returns a 404 Not Found status, does the Promise reject and trigger the catch block?

No! fetch only rejects a promise if there is a fundamental network failure (like the wifi turning off). For all HTTP error statuses (404, 500, 401), the promise resolves normally. You must manually check if response.ok is true.

Real-World Example

Submitting a user login form to the backend authentication server.

example
javascript
const response = await fetch('/api/login', {
  method: 'POST',
  body: JSON.stringify({ email, password })
});

Check Your Knowledge

Test your understanding of Fetch API with these quick questions.

Question 1

Which object does the `fetch()` method return?

Take JavaScript Quiz

JavaScript coding notes for Indian students — 87 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in JavaScript

  1. Introduction
  2. Script Loading
  3. Output Mechanics
  4. Code Comments
  5. Syntax Rules
  6. Strict Mode
  7. Execution Context
  8. var Keyword
  9. let Keyword
  10. const Keyword
  11. Hoisting
  12. Temporal Dead Zone
  13. Primitive Types
  14. Reference Types
  15. typeof Operator
  16. Type Coercion
  17. Stack & Heap
  18. Arithmetic Operators
  19. Assignment Operators
  20. Comparison Operators
  21. Logical Operators
  22. Bitwise Operators
  23. Math Object
  24. Modern Math (ES6+)
  25. Date Object
  26. if / else
  27. Ternary Operator
  28. switch Statement
  29. for Loop
  30. while Loop
  31. do...while Loop
  32. break & continue
  33. for...in Loop
  34. for...of Loop
  35. Template Literals
  36. String Properties
  37. String Extraction
  38. String Modification
  39. String Search
  40. Regex Basics
  41. Array Basics
  42. Array Methods
  43. Array Mutators
  44. Array Searching
  45. Array Sorting
  46. Array Iteration
  47. Array map()
  48. Array filter()
  49. Array reduce()
  50. Spread & Rest
  51. Destructuring
  52. Declarations vs Expressions
  53. Arrow Functions
  54. Parameters & Arguments
  55. Return Statements
  56. Scope Chain
  57. Closures
  58. IIFEs
  59. Callbacks
  60. this Keyword
  61. Call, Apply, Bind
  62. Object Basics
  63. Object Iteration
  64. Object Destructuring
  65. Deep vs Shallow Copies
  66. Maps
  67. Sets
  68. WeakMap & WeakSet
  69. JSON Methods
  70. try / catch
  71. throw Statement
  72. The Error Object
  73. Custom Errors
  74. finally Block
  75. What is the DOM?
  76. Selecting Elements
  77. Changing HTML & Text
  78. Changing Styles & Classes
  79. Event Listeners
  80. Event Bubbling
  81. Creating Elements
  82. Sync vs Async
  83. setTimeout
  84. Promises
  85. Async / Await
  86. Fetch API
  87. CORS Basics

Study next

  • All coding notes
  • JavaScript notes home
  • JavaScript certification quiz
  • Online compiler
  • Interview Q&A

JavaScript coding notes for Indian students — 87 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in JavaScript

  1. Introduction
  2. Script Loading
  3. Output Mechanics
  4. Code Comments
  5. Syntax Rules
  6. Strict Mode
  7. Execution Context
  8. var Keyword
  9. let Keyword
  10. const Keyword
  11. Hoisting
  12. Temporal Dead Zone
  13. Primitive Types
  14. Reference Types
  15. typeof Operator
  16. Type Coercion
  17. Stack & Heap
  18. Arithmetic Operators
  19. Assignment Operators
  20. Comparison Operators
  21. Logical Operators
  22. Bitwise Operators
  23. Math Object
  24. Modern Math (ES6+)
  25. Date Object
  26. if / else
  27. Ternary Operator
  28. switch Statement
  29. for Loop
  30. while Loop
  31. do...while Loop
  32. break & continue
  33. for...in Loop
  34. for...of Loop
  35. Template Literals
  36. String Properties
  37. String Extraction
  38. String Modification
  39. String Search
  40. Regex Basics
  41. Array Basics
  42. Array Methods
  43. Array Mutators
  44. Array Searching
  45. Array Sorting
  46. Array Iteration
  47. Array map()
  48. Array filter()
  49. Array reduce()
  50. Spread & Rest
  51. Destructuring
  52. Declarations vs Expressions
  53. Arrow Functions
  54. Parameters & Arguments
  55. Return Statements
  56. Scope Chain
  57. Closures
  58. IIFEs
  59. Callbacks
  60. this Keyword
  61. Call, Apply, Bind
  62. Object Basics
  63. Object Iteration
  64. Object Destructuring
  65. Deep vs Shallow Copies
  66. Maps
  67. Sets
  68. WeakMap & WeakSet
  69. JSON Methods
  70. try / catch
  71. throw Statement
  72. The Error Object
  73. Custom Errors
  74. finally Block
  75. What is the DOM?
  76. Selecting Elements
  77. Changing HTML & Text
  78. Changing Styles & Classes
  79. Event Listeners
  80. Event Bubbling
  81. Creating Elements
  82. Sync vs Async
  83. setTimeout
  84. Promises
  85. Async / Await
  86. Fetch API
  87. CORS Basics

Study next

  • All coding notes
  • JavaScript notes home
  • JavaScript certification quiz
  • Online compiler
  • Interview Q&A