Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Asynchronous JavaScript
Next article icon

Fetch API in JavaScript

Last Updated : 14 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Fetch API is a modern interface in JavaScript that allows you to make HTTP requests. It replaces the older XMLHttpRequest method and provides a cleaner and more flexible way to fetch resources asynchronously. The Fetch API uses Promises, making it easier to work with asynchronous data.

Syntax

fetch(url, options)     .then(response => response.json())     .then(data => console.log(data))     .catch(error => console.error('Error:', error));
  • url: The API endpoint from which data is fetched.
  • options (optional): Specifies method, headers, body, etc.
  • response.json(): Parses the response as JSON.
  • .catch(error): Handles any errors that occur during the request.

How Fetch API Works?

  • A request is sent to the specified URL.
  • The server processes the request and sends a response.
  • The response is converted to JSON (or another format) using .json().
  • Errors are handled using .catch() or try-catch blocks.

Common HTTP Request Methods in Fetch API

  • GET: This request helps to retrieve some data from another server.
  • POST: This request is used to add some data onto the server.
  • PUT: This request is used to update some data on the server.
  • DELETE: This request is used to delete some data on the server.

Basic Fetch Request

A simple GET request to fetch data from an API.

JavaScript
fetch('https://fakestoreapi.com/products/1')     .then(response => response.json())     .then(data => console.log(data))     .catch(error => console.error('Error:', error)); 

Output

Screenshot-2025-01-23-124520

Making a Basic GET Request

  • fetch() sends an HTTP request to the specified URL.
  • .json() parses the response body as JSON.
  • .then() handles the resolved promise with the fetched data, and .catch() catches any errors (e.g., network issues).

Handling Response Status Codes

When making an HTTP request, handling response status codes is crucial for determining whether the request was successful or if there was an error. The status code provides information about the result of the request.

JavaScript
fetch('https://api.example.com/data')     .then(response => {         if (response.ok) {             return response.json();          } else {             throw new Error('Network response was not ok');          }     })     .then(data => console.log(data))     .catch(error => console.error('There was a problem with the fetch operation:', error)); 

Output

Screenshot-2025-02-13-110223

Handling Response Status Codes

  • fetch(): Initiates a network request to the provided URL.
  • response.ok: Checks if the HTTP response status is in the range of 200–299, indicating success.
  • return response.json(): If the response is successful, the data is parsed as JSON for further use.
  • throw new Error(): If the status code indicates an error (e.g., 404 or 500), an error is thrown to handle it.
  • catch(error): Catches any errors (network or HTTP issues) and logs them to the console for debugging.

Using async/await with Fetch API

Using async/await makes handling asynchronous code like fetch cleaner and more readable. It allows you to write code that appears synchronous while still being non-blocking.

JavaScript
async function getP() {     try {         const response = await fetch('https://fakestoreapi.com/products');         if (response.ok) {             const data = await response.json();              console.log(data);         } else {             throw new Error('Failed to fetch data');         }     } catch (error) {         console.error('Error:', error);      } } getP() 

Output

Screenshot-2025-02-13-111336

Using async/await with Fetch API

  • async function getP(): This defines an asynchronous function, meaning it can handle tasks like fetching data without blocking the rest of the program.
  • await fetch(): The await keyword pauses the function until the fetch() request is complete, so the data can be used right after it’s retrieved.
  • response.ok: Checks if the fetch request was successful by ensuring the response status is in the 200-299 range.
  • await response.json(): If the response is successful, it converts the data from the server (usually in JSON format) into a JavaScript object.
  • try/catch block: Catches any errors that may happen (like network problems) and logs them, preventing the program from crashing.

Sending Custom Headers with Fetch API

Sending custom headers with the Fetch API allows you to include additional information with your request, like authentication tokens or content types.

JavaScript
//server.js const express = require('express'); const app = express();  app.use(express.json()); // Middleware to parse JSON request body  app.post('/test-api', (req, res) => {     console.log('Received Headers:', req.headers);     console.log('Received Body:', req.body);          res.json({ message: 'Headers received successfully!', receivedHeaders: req.headers }); });  const PORT = 3000; app.listen(PORT, () => {     console.log(`Server running on http://localhost:${PORT}`); }); 
JavaScript
//client.js fetch('http://localhost:3000/test-api', {     method: 'POST',     headers: {         'Content-Type': 'application/json',         'Authorization': 'Bearer my-secret-token',         'Custom-Header': 'HelloWorld'     },     body: JSON.stringify({ message: 'Hello API!' }) }) .then(response => response.json()) .then(data => console.log('Response:', data)) .catch(error => console.error('Error:', error)); 
Screenshot-2025-02-13-121558

Sending Custom Headers with Fetch API

  • Purpose of Custom Headers: Custom headers allow clients to send additional information to the server beyond the standard headers. They help in authentication, tracking, and providing metadata about the request.
  • Authentication & Security: Headers like Authorization (e.g., Bearer token) enable secure API access by verifying the client’s identity before processing requests.
  • Content Negotiation: Headers such as Content-Type and Accept define the format of the request and response (e.g., application/json). This ensures proper communication between client and server.
  • Custom Headers for API Enhancements: APIs can define non-standard headers (e.g., X-Client-Version) to send extra information like app version, request source, or debugging data.
  • Server-Side Header Handling: The server extracts, validates, and processes headers before executing the request. Logging headers helps in monitoring and debugging API interactions.

Handling Different Request Methods (POST, PUT, DELETE)

1. GET Request to Retrieve Data

Fetching a list of items from an API.

JavaScript
fetch('https://fakestoreapi.com/products/1')     .then(response => response.json())     .then(items => console.log(items)); 
Screenshot-2025-01-23-125201

GET Request to Retrieve Data

  • fetch() sends the GET request to the specified URL.
  • The response.json() method parses the JSON response.
  • .then() logs the list of items once they are fetched.

2. POST Request to Submit Data

Sending data to an API using POST.

JavaScript
const data = { name: 'Pranjal', age: 25 }; fetch('https://fakestoreapi.com/products', {     method: 'POST',     headers: { 'Content-Type': 'application/json' },     body: JSON.stringify(data) })     .then(response => response.json())     .then(result => console.log(result)); 
  • The method: ‘POST’ tells Fetch to send data to the server.
  • The headers include the Content-Type to indicate we are sending JSON.
  • The body contains the data to be sent, which is stringified using JSON.stringify().
Screenshot-2025-01-23-130059

POST Request to submit data

3. PUT Request to Update Data

Updating existing user information.

JavaScript
const updatedData = { id: 1, price: 300 };  fetch('https://fakestoreapi.com/products/1', {     method: 'PUT',     headers: { 'Content-Type': 'application/json' },     body: JSON.stringify(updatedData) })     .then(response => response.json())     .then(result => console.log(result)); 
  • The method: ‘PUT‘ indicates we are updating data.
  • The body sends the updated data, converted to JSON.
  • The response is parsed as JSON, and the updated result is logged.
Screenshot-2025-01-23-152657

PUT Request to Update Data

4. DELETE Request to Remove Data

Deleting a user from an API.

JavaScript
fetch('https://fakestoreapi.com/products/1', {     method: 'DELETE'   })     .then(response => response.json())     .then(result => console.log('Deleted:', result));    
Screenshot-2025-01-23-153110

DELETE Request to Remove Data

  • method: ‘DELETE’ indicates that we want to delete the specified resource.
  • The response is parsed as JSON to confirm the deletion.
  • The result is logged to indicate the operation was successful.

Handling Errors in Fetch API

When making requests with fetch(), errors can occur due to network issues or invalid responses. Proper error handling ensures a smooth user experience.

JavaScript
fetch('https://api.example.com/data')   .then(response => {       if (!response.ok) {           throw new Error(`HTTP error! Status: ${response.status}`);       }       return response.json();   })   .then(data => console.log('Data:', data))   .catch(error => console.error('Fetch error:', error.message)); 
Screenshot-2025-02-13-123229

Handling Errors in Fetch API

  • Fetching Data: The fetch(‘https://api.example.com/data’) call requests data from the API.
  • Checking for Errors: The .then(response => { … }) block checks if response.ok is true. If not, it throws an error with the status code.
  • Parsing JSON: If successful, response.json() converts the response into JSON format.
  • Logging Data: The .then(data => console.log(‘Data:’, data)) logs the received data.
  • Handling Errors: The .catch(error => console.error(‘Fetch error:’, error.message)) captures and logs errors.

Conclusion

The Fetch API is a powerful tool for making HTTP requests in JavaScript. It simplifies working with asynchronous data and provides flexibility in handling various request types.

Key Takeaways

  • fetch() makes HTTP requests easier.
  • Use .then() or async/await to process responses.
  • Always check response.ok before parsing data.
  • Handle errors properly using .catch() or try-catch.
  • Customize requests with headers, methods, and body options.


Next Article
Asynchronous JavaScript

T

tarun007
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Methods

Similar Reads

  • How to connect to an API in JavaScript ?
    An API or Application Programming Interface is an intermediary which carries request/response data between the endpoints of a channel. We can visualize an analogy of API to that of a waiter in a restaurant. A typical waiter in a restaurant would welcome you and ask for your order. He/She confirms th
    5 min read
  • How to Fetch XML with Fetch API in JavaScript ?
    The JavaScript fetch() method retrieves resources from a server and produces a Promise. We will see how to fetch XML data with JavaScript's Fetch API, parse responses into XML documents, and utilize DOM manipulation for streamlined data extraction with different methods. These are the following meth
    3 min read
  • What is the use of the Fetch API in JavaScript ?
    The Fetch API in JavaScript provides a modern, powerful, and flexible way to make HTTP requests from web browsers or Node.js environments. Its primary purpose is to facilitate fetching resources, typically data, from servers or other sources across the web. In simple terms, the Fetch API in JavaScri
    2 min read
  • Async and Await in JavaScript
    Async and Await in JavaScript is used to simplify handling asynchronous operations using promises. By enabling asynchronous code to appear synchronous, they enhance code readability and make it easier to manage complex asynchronous flows. [GFGTABS] JavaScript async function fetchData() { const respo
    3 min read
  • Asynchronous JavaScript
    Asynchronous JavaScript is a programming approach that enables the non-blocking execution of tasks, allowing concurrent operations, improved responsiveness, and efficient handling of time-consuming operations in web applications, JavaScript is a single-threaded and synchronous language. The code is
    2 min read
  • How To Use JavaScript Fetch API To Get Data?
    An API is a set of rules, protocols, and tools that allows different software applications to communicate with each other. One of the popular ways to perform API requests in JavaScript is by using Fetch API. What is the Fetch API?The Fetch API is a built-in JavaScript feature that allows you to make
    4 min read
  • How to use JavaScript Fetch API to Get Data ?
    The Fetch API provides a JavaScript interface that enables users to manipulate and access parts of the HTTP pipeline such as responses and requests.  Fetch API has so many rich and exciting options like method, headers, body, referrer, mode, credentials, cache, redirect, integrity, and a few more. H
    2 min read
  • How to use Ejs in JavaScript ?
    EJS or Embedded Javascript Templating is a templating engine used by Node.js. The template engine helps to create an HTML template with minimal code. Also, it can inject data into the HTML template on the client side and produce the final HTML. Installation StepsInstall the module using the followin
    3 min read
  • Working with APIs in JavaScript
    An API is simply a medium to fetch or send data between interfaces. Let's say you want to make an application that provides the user with some real-time data fetched from the server or maybe even allows you to modify or add data to some other endpoint. This is made possible by the API or the Applica
    5 min read
  • JavaScript- Read CDATA in XML
    CDATA sections in XML are used to include text that shouldn't be parsed by the XML parser, such as special characters or reserved words. You can read CDATA content in JavaScript by parsing the XML and accessing the content. Parse XML and Read CDATAIn this method, we parse an XML string using the DOM
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences