๐Ÿงฐ Web APIs
Estimated reading: 4 minutes 13 views

๐Ÿ”„ JavaScript Fetch API Guide (2025) โ€“ GET, POST, JSON, Headers


๐Ÿงฒ Introduction โ€“ Why Use the Fetch API?

Need to get data from an API or submit a form without reloading the page? Welcome to the Fetch APIโ€”the modern, promise-based way to perform AJAX requests in JavaScript.

Unlike the older XMLHttpRequest, the fetch() method is more powerful, readable, and integrated with Promises, making asynchronous calls cleaner and easier to manage.

By the end of this article, youโ€™ll be able to:

โœ… Use fetch() to make GET, POST, PUT, and DELETE requests
โœ… Send and receive JSON data
โœ… Handle HTTP headers, status codes, and errors gracefully
โœ… Apply best practices for performance and security


๐Ÿ”ง What Is the Fetch API?

The Fetch API is a modern interface that lets you make HTTP requests to servers (like REST APIs) from your frontend JavaScript.

fetch(url, options);

๐Ÿ“˜ Note: fetch() always returns a Promise, resolving to the response of the request.


๐ŸŒ Basic Fetch GET Request

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

โœ… Explanation:

  • fetch() sends the request to the given URL.
  • .json() parses the response into a usable JavaScript object.
  • .catch() handles network or parsing errors.

๐Ÿ’ก Tip: Always include .catch() to avoid unhandled promise rejections.


โœ‰๏ธ POST Request with JSON Body

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'Learn Fetch API',
    body: 'It is easy and modern!',
    userId: 1
  })
})
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

โœ… Explanation:

  • method: HTTP method (GET, POST, etc.)
  • headers: Sets the request type (like JSON)
  • body: Serialized data using JSON.stringify()

๐Ÿ“˜ Note: Headers must match the content type youโ€™re sending.


๐Ÿ” Handling HTTP Response Status Codes

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))
  .catch(error => console.error('Fetch failed:', error));

โœ… Explanation:

  • response.ok is true for 200โ€“299 status codes.
  • Use response.status to inspect HTTP codes like 404 or 500.

โš ๏ธ Warning: fetch() only rejects promises on network failure, not on HTTP errorsโ€”you must check manually.


๐Ÿงช Common HTTP Methods with Fetch

MethodUse Case
GETRetrieve data
POSTCreate a new resource
PUTUpdate an existing resource
PATCHPartial update of a resource
DELETERemove a resource

๐Ÿ” Custom Headers & Authorization

Example with Bearer Token

fetch('https://api.example.com/user', {
  headers: {
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
  }
})
  .then(res => res.json())
  .then(data => console.log(data));

โœ… Use Case: When working with protected APIs (e.g., JWT auth).


๐Ÿ“‚ Uploading Files with Fetch

const formData = new FormData();
formData.append('avatar', fileInput.files[0]);

fetch('/upload', {
  method: 'POST',
  body: formData
})
  .then(res => res.json())
  .then(result => console.log(result));

๐Ÿ“˜ Note: Do not set Content-Type header manually with FormData; the browser will handle it.


๐Ÿ” Async-Await with Fetch

async function loadData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/2');
    if (!response.ok) throw new Error('Failed to fetch!');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
loadData();

โœ… Explanation:

  • async/await makes the syntax cleaner.
  • try/catch is used for error handling.

๐ŸŒ CORS (Cross-Origin Resource Sharing)

If you see errors like:

Access to fetch at 'https://api.domain.com' has been blocked by CORS policy

๐Ÿ” This means the server must explicitly allow your origin using response headers like:

Access-Control-Allow-Origin: *

๐Ÿ’ก Tip: Use a proxy or CORS-enabled backend for local development.


๐Ÿ“Š Comparison: Fetch API vs XMLHttpRequest

Featurefetch() โœ…XMLHttpRequest โŒ
Modern APIโœ… YesโŒ No
Returns Promisesโœ… YesโŒ No (uses events)
Streaming Supportโœ… YesโŒ No
Code Simplicityโœ… SimpleโŒ Verbose
Built-in JSON parseโœ… EasyโŒ Manual

๐Ÿง  Best Practices

๐ŸŸฉ Recommended:

  • โœ… Always handle .catch() or use try/catch
  • โœ… Use response.ok for HTTP validation
  • โœ… Set correct Content-Type headers
  • โœ… Use async/await for cleaner code

๐ŸŸฅ Avoid:

  • โŒ Assuming fetch() fails on HTTP error
  • โŒ Sending unstringified objects in body
  • โŒ Ignoring CORS policies during integration

โ“ FAQ โ€” JavaScript Fetch API


โ“ Does fetch() replace XMLHttpRequest?
โžก๏ธ Yes. It’s the modern replacement, more powerful and Promise-based.


โ“ Can I send files using fetch()?
โžก๏ธ Yes, using FormData.


โ“ Does fetch() support timeout?
โžก๏ธ Not natively. You can create one manually using AbortController.


โ“ Is fetch() supported in all browsers?
โžก๏ธ Yes, except Internet Explorer. Use a polyfill if needed.


โ“ How to send custom headers with fetch()?
โžก๏ธ Use the headers object in the options parameter.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Fetch API

Or Copy Link

CONTENTS
Scroll to Top