Making Network Requests and Handling APIs with Fetch
In modern web development, interacting with external APIs is a common task. The Fetch API is a modern and powerful method for making network requests, fetching data from external servers, and working with APIs. This module will introduce you to the Fetch API, explain how it works, and show you how to use it effectively in JavaScript.
Table of Contents
- What is the Fetch API?
- Syntax of Fetch API
- Making a GET Request
- Making a POST Request
- Handling JSON Responses
- Handling Errors with Fetch
- Using Async/Await with Fetch
- Handling Multiple Requests (Parallel Requests)
- CORS (Cross-Origin Resource Sharing)
- Practical Example
- Conclusion
1. What is the Fetch API?
The Fetch API is a modern browser API used for making HTTP requests in JavaScript. It provides a more powerful and flexible way to interact with REST APIs or other network resources compared to the older XMLHttpRequest
method.
The Fetch API returns a Promise that resolves to the Response object representing the response to the request.
2. Syntax of Fetch API
The syntax for the Fetch API is straightforward. It accepts the URL of the resource you want to fetch and an optional configuration object to define the request method (GET, POST, etc.) and other settings.
Basic syntax:
fetch(url, options)
.then(response => response.json()) // Parse JSON response
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
- url: The URL of the resource you want to fetch.
- options: (optional) An object that specifies the request method, headers, body, etc.
3. Making a GET Request
A GET request is used to retrieve data from a server. It is the most common type of request when working with APIs. Here’s how you can make a simple GET request using Fetch:
Example:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.log('Fetch error:', error));
In this example:
- We use the
fetch
function to request data from an API. - We check if the response is successful using
response.ok
before attempting to parse the response as JSON. - If successful, the JSON data is logged to the console.
4. Making a POST Request
A POST request is used to send data to a server, such as submitting form data. You can use the Fetch API to send data by setting the method
to POST
and including the data in the body
of the request.
Example:
const data = {
name: 'John Doe',
email: '[email protected]'
};
fetch('https://api.example.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => console.log('Success:', result))
.catch(error => console.error('Error:', error));
In this example:
- We send a POST request with the
method: 'POST'
option. - The
headers
indicate that the body is in JSON format ('Content-Type': 'application/json'
). - The
body
contains the data to be sent, which is stringified usingJSON.stringify()
.
5. Handling JSON Responses
Most APIs return data in JSON format, which you need to parse into a JavaScript object to work with it. This is done using response.json()
.
Example:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data); // Now data is a JavaScript object
})
.catch(error => console.log('Error:', error));
6. Handling Errors with Fetch
The Fetch API doesn’t automatically throw an error for non-2xx HTTP responses (e.g., 404 or 500). To handle errors properly, you need to check the response status explicitly.
Example:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
In this example, if the response status is not ok, an error is thrown, which is then caught in the catch
block.
7. Using Async/Await with Fetch
async/await
is a more modern and cleaner way of handling asynchronous code in JavaScript. It works with Promises and provides a more synchronous-looking structure, making the code easier to read and maintain.
Example with async/await
:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
- The
async
keyword makes the function asynchronous, andawait
pauses the execution of the function until the Promise is resolved. - The
try/catch
block handles errors effectively.
8. Handling Multiple Requests (Parallel Requests)
You can make multiple API requests in parallel using Promise.all()
. This allows you to run multiple fetch calls at once and wait for all of them to resolve.
Example:
async function fetchMultipleData() {
try {
const [data1, data2] = await Promise.all([
fetch('https://api.example.com/data1').then(res => res.json()),
fetch('https://api.example.com/data2').then(res => res.json())
]);
console.log(data1, data2);
} catch (error) {
console.error('Error:', error);
}
}
fetchMultipleData();
- The
Promise.all()
method ensures all the fetch requests are processed simultaneously, which can improve performance.
9. CORS (Cross-Origin Resource Sharing)
When making requests to an API from a different domain, you might encounter CORS (Cross-Origin Resource Sharing) issues. This occurs when the API does not allow requests from different origins for security reasons.
To solve CORS issues:
- The server must include the correct CORS headers to allow the request from a different origin.
- You can also use a proxy server to avoid direct cross-origin requests.
Example of CORS headers on the server:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST
10. Practical Example
Let’s implement a practical example where we fetch a list of users from an API and display the data on the page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fetch API Example</title>
</head>
<body>
<ul id="userList"></ul>
<script>
async function fetchUsers() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await response.json();
const userList = document.getElementById('userList');
users.forEach(user => {
const li = document.createElement('li');
li.textContent = user.name;
userList.appendChild(li);
});
} catch (error) {
console.error('Error fetching users:', error);
}
}
fetchUsers();
</script>
</body>
</html>
In this example, we fetch a list of users from an API and display their names in an unordered list on the webpage.
11. Conclusion
The Fetch API is a powerful tool for working with APIs in JavaScript. It makes making HTTP requests simpler and more flexible, allowing you to interact with REST APIs, handle JSON responses, and manage asynchronous code with ease using Promise
and async/await
.