JavaScript Fetch API Tutorial
Quick Answer
The Fetch API provides a modern, promise-based way to make asynchronous HTTP requests in JavaScript. It simplifies fetching resources like JSON data from servers and handling responses with clean syntax and better error handling compared to older methods like XMLHttpRequest.
Learning Objectives
- Explain the purpose of Fetch API in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Fetch API.
- Apply Fetch API in a simple real-world scenario or practice task.
Introduction
The Fetch API is a modern interface for making HTTP requests in JavaScript. It replaces older techniques like XMLHttpRequest with a cleaner, promise-based syntax.
This tutorial will guide you through the basics of using Fetch to request data from servers, handle responses, and manage errors effectively.
Fetch API: Modern, simple, and promise-based network requests.
What is the Fetch API?
Fetch is a browser API that allows you to make network requests similar to XMLHttpRequest but with a simpler and more powerful interface.
It returns promises, enabling easier chaining and asynchronous code management.
- Introduced as a modern alternative to XMLHttpRequest.
- Uses promises for asynchronous operations.
- Supports various request methods like GET, POST, PUT, DELETE.
- Works well with JSON and other response types.
Basic Usage of Fetch
To fetch a resource, call fetch() with the URL. It returns a promise that resolves to a Response object.
You can then extract the data from the response, commonly using response.json() for JSON data.
Example: Fetching JSON Data
Here is a simple example that fetches JSON data from an API and logs it to the console.
Handling Responses and Errors
Fetch only rejects a promise if a network error occurs. It does not reject on HTTP error statuses like 404 or 500.
You need to check the response.ok property to handle HTTP errors explicitly.
- Check response.ok to verify successful responses.
- Use response.status to get the HTTP status code.
- Catch network errors with .catch() on the promise.
Advanced Fetch Options
Fetch supports additional options such as method, headers, body, mode, credentials, and cache to customize requests.
This allows you to perform POST requests, send JSON payloads, and control CORS behavior.
- method: HTTP method like GET, POST, PUT, DELETE.
- headers: Custom headers as an object.
- body: Data sent with POST or PUT requests.
- mode: Controls CORS mode (cors, no-cors, same-origin).
- credentials: Include cookies with requests.
Practical Example
This example fetches JSON data from an API, checks for HTTP errors, parses the JSON, and logs the data or errors.
This example sends a POST request with JSON data and handles the response.
Examples
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.status);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));This example fetches JSON data from an API, checks for HTTP errors, parses the JSON, and logs the data or errors.
fetch('https://api.example.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'John', age: 30 })
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));This example sends a POST request with JSON data and handles the response.
Best Practices
- Always check response.ok to handle HTTP errors.
- Use .catch() to handle network errors.
- Set appropriate headers, especially Content-Type for POST requests.
- Use async/await syntax for cleaner asynchronous code.
- Avoid sending sensitive data without HTTPS.
Common Mistakes
- Assuming fetch rejects on HTTP error status codes.
- Not parsing the response body before using it.
- Forgetting to set Content-Type header when sending JSON.
- Ignoring network errors by not using .catch().
- Using fetch in environments without polyfills or support.
Hands-on Exercise
Fetch and Display JSON Data
Write a function that fetches JSON data from a public API and logs the result to the console, handling HTTP and network errors.
Expected output: JSON data logged or error message printed.
Hint: Use fetch(), check response.ok, parse JSON, and catch errors.
Send a POST Request
Create a function that sends a POST request with JSON data to a test API endpoint and logs the response.
Expected output: Response data logged or error message printed.
Hint: Set method to 'POST', include headers and body as JSON string.
Interview Questions
What does the Fetch API return?
InterviewThe Fetch API returns a promise that resolves to a Response object representing the response to the request.
How do you handle HTTP errors with Fetch?
InterviewYou check the response.ok property or response.status code after the promise resolves to detect HTTP errors, since fetch only rejects on network errors.
Can Fetch be used to send POST requests?
InterviewYes, by passing an options object with method set to 'POST' and including a body, you can send POST requests with Fetch.
MCQ Quiz
1. What is the best first step when learning Fetch API?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Fetch API?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. The Fetch API provides a modern, promise-based way to make asynchronous HTTP requests in JavaScript.
B. Fetch API never needs examples
C. Fetch API is unrelated to practical work
D. Fetch API should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- The Fetch API provides a modern, promise-based way to make asynchronous HTTP requests in JavaScript.
- It simplifies fetching resources like JSON data from servers and handling responses with clean syntax and better error handling compared to older methods like XMLHttpRequest.
- The Fetch API is a modern interface for making HTTP requests in JavaScript.
- It replaces older techniques like XMLHttpRequest with a cleaner, promise-based syntax.
- This tutorial will guide you through the basics of using Fetch to request data from servers, handle responses, and manage errors effectively.
Summary
The Fetch API is a powerful and modern way to perform HTTP requests in JavaScript using promises.
It simplifies asynchronous network calls and provides flexible options for different request types.
Proper error handling and response parsing are essential for robust applications using Fetch.
Frequently Asked Questions
Does Fetch work in all browsers?
Most modern browsers support Fetch, but older browsers may require polyfills.
How do I send form data with Fetch?
You can send form data by creating a FormData object and passing it as the body in the fetch options.
Is Fetch synchronous or asynchronous?
Fetch is asynchronous and returns a promise that resolves when the response is available.


