A minimal example showing how to use the Fetch API with Flask. This demo shows how to make a simple request from a webpage to a Flask backend.
- Displays a webpage with a button
- When clicked, fetches a message from the Flask server
- Displays the response on the page
.
├── README.md
├── app.py
├── requirements.txt
└── templates/
└── index.html
-
Install Python requirements:
pip install -r requirements.txt
-
Run the Flask app:
python app.py
-
Open your browser to
http://127.0.0.1:5000
- Creates a Flask server with two routes:
/serves the main webpage/helloreturns a simple greeting
- Shows a button that triggers a fetch request
- Uses the Fetch API to make a request to
/hello - Displays the server's response in a paragraph element
The JavaScript code can be written in two equivalent ways. Here's the traditional function notation with detailed comments:
function sayHello() {
fetch('/hello') // Makes GET request to /hello endpoint
.then(function(response) { // Handles the response
return response.text(); // Converts response to text
})
.then(function(text) { // Handles the text
document.getElementById('message').textContent = text; // Updates page
});
}And here's the same code using modern arrow function notation, which is more concise:
function sayHello() {
fetch('/hello') // Makes GET request to /hello endpoint
.then(response => response.text()) // Arrow function to handle response
.then(text => document.getElementById('message').textContent = text); // Arrow function to update page
}Both versions do exactly the same thing:
- Makes a GET request to the
/helloendpoint - Converts the response to text
- Updates the page by setting the text content of the element with id="message"
The arrow function notation (=>) is a shorter way to write functions in JavaScript. It's particularly useful for short callback functions like these. The two notations are equivalent, but arrow functions are more commonly used in modern JavaScript.
- Basic Flask route setup
- Simple HTML structure
- How to use the Fetch API
- Handling responses from a server
- Updating webpage content with JavaScript
Try modifying the code to:
- Return different types of messages
- Add more buttons with different actions
- Style the page with CSS
- Add error handling
- Return JSON data instead of plain text
For more information about the Fetch API: