Chapter 4.1: Fetch API Basics
Study time: 45 minutes
1. Fetch API: The "Main Antenna" of Mission Control
Imagine that your Mission Control Center has a huge radio antenna for communicating with spacecraft. You can tune it to the right frequency, send a command, and wait for a response.
Fetch API is the same kind of "built-in antenna" in modern browsers. It is a standard JavaScript interface for making HTTP requests to servers. It allows you to:
- 📡 Send "commands" (GET, POST, PUT, DELETE) to our API.
- 🛰️ Receive "telemetry" (JSON data) from the server.
- ⚙️ Work asynchronously, without "freezing" the user interface while waiting for a response.
💡 Space analogy:
fetch()
is the command "Antenna, establish communication!". You pass it:
- Target coordinates (the URL of our API).
- Command type (method: GET, POST).
- Command content (request body, headers).
In return, you don't get the data itself, but a Promise that the data will arrive.
2. Asynchrony: Communication at the speed of light
Communicating with a distant spacecraft takes time. You can't just stop all work at Mission Control and wait for a response. You send a command and continue working, and when the response arrives, the system will notify you.
This is asynchrony. JavaScript does not block the execution of the rest of the code while waiting for a response from the server. To manage this process, the Fetch API uses Promises.
A Promise is a "receipt" that you have sent a request. It has three states:
pending
: The signal is still on its way.fulfilled
: The response was received successfully!rejected
: An error occurred (e.g., no connection).
3. First request: Let's find out where the ISS is
Let's send our first request using fetch
. We will use a simple HTML file and <script>
tags.
Step 1: Create index.html
Create an index.html
file in a new folder (e.g., frontend_fleet_control
).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mission Control - Fetch API</title>
</head>
<body>
<h1>ISS Communication Status</h1>
<div id="iss-status">Waiting for data...</div>
<script>
// Our JavaScript code will be here
</script>
</body>
</html>
Step 2: Write the code with fetch
Inside the <script>
tag, let's add our first fetch
request to the public Open Notify API.
// index.html -> <script>
const issApiUrl = 'http://api.open-notify.org/iss-now.json';
const statusDiv = document.getElementById('iss-status');
console.log('Sending request to get ISS coordinates...');
fetch(issApiUrl)
.then(response => {
// The first .then() handles the HTTP response itself
console.log('Received response from server!', response);
// Convert the response body to JSON, this is also an asynchronous operation
return response.json();
})
.then(data => {
// The second .then() gets the already parsed JSON data
console.log('Data successfully converted to JSON!', data);
const position = data.iss_position;
statusDiv.innerHTML = `The ISS is currently here:
<strong>Latitude:</strong> ${position.latitude},
<strong>Longitude:</strong> ${position.longitude}`;
})
.catch(error => {
// .catch() will trigger if a network error occurs
console.error('Error communicating with the ISS!', error);
statusDiv.textContent = 'Could not retrieve data. Check your connection.';
});
fetch(url)
: Sends a GET request. Returns a promise..then(callback)
: Executes when the promise is successfully resolved (fulfilled
). The first.then
receives aResponse
object.response.json()
: A method that reads the response body and parses it as JSON. It also returns a promise!.catch(callback)
: Executes if the promise is rejected, for example, due to a network error.
Step 3: Open in browser
Just open the index.html
file in your browser. You should see "Waiting for data..." change to the current coordinates of the ISS. Open the developer console (F12) to see the logs.
4. "What if...": Handling server errors
What if we request a non-existent URL?
fetch('http://api.open-notify.org/non-existent-endpoint')
fetch
is designed so that .catch()
will only trigger on network errors (no internet, DNS not found). But responses with codes 404
or 500
are a successfully received response for fetch
! It just contains an error code.
The correct way to check:
fetch('http://api.open-notify.org/non-existent-endpoint')
.then(response => {
// Check the .ok property, which is true for statuses 200-299
if (!response.ok) {
// If the response is not "OK", create our own error to go to .catch()
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('An error occurred while executing the request:', error);
});
response.ok
: This is your main indicator of success.throw new Error()
: We manually "fail" the promise chain to get to the.catch
block.
Quiz to consolidate
🚀 Chapter summary:
You have configured the "main antenna" of your Mission Control and learned how to send requests and receive responses.
- 📡 You have mastered the basic syntax of
fetch()
. - 🛰️ You understand what Promises are and how to work with
.then()
and.catch()
. - ⚙️ You have learned how to correctly handle server responses by checking
response.ok
.
Communication established! In the next chapter, we will connect our Mission Control to the space fleet API that we created with FastAPI, and learn how to get and display a list of our ships.
📌 Check:
- Make sure your
index.html
file correctly displays the ISS coordinates.- Try to intentionally break the URL and see what error is displayed in the developer console.
⚠️ If the code doesn't work:
- CORS Error: If you are trying to make a request to your local FastAPI API (e.g.,
http://127.0.0.1:8000
) from a file opened asfile:///...
, the browser will block the request due to the CORS security policy. We will solve this problem in the next chapter. For now, we are using public APIs that allow this.- HTTP/HTTPS:
http://api.open-notify.org
works over HTTP. Some browsers may warn about this. If you are working from an HTTPS site, requests to HTTP resources may be blocked.