[Go to site: main page, start]

0% found this document useful (0 votes)
8 views6 pages

JavaScript Fetch API Overview and Examples

The Fetch API is a modern JavaScript interface for making asynchronous HTTP requests to servers, supporting methods like GET, POST, PUT, and DELETE. It returns a Promise that resolves to a Response object, allowing for easy handling of responses and errors. The API is simpler than XMLHttpRequest, supports async/await, but has limitations such as not automatically rejecting HTTP errors.

Uploaded by

sumit.patial
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views6 pages

JavaScript Fetch API Overview and Examples

The Fetch API is a modern JavaScript interface for making asynchronous HTTP requests to servers, supporting methods like GET, POST, PUT, and DELETE. It returns a Promise that resolves to a Response object, allowing for easy handling of responses and errors. The API is simpler than XMLHttpRequest, supports async/await, but has limitations such as not automatically rejecting HTTP errors.

Uploaded by

sumit.patial
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🧠 Detailed Notes on JavaScript Fetch API

🔹 What is Fetch API?


The Fetch API is a modern JavaScript interface used to make HTTP requests (like GET, POST,
PUT, DELETE, etc.) to servers.​
It is used to fetch resources (such as JSON data, text, images, etc.) from a web server or API
endpoint.

Fetch API is promise-based, meaning it works asynchronously and avoids callback hell (which
was common with older XMLHttpRequest).

🔹 Basic Syntax
fetch(url, options)
.then(response => {
// handle response
})
.catch(error => {
// handle error
});

●​ url → The address (API endpoint) you want to fetch data from.​

●​ options → (Optional) Configuration object that defines the request method, headers,
body, etc.​

🔹 Example 1: Simple GET Request


fetch('[Link]
.then(response => [Link]()) // converts response to JSON
.then(data => [Link](data)) // handles the JSON data
.catch(error => [Link]('Error:', error));

Explanation:
1.​ fetch() sends an HTTP request to the given URL.​

2.​ The first .then() handles the response object and converts it to JSON using
[Link]().​

3.​ The second .then() works with the actual JSON data.​

4.​ The .catch() handles any network or connection errors.​

🔹 Example 2: POST Request (Sending Data to Server)


fetch('[Link] {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: [Link]({
name: 'John Doe',
age: 25
})
})
.then(response => [Link]())
.then(data => [Link]('Success:', data))
.catch(error => [Link]('Error:', error));

Explanation:

●​ method: 'POST' → Specifies that this is a POST request.​

●​ headers → Used to set the content type of the request.​

●​ body → Contains the data sent to the server, converted to a JSON string.​

🔹 Response Object
When fetch() resolves successfully, it returns a Response object that includes:

●​ [Link] → Boolean (true if response status is 200–299).​

●​ [Link] → HTTP status code (e.g., 200, 404, 500).​

●​ [Link]() → Reads and parses the response body as JSON.​

●​ [Link]() → Reads response as plain text.​

●​ [Link]() → For binary data (images, files, etc.).​

🔹 Example 3: Handling Response Status


fetch('[Link]
.then(response => {
if (![Link]) {
throw new Error(`HTTP error! Status: ${[Link]}`);
}
return [Link]();
})
.then(data => [Link](data))
.catch(error => [Link]('Fetch failed:', error));

🔹 Example 4: Using async / await with Fetch


Using async and await makes the code more readable and synchronous-like.

async function getUserData() {


try {
const response = await fetch('[Link]
if (![Link]) {
throw new Error(`HTTP error! status: ${[Link]}`);
}
const data = await [Link]();
[Link](data);
} catch (error) {
[Link]('Error fetching data:', error);
}
}

getUserData();

Advantages:

●​ Easier to read and debug.​

●​ Uses try...catch for error handling instead of .catch() chaining.​

🔹 Example 5: PUT and DELETE Requests


PUT (update data):

fetch('[Link] {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: [Link]({ name: 'Updated User', age: 26 })
})
.then(res => [Link]())
.then(data => [Link]('Updated:', data))
.catch(err => [Link](err));

DELETE (remove data):

fetch('[Link] {
method: 'DELETE'
})
.then(res => [Link]())
.then(data => [Link]('Deleted:', data))
.catch(err => [Link](err));
🔹 Advantages of Fetch API
✅ Simpler and cleaner syntax than XMLHttpRequest​
✅ Returns Promises (easier async handling)​
✅ Supports all HTTP methods​
✅ Can be used with async/await​
✅ Built into all modern browsers

🔹 Limitations
❌ Doesn’t automatically reject HTTP errors (like 404 or 500) — you must check [Link]
❌ Doesn’t support request timeout natively (you must use AbortController).​
manually.​

❌ Limited browser support in very old versions (e.g., IE).

🔹 Example 6: Using AbortController (Optional Advanced)


You can cancel a fetch request using the AbortController.

const controller = new AbortController();


const signal = [Link];

fetch('[Link] { signal })
.then(response => [Link]())
.then(data => [Link](data))
.catch(err => {
if ([Link] === 'AbortError') {
[Link]('Fetch aborted');
} else {
[Link]('Error:', err);
}
});

// Abort the fetch after 3 seconds


setTimeout(() => [Link](), 3000);
🔹 Real-Life Example
Fetching weather data from an API:

async function getWeather(city) {


try {
const response = await
fetch(`[Link]
=YOUR_API_KEY`);
const data = await [Link]();
[Link](`Weather in ${city}:`, [Link][0].description);
} catch (error) {
[Link]('Error fetching weather data:', error);
}
}

getWeather('Delhi');

🏁 Summary
Feature Description

API Type Promise-based

Used For Making HTTP requests

Common Methods GET, POST, PUT, DELETE

Response .json(), .text(), .blob()


Handling

Error Handling Check [Link] and use


catch()

Async Syntax Works well with async/await

You might also like